17.Sort Colors(Sort array of 0, 1, 2)
Given an array nums
with n
objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Here, we will use the integers 0
, 1
, and 2
to represent the color red, white, and blue respectively.
Solution : (Using 3 pointers)
Approach: Keep three pointers low=0, mid=0, high =0 if mid = 0 {swap (mid,low) and increment mid,low } if mid = 1 {incement mid} if mid = 2 {swap (mid,high) and decrement high}
Time Complexity: O(n)
Last updated