DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Sort Colors - Sort 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.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:

Input: nums = [2,0,1]
Output: [0,1,2]

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var sortColors = function (nums) {
  let start = 0;
  let mid = 0;
  let end = nums.length - 1;
  // setting 3 pointers start, mid , end..

  // Ideally moving from 0 to end
  while (mid <= end) {
    // checking it for 0
    // if nums[mid] === 0 => mean we have lower value..
    // so we swap this value with start pointer & move value at start index to this index
    if (nums[mid] === 0) {
      let temp = nums[start];
      nums[start] = nums[mid];
      nums[mid] = temp;
      start++;
      mid++;
    } else if (nums[mid] === 1) {
      // if nums[mid] === 1 => do nothing just move mid to next place
      mid++;
    } else {
      // if nums[mid] === 2 => swap elemnt from mid & last..
      let temp = nums[mid];
      nums[mid] = nums[end];
      nums[end] = temp;
      end--;
    }
  }
  return nums;
};

console.log(sortColors([2, 0, 2, 1, 1, 0]));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)