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

02 Find The Duplicate Number

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

const findTheDuplicateNumber = nums => {
  let slow = nums[0]
  let fast = nums[0]
  while (true) {
    slow = nums[slow]
    fast = nums[nums[fast]]
    if (slow == fast) {
      break
    }
  }

  let slow2 = nums[0]
  while (true) {
    if (slow == slow2) {
      return slow
    }
    slow = nums[slow]
    slow2 = nums[slow2]
  }
}

console.log(findTheDuplicateNumber([1, 3, 4, 2, 2]))

Created 2022-02-04T04:03:39+00:00 · Edit