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

287 Find The Duplicate Number

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

const findTheDuplicateNumber = nums => {
  for (let i = 0; i < nums.length; i++) {
    while (i != nums[i] - 1) {
      if (nums[i] == nums[nums[i] - 1]) {
        return nums[i]
      }
      let temp = nums[nums[i] - 1]
      nums[nums[i] - 1] = nums[i]
      nums[i] = temp
      console.log(nums)
    }
  }
  console.log(nums)
  return nums
}
//console.log(findTheDuplicateNumber([1, 3, 4, 2, 2]))
test('findTheDuplicateNumber', () => {
  expect(findTheDuplicateNumber([1, 3, 4, 2, 2])).toEqual(2)
})

Created 2021-03-02T14:56:43+05:30 · Edit