⬅ Previous Topic
Count Subarrays with Given SumNext Topic ⮕
Two Sum Problem⬅ Previous Topic
Count Subarrays with Given SumNext Topic ⮕
Two Sum ProblemTopic Contents
You are given an array consisting of only the numbers 0
, 1
, and 2
. Your task is to sort the array in-place so that all 0s come first, then all 1s, followed by all 2s.
This problem must be solved without using any sorting function and in a way that is both time and space efficient. You should not use extra space for counting or storing elements separately.
Return the same array after sorting.
arr
consisting only of 0s, 1s, and 2s.low = 0
, mid = 0
, and high = n - 1
.mid
pointer until it exceeds high
:arr[mid] == 0
, swap arr[low]
and arr[mid]
, increment both low
and mid
.arr[mid] == 1
, just move mid
one step ahead.arr[mid] == 2
, swap arr[mid]
and arr[high]
, and decrement high
.def sort_colors(arr):
low, mid, high = 0, 0, len(arr) - 1
while mid <= high:
if arr[mid] == 0:
arr[low], arr[mid] = arr[mid], arr[low]
low += 1
mid += 1
elif arr[mid] == 1:
mid += 1
else:
arr[mid], arr[high] = arr[high], arr[mid]
high -= 1
return arr
# Sample Input
arr = [2, 0, 2, 1, 1, 0]
print("Sorted Array:", sort_colors(arr))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | In all cases, the array is traversed only once from start to end using the mid pointer. |
Average Case | O(n) | Each element is visited at most once, making the number of operations directly proportional to the array size. |
Average Case | O(n) | Even in the worst distribution (e.g., alternating 0s and 2s), the algorithm completes in linear time as each element is handled in a single pass. |
O(1)
Explanation: The algorithm uses only constant extra space with three pointers (low
, mid
, high
), and all operations are done in-place.
⬅ Previous Topic
Count Subarrays with Given SumNext Topic ⮕
Two Sum ProblemYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.