You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We are asked to sort an array with 3 possible values. If we use the standard sorting method `Array.sort`, that will be `O(n log n)`. However, we are asked to solve in linear time and constant space complexity.
906
+
907
+
The concept on quicksort can help here. We can choose 1 as a pivot and move everything less than 1 to the left and everything bigger than 1 to the right.
908
+
909
+
*Algorithm*:
910
+
911
+
* Initialize 3 pointers: `left = 0`, `right = len - 1` and `current = 0`.
912
+
* While the `current` pointer is less than `right`
913
+
** If `current` element is less than pivot 1, swap it to the left and increase the `left` and `current` pointer.
914
+
*** We can safely increase the current pointer
915
+
** If `current` element is bigger than pivot 1, swap it to the right and decrease `right` pointer.
916
+
*** Here, we don't increase the `current` pointer because the number that we swapped with could be another 2 and we might need to keep swapping while decreasing `right`.
0 commit comments