
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find First Duplicate Item in Array in Linear Time Using JavaScript
We are required to write a JavaScript function that takes in a read only array of n + 1 integers between 1 and n.
The function should find one number that repeats in linear time and using at most O(n) space.
For example If the input array is −
const arr = [3 4 1 4 1];
Then the output should be −
const output = 1;
If there are multiple possible answers ( like above ), we should output any one. If there is no duplicate, we should output -1.
Example
const arr = [3, 4, 1, 4, 1]; const findRepeatedNumber = (arr = []) => { const set = new Set(); for (const item of arr) { if (set.has(item)){ return item; }; set.add(item); }; return -1; }; console.log(findRepeatedNumber(arr));
Output
This will produce the following output −
4
Advertisements