Jul 17, 2024
0
, 1
, or 2
in ascending order.O(n)
and constant space complexity O(1)
.O(n log n)
complexity).O(n log n)
complexity.0
, 1
, and 2
.0
, 1
, and 2
.O(n)
time, O(1)
space for array of size 3.Inspired by the Quicksort Partition method.
Pointers:
left
: Marks the boundary for zeros.right
: Marks the boundary for twos.i
: Iterates through the array.Procedure:
0
, swap it to the position marked by left
and increment left
.2
, swap it with right
and decrement right
.i
unless you performed a swap with right
(to check the swapped value).Edge Cases: Swapping might bring a zero in the middle; hence the increment logic.
sortColors(nums)
function containing helper swap(i, j)
function for swapping.left
and right
, with i
traversing the array.left
and right
pointers based on the current value of nums[i]
.i
surpasses right
as remaining elements will already be sorted (all twos after right
).class Solution:
def sortColors(self, nums: List[int]) -> None:
def swap(i, j):
nums[i], nums[j] = nums[j], nums[i]
left, right = 0, len(nums) - 1
i = 0
while i <= right:
if nums[i] == 0:
swap(i, left)
left += 1
elif nums[i] == 2:
swap(i, right)
right -= 1
i -= 1 # Decrement i to revisit this index in next iteration.
i += 1
O(n)
time complexity and O(1)
space complexity.