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
Post a Comment