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

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:12:17+05:18, updated 2021-01-31T20:49:21+05:18 · History · Edit