Sort Array by Increasing Frequency - Leetcode 1636 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·1y ago

Key Takeaways

The video demonstrates how to solve the Leetcode 1636 problem, 'Sort Array by Increasing Frequency', using Python and a custom key with a hashmap to calculate frequency.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem sort array by increasing frequency it's funny that this is actually very similar to yesterday's problem and I think I mentioned yesterday or maybe the day before that sometimes you want to sort based on a custom key and languages have a different way of providing that python makes it very very easy I think most languages do have a way of providing that though and this problem can most easily be solved by doing exactly this so first let's get into what the problem is asking cuz it's not super trivial so the idea is we're given an array something like this every single one of these numbers has a frequency so one has a frequency or a count of two actually it appears two times in the input array two shows up three times and three shows up a single time so instead of sorting the input based on the values themselves we want to sort each value based on the frequency of that value so we want to do it in ascending order based on the frequency so one is the lowest frequency that we have and three is the only number with that frequency it could have been possible though that we had multiple numbers maybe four shows up and it has a frequency of one and we'll cover that case in just a second but for now let's consider this three will show up first next we have a count of two one has a count of two so one's going to show up in the output array but not only is it going to show up once it's actually going to show up twice because that's how many times it appeared in the input so we don't want to eliminate duplicates or anything like that and lastly two shows up three times so we we will add three occurrences of two in the output and that's exactly what we're going to return now let's get back into that other case though where suppose we had four and it showed up a single time so now we have two numbers with the exact same frequency so the straightforward thing to do would be to sort them in ascending order so we could have two elements here like the rest of the array was going to look the same we're going to have a one twice and then we're going to have two three times sorry I'll draw it down here so now these are the elements that show up a single time so we could have either put them like this or this three and four or we could put them like four and three the annoying thing about this problem is that they actually want us to do it this way they want us to only put them in decreasing order if there are elements with the same frequency so this is kind of the complicated part about this problem one way to solve it sure we could collect all elements with the same frequency it might not just be one group you can imagine that there could have been multiple sections that have elements with the exact same frequency and they could be very very long so what would you do would you individually sort each of these pieces cuz that's going to be in log in multiple times which I'm not even sure honestly what the Big O time complexity of that would be I think it might still be in login but there is a better solution and it's an easier solution to code up so that's the one I'm going to be showing you the idea is this when you call like a built-in sort method on an input array so if we call builtin sort on the input array we can pass in a custom key key so what do you imagine we want to pass in for the key like if we have an element one what is the Precedence that we want to give it well remember we're sorting based on the frequency so of course let's just calculate the frequency of each element kind of like I did over here the best data structure to use is usually a hashmap for that so that's what we're going to do and then we'll have that mapping so then we'll say okay for the key don't sort it based on the element num sort it based on the count of num or the frequency of num that will get us pretty far that would give us an output that looks like this now obviously there is an issue with this output it's this part where there are duplicates it's kind of unpredictable it'll sort it based on the count and if two elements have the same count we don't know if it's going to give us the desired result so in Python the way to do that is by adding like a second thing like if there's a tie with these okay then sort it based on something else and the second key that we could provide is the number itself if we do that of course though when there's a tie it's going to sort them in ascending order can you think of a possible workaround we want to not do it in ascending order we want to do the opposite and that makes you think okay we'll try to reverse it well that's hard to do we'd have to reverse like each individual portion then but the better way would be if it's by default sorting them in ascending order the second key instead of being the original number itself could be the -1 multiplied by that number or just you know in Python it'll just be the negative of that number so for example like the sort key for four would be this it would be first the count of four which is one and then next it would be the negative of it which is -4 the sort key of three would be one because that's the count of one and then the second sort key would be -3 so first this part will be evaluated like this first it's going to look here okay these two numbers have the same frequency there's a tie so now look at the second which is the negative of each number by default it's going to try to sort them in ascending order so it's going to say put -4 first and then put -3 because -4 is of course smaller than -3 so that means that you know what number had this sort key four had that sort key and three had this sort key therefore this one is going to go first four is going to be first and then three is going to be second so this is generally high level how you do it in Python when I say we're going to provide a sort key in Python we can only provide a tupal so we're going to have like the first part of the sort key and then the second part of the sort key in the form of a tupal in languages like Java I think you actually have to do a bit more work your sort key will be a function that takes in two parameters A and B and you'll have to do some kind of comparison between them so in Java you actually have more precise control over how exactly you want to do it it's just I think a bit more verbose which if you're a Java person I don't think I have to probably tell you that but anyways given that we're just first counting the occurrences of each number then doing the sorting we can implement this in N plus n log n time so that's the time complexity and Big O of n for the space complexity up above so the first thing we want to do is get the count of each character I could do that in a hashmap for you I'm going to assume you probably know how to do that portion though and I have various videos covering how to do that so in Python I'm going to take the shortcut of just calling the counter on this so this will basically create a hashmap counting each element and then we want to take this we want to take the input array nums and sort it and then we want to return it again the hard part is how we want to sort it we can provide a custom key and that can be in the form of a function while it has to be in the form of a function so I'm going to Define that function up above actually think we have to do that we could do a Lambda function but I'm going to Define like a separate function just to kind of make it very very clear what's going on we have a function it's called custom sort I guess it'll take in a single parameter and I don't think we have control over that it has to take in a single parameter which is going to be a number from the and we want to sort it based on the count of that number but if there's a tie with the count of the number we have to have it in a very particular order so we're going to have a second key so if there's a tie with this then it'll use the next element and it's not going to be the number itself it's going to be the negative of the number because we want them to be in descending order and so now for the custom key here all you do is pass in the name of the function you don't have to call the function do not call the function it won't work in that case so this will work I'll show it to you you can see here it works it's pretty efficient if you wanted to rewrite this in the form of a Lambda function AKA an inline function you could do something like this it takes in a parameter let's call it n once again and then it'll return a tupal so this is just like a short hand for what I'm doing up above it'll return a tupal I'll just copy and paste this because the content is going to be the same this is equivalent to what I have up above generally people prefer to write it below but I thought the previous solution was probably more easy to translate into other languages even though most languages probably don't have like a tupal but this also works as you can see here this time it was more efficient but that's pretty random if you found this helpful check out n code. before recording this video I was working on adding some animations to the DSA for beginners course we'll be adding like about 100 animations to that over the next few days looking forward to it and hopefully I'll see you soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/ 🐦 Twitter: https://twitter.com/neetcode1 ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf Problem Link: https://leetcode.com/problems/sort-array-by-increasing-frequency/description/ 0:00 - Read the problem 0:30 - Drawing Explanation 6:07 - Coding Explanation leetcode 1636 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

This video teaches how to solve the Leetcode 1636 problem by sorting an array by increasing frequency using a custom key with a hashmap. The problem requires sorting elements with the same frequency in decreasing order. The video provides a step-by-step solution using Python and explains the time and space complexity of the solution.

Key Takeaways
  1. Call the built-in sort method on the input array with a custom key
  2. Calculate the frequency of each element using a hashmap
  3. Sort elements based on frequency
  4. Count occurrences of each number using a hashmap
  5. Sort the input array using a custom key function
  6. Define a custom key function to sort by frequency and then by negative of the number itself
💡 Using a custom key with a hashmap allows for efficient sorting of the array by frequency, and resolving ties by sorting in decreasing order based on the negative of the number itself.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (3)

Read the problem
0:30 Drawing Explanation
6:07 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →