code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

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:41:58+05:30, updated 2021-03-02T14:56:43+05:30 · History · Edit