Day 8: Find Duplicate Number in Array – JavaScript Interview Question

 ๐Ÿ“Œ Problem:


> Given an array of integers, find any duplicate number.




๐Ÿงช Example:


Input: [1, 2, 3, 4, 2]

Output: 2



---


✅ Solution 1 – Using Set:


function findDuplicate(arr) {

  const seen = new Set();

  for (let num of arr) {

    if (seen.has(num)) return num;

    seen.add(num);

  }

  return -1;

}



---


✅ Solution 2 – Sort & Compare:


function findDuplicate(arr) {

  arr.sort();

  for (let i = 1; i < arr.length; i++) {

    if (arr[i] === arr[i - 1]) return arr[i];

  }

  return -1;

}



---


๐Ÿ’ก Tips to Remember:


Set is great for uniqueness checks


Sorting reduces space, but increases time: O(n log n)


Use return -1 for "no duplicate" fallback



Comments

Popular posts from this blog

Day 4 – Palindrome Number in JavaScript Without Converting to String

Day 9 – Count Vowels in a String using JavaScript | DSA Challenge with Code & Explanation

Day 13: Find Missing Number in an Array – JavaScript DSA Challenge