code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

075 Sort Colors

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const sortColors = colors => {
  let [low, current, high] = [0, 0, colors.length - 1]
  while (current <= high) {
    if (colors[current] == 2) {
      colors[current] = colors[high]
      colors[high--] = 2
    }
    if (colors[current] == 0) {
      colors[current++] = colors[low]
      colors[low++] = 0
    }
    if (colors[current] == 1) {
      current++
    }
  }
  return colors
}

test('sortColors', () => {
  expect(sortColors([2, 0, 2, 1, 1, 0])).toEqual([0, 0, 1, 1, 2, 2])
})

Created 2021-02-03T01:29:58+05:18, updated 2021-03-02T14:44:43+05:18 · History · Edit