educative.io

Educative

Alternate solution with different comparison

Just putting it out there

/**
 *
 * @param input
 * return the duplicate number
 */
const findDuplicateNumber = (input: Array<number>): number => {
  let index = 0;
  const length = input.length;
  while(index < length) {
    const rightPlace = input[index] - 1;
    if (input[rightPlace] !== input[index]) {
      // swap
      [input[rightPlace], input[index]] = [input[index], input[rightPlace]];
    } else {
      if (index > 1 && input[index] === input[index - 1]) {
        const duplicate = input[index];
        console.log('duplicate is', duplicate);
        return duplicate;
      }
      index += 1;
    }
  }
  // if no duplicate found
return -Infinity;
}

I don’t know what name to give it.

Cheers

Looks good!