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

041 First Missing Positive

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

const firstMissingPositive = nums => {
  nums = nums.sort((a, b) => a - b)
  if (nums.length == 0 || nums[nums.length - 1] < 0) {
    return 1
  }
  for (let i = 1; i < nums[nums.length - 1]; i++) {
    if (nums.indexOf(i) == -1) {
      return i
    }
  }
  return nums[nums.length - 1] + 1
}

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

Created 2021-01-25T05:24:17+05:30, updated 2021-01-31T21:01:21+05:30 · History · Edit