The Dutch National Flag Problem (The Quicksort "Band-Aid")

  Рет қаралды 30,723

Back To Back SWE

Back To Back SWE

5 жыл бұрын

Free 5-Day Mini-Course: backtobackswe.com
Try Our Full Platform: backtobackswe.com/pricing
📹 Intuitive Video Explanations
🏃 Run Code As You Learn
💾 Save Progress
❓New Unseen Questions
🔎 Get All Solutions
The relevance of this problem is in its applications to quicksort. If we pick bad pivots for quicksort then we will have a O(n^2) runtime which is very bad.
The way of repartitioning an array as shown in O(n) time aids in this issue of repeated elements in an array being sorted.
You can read more here: en.wikipedia.org/wiki/Dutch_n...
The code for this problem is pretty straightforward to do (just 2 for loops, one going forward and one going backward UNTIL we hit the region less than the pivot). If you really want to see the code, this problem can be found in the amazing book Elements of Programming Interviews by Adnan Aziz as question 6.1
++++++++++++++++++++++++++++++++++++++++++++++++++
Question: Write a program that takes an array A and an index i into A, and rearranges the elements such that
1.) All elements less than A[i] (the "pivot") appear first
2.) Followed by elements equal to the pivot
3.) Followed by elements greater than the pivot
Example
A = [0, 1, 2, 0, 2, 1, 1] (same array)
Pivot Index = 2
Valid Output: [0, 1, 0, 1, 1, 2, 2]
Valid Output: [0, 0, 1, 1, 1, 2, 2] (a more perfect output)
This is called Dutch national flag partitioning because the Dutch national flag consists of three horizontal bands, each in a different color.
We will get an input and attempt to form a 3 section partitioning of the array and will always end up with these 3 sections of "lesser", "equal", and "greater" value UNLESS the value at our partition index is the smallest OR greatest value in the array.
Approach 2
Rather than create extra space, we can just do 2 passes, one forward, and then one backward.
During the forward pass for each element in the array, we will look for an element smaller than the element we are at. If it is smaller we would swap ourselves with that element.
During the backward pass move backward and look for an element larger than the element we are at. If it is larger we will swap ourselves with it.
ALSO, we stop moving backward when the element we stand at is less than the pivot because at the point we know that the partitioning is finished.
Complexities:
Time: O(n^2) + O(n^2) = O(n^2)
2 O(n^2) passes. For each element in the array, we do nearly the whole array of comparisons (triangular number) both for the forwards and backward scans.
Space: O(1)
Approach 3
But we don't need to do a new scan for a smaller or larger element FOR EACH element in the array.
We can just have a placement pointer where we swap in "smaller than pivot" values (for the forward iteration) and a "larger than pivot" placement pointer to swap in larger values.
The values equal to the pivot will end up lying in the middle by themselves.
Example
A = [0, 1, 2, 0, 2, 1, 1]
Pivot Index = 1
Value at pivot index is 1.
Forward pass: (looking to place items less than 1)
i = 0 [0, 1, 2, 0, 2, 1, 1] Swap index 0 with index 0
i = 1 [0, 1, 2, 0, 2, 1, 1] (no swap)
i = 2 [0, 1, 2, 0, 2, 1, 1] (no swap)
i = 3 [0, 0, 2, 1, 2, 1, 1] Swap index 1 with index 3
i = 4 [0, 0, 2, 1, 2, 1, 1] (no swap)
i = 5 [0, 0, 2, 1, 2, 1, 1] (no swap)
i = 6 [0, 0, 2, 1, 2, 1, 1] (no swap)
After backwards pass: (looking to place items greater than 1)
i = 6 [0, 0, 2, 1, 2, 1, 1] (no swap)
i = 5 [0, 0, 2, 1, 2, 1, 1] (no swap)
i = 4 [0, 0, 2, 1, 1, 1, 2] Swap index 4 and index 6
i = 3 [0, 0, 2, 1, 1, 1, 2] (no swap)
i = 2 [0, 0, 1, 1, 1, 2, 2] Swap index 2 and index 5
i = 1 [0, 0, 1, 1, 1, 2, 2] (stop*)
*0 is less than the pivot value of 1 so we are now in the region LESS THAN the pivot that we already created in the front of the array
Complexities:
Time: O(n) + O(n) = O(n)
Forward pass with a backwards pass, both running in linear time
Space: O(1)
No auxiliary spaces is created that scales with the input
++++++++++++++++++++++++++++++++++++++++++++++++++
HackerRank: / @hackerrankofficial
Tuschar Roy: / tusharroy2525
GeeksForGeeks: / @geeksforgeeksvideos
Jarvis Johnson: / vsympathyv
Success In Tech: / @successintech
++++++++++++++++++++++++++++++++++++++++++++
This question is 6.1 in the fantastic book Elements of Programming Interviews by Adnan Aziz.

Пікірлер: 89
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
Table of Contents: Finding A Room...AGAIN 0:00 - 0:26 Introduction To The Problem 0:26 - 1:22 An Example Of The Partitioning 1:22 - 3:59 Some Approaches To The Problem 3:59 - 7:16 Optimal Solution Walkthrough (Forward) 7:16 - 8:36 Optimal Solution Walkthrough (Backward) 8:36 - 9:44 The Final Solution 9:44 - 10:26 The Wrap Up 10:26 - 10:35 This problem has implications in the improvement of quicksort's worst case O(n^2) runtime cases caused by repeated elements (quicksort has poor performance for inputs that have many repeated elements).
@ShubhamSinghYoutube
@ShubhamSinghYoutube 3 жыл бұрын
learning quick sort from A-train , made my day! lol
@BackToBackSWE
@BackToBackSWE 3 жыл бұрын
ye
@clipzone8302
@clipzone8302 3 жыл бұрын
Lol A-train's teaching algorithms after retirement from vought
@kumarshubham9217
@kumarshubham9217 4 жыл бұрын
really appreciate your enthusiasm for teaching..you are a great and honest teacher...you put a lot of energy man! keep it up!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thanks ok
@PiIsRational
@PiIsRational 4 жыл бұрын
I thought I could figure this out because I am comfortable with the partitioning algorithm in the context of quick sort, but I could not. Thanks for the great explanation. Keep up the great work. Learning a ton on this chan.
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
sure
@sachitmohannayak4964
@sachitmohannayak4964 5 жыл бұрын
Wow, this helped me learn the algorithm so quick; the colours are very helpful too.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
hahaha nice, glad it did
@abhinavgupta1492
@abhinavgupta1492 3 жыл бұрын
This cleared my concept, i was stuck at a quick sort problem. THANKS MAN!!
@BackToBackSWE
@BackToBackSWE 3 жыл бұрын
sure
@jeezradz
@jeezradz 4 жыл бұрын
The best video on dutch national flag on youtube so far! Just subscribed!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thanks and welcome
@colemanhoyt5437
@colemanhoyt5437 3 жыл бұрын
The example at the end works so well! Thank you for the explanation!
@OmniscientPotato
@OmniscientPotato 5 жыл бұрын
Thank you for this excellent explanation!
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
thansk
@FrancisGabon
@FrancisGabon 2 жыл бұрын
Really like the tone and style of that channel and his presenter! Thanks a lot, great content.
@zarlorin3728
@zarlorin3728 Жыл бұрын
this guy is more motivated than my prof in any ways
@ananyapamde4514
@ananyapamde4514 3 жыл бұрын
Really like your videos
@69shrutivichare60
@69shrutivichare60 3 жыл бұрын
Thank you so much This is the only HELPFUL video on 3 way quick sort Please make such more videos 🙏
@Ghungroo-Beats
@Ghungroo-Beats 3 жыл бұрын
Great Explanation!
@YavinArba
@YavinArba 4 жыл бұрын
informative and engaging, thanks man
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
sure
@sidhant4674
@sidhant4674 5 жыл бұрын
Great work man!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thanks
@xVermyy
@xVermyy 5 жыл бұрын
Bro, great explanation!
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
Thank you!
@vaibhavsingh755
@vaibhavsingh755 Жыл бұрын
Great Explanation Sir😊
@PankajKumar-hz3oi
@PankajKumar-hz3oi 3 жыл бұрын
thanks, brother, great explanation
@deepaktiwari2847
@deepaktiwari2847 4 жыл бұрын
You were just FANTASTIC !!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thanks
@felixongati1840
@felixongati1840 3 жыл бұрын
One trivial but important optimization, if the position of the current item is on the left of the pivot position, do not swap. i.e. if current_item < pivot and index_current_item < index_pivot, do not swap.
@jacobzhang840
@jacobzhang840 4 жыл бұрын
Great explanation!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thanks
@aribakodes5453
@aribakodes5453 4 жыл бұрын
you are a truly amazing teacher
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thanks
@akashsrivastava8324
@akashsrivastava8324 3 жыл бұрын
Awesome !!!
@chengjiang7051
@chengjiang7051 5 жыл бұрын
Amazing solution
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
thx
@pawehoowicki7940
@pawehoowicki7940 4 жыл бұрын
very nice!!
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
thx
@kumarc4853
@kumarc4853 3 жыл бұрын
thank you
@gamingblast2325
@gamingblast2325 3 жыл бұрын
In second way i dont get why its O(n^2) , is the approach is to select every single element and look to element less than it ?
@khadijakhaldi6468
@khadijakhaldi6468 5 жыл бұрын
Thank you so much for your help! why don't we use the partition step in the quicksort ?
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
I made this a while back, don't remember the problem 😳
@khadijakhaldi6468
@khadijakhaldi6468 5 жыл бұрын
haha it’s ok 😁
@ritikkhatri
@ritikkhatri 3 жыл бұрын
thank you, i couldn't grasp 3 partition before watching.
@BackToBackSWE
@BackToBackSWE 3 жыл бұрын
Glad I could help!
@prathameshpatil6040
@prathameshpatil6040 4 жыл бұрын
Can we not do this in one pass? just swap with back or front pointers as per index value ..
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
Maybe, I dont remember
@AnantChowdhary
@AnantChowdhary 4 жыл бұрын
Yup, we can: public void sortColors(int[] nums) { int filledUpTillFromStart = -1; int filledUpTillFromEnd = nums.length; int i = 0; while(i < nums.length && i < filledUpTillFromEnd) { if(nums[i] == 0) { filledUpTillFromStart++; swap(i, filledUpTillFromStart, nums); if(i == filledUpTillFromStart) i++; } else if(nums[i] == 2) { filledUpTillFromEnd--; swap(i, filledUpTillFromEnd, nums); } else { i++; } } } public void swap(int i, int j, int[] arr) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
@anveshreddy1245
@anveshreddy1245 3 жыл бұрын
Can we apply this algorithm if the arrays number are not only 0 1 2,I mean more unique numbers like array of 1,3,5,6
@okeuwechue9238
@okeuwechue9238 4 ай бұрын
you can replace single-digit values with a RANGE of values i.e. each single digit transforms to a SET of values
@doggo660
@doggo660 5 жыл бұрын
wow good job! Thank you.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
thanks
@doggo660
@doggo660 5 жыл бұрын
@@BackToBackSWE I just have one question. Why is the first approach O(n) space complexity if we're just using 3 arrays? Doesn't memory have to grow by n based on input? In that case it's O(1) I think. Space complexity is pretty confusing and not easy to find on the internet.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
Each array cannot be larger than n. We bound to O(n) asymptotically because the space we use cannot exceed that linear nature on the tail end of a graph of space usage. For time...we are just doing linear time passes. No nested operations that will tie one variable to another. Is this clear? Continue asking questions.
@doggo660
@doggo660 5 жыл бұрын
@@BackToBackSWE Ohh ok I think I understand now. So it's O(n) space complexity since n is the size of the array. Therefore, the space is dependent on the size of what array that has been passed in to the function. So really its O(n) auxiliary space since an array by default has an O(n) space complexity.
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
@@doggo660 yeah.
@nackyding
@nackyding 5 жыл бұрын
Is the second example the bubble sort algorithm?
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
can you timestamp it?
@vitna91
@vitna91 4 жыл бұрын
How do yoi choose the pivot? The value at pivot index should always be 1?
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
can u timestamp? I made this a while back
@vitna91
@vitna91 4 жыл бұрын
7:16
@Dyslexic_Neuron
@Dyslexic_Neuron 5 жыл бұрын
finally !!!
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
hi
@LalitYadav-vi1ul
@LalitYadav-vi1ul 4 жыл бұрын
I think the forward and backward scan and replace is Bentley-McIlory 3-way partitioning. But, nice explanation :)
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
ok
@ashwin-g-1701
@ashwin-g-1701 5 жыл бұрын
There is a better way... You do not need to have a separate forward and backwards pass.... This is how its gonna work: You store the indexes to which we have to take the lower than pivot values to, i.e the green pointer in the end of the video, and also another value that stores the index after which, are the greater than pivot values, i.e the red pointer. Let me just call them green and red indexes for now.... -- Now, when you encounter a value < pivot, exchange with green index, increment green index and go on to check the next value. -- When you encounter a value = pivot, ignore it and move to the next value. -- When you encounter a value > pivot, swap it with red index, and move red index to left, but check the value at that position again with these 3 points(the one which you had swapped for the > pivot value, ie the one that was previously at the red index) This might not make sense at first, but the way it works is that all values between green pointer and the one we are going to check, have been checked before, to be equal to pivot. Just try this for the example in the video... Its a pretty small improvement to reduce array accesses to exactly the size of the array, but its an improvement nonetheless. Sorry if my explanation was too confusing :)
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
nah u good
@snlagr
@snlagr 4 жыл бұрын
every superhero has a basement
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
tru
@yipg2076
@yipg2076 4 жыл бұрын
I think the way you explained from 7:27 is not appropriate in the case like pivot number is 2 (Blue)
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
I dont remember this video too much
@yipg2076
@yipg2076 4 жыл бұрын
@@BackToBackSWE k, don't mind. All your videos are very helpful for me to understand the problem well. Best Regards ;)
@AffairWithGeo
@AffairWithGeo Жыл бұрын
Am i late ?? in learning from you?
@ayusharora2019
@ayusharora2019 3 жыл бұрын
Hey !! Can you please post the code for the same? in Java If possible
@noa.leshem
@noa.leshem Жыл бұрын
i just failed this question in a job interview 🤡 edit: nvm, bombed the question passed the interview
@BackToBackSWE
@BackToBackSWE Жыл бұрын
Congratulations on passing the interview 🎉
@hawksawed
@hawksawed 3 жыл бұрын
4:45 if anyone is trying to see the 3 solutions
@StanOliver1000
@StanOliver1000 4 жыл бұрын
What is so unusual about being in a basement??????
@BackToBackSWE
@BackToBackSWE 4 жыл бұрын
nothing
@StanOliver1000
@StanOliver1000 4 жыл бұрын
@@BackToBackSWE Exactly
@arowa.
@arowa. 5 жыл бұрын
i literally thought that he will start by saying , hey yo my man's here rofl
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
what
@anuragv400
@anuragv400 3 жыл бұрын
Should be Ez for Dutch peoples..
@spk9434
@spk9434 5 жыл бұрын
Awesome !
@BackToBackSWE
@BackToBackSWE 5 жыл бұрын
love.
Dutch National Flag Algorithm. Explained with playing cards.
12:11
IQ Level: 10000
00:10
Younes Zarou
Рет қаралды 12 МЛН
Советы на всё лето 4 @postworkllc
00:23
История одного вокалиста
Рет қаралды 4,7 МЛН
لقد سرقت حلوى القطن بشكل خفي لأصنع مصاصة🤫😎
00:33
Cool Tool SHORTS Arabic
Рет қаралды 29 МЛН
The Change Making Problem - Fewest Coins To Make Change Dynamic Programming
23:12
The N Queens Problem using Backtracking/Recursion - Explained
14:29
Back To Back SWE
Рет қаралды 135 М.
You Are Two
4:58
CGP Grey
Рет қаралды 15 МЛН
The 0/1 Knapsack Problem (Demystifying Dynamic Programming)
20:30
Back To Back SWE
Рет қаралды 203 М.
Oh, wait, actually the best Wordle opener is not “crane”…
10:53
Rotation without rotating.
16:52
Stand-up Maths
Рет қаралды 988 М.
The SAT Question Everyone Got Wrong
18:25
Veritasium
Рет қаралды 12 МЛН
Nokia 3310 top
0:20
YT 𝒯𝒾𝓂𝓉𝒾𝓀
Рет қаралды 4,4 МЛН
Bluetooth connected successfully 💯💯
0:16
Blue ice Comedy
Рет қаралды 2 МЛН
Сколько реально стоит ПК Величайшего?
0:37
Запрещенный Гаджет для Авто с aliexpress 2
0:50
Тимур Сидельников
Рет қаралды 1,1 МЛН
Хакер взломал компьютер с USB кабеля. Кевин Митник.
0:58
Последний Оплот Безопасности
Рет қаралды 2,3 МЛН
iPhone socket cleaning #Fixit
0:30
Tamar DB (mt)
Рет қаралды 19 МЛН