
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Find first duplicate item in array in linear time 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
- Related Articles
- How to splice duplicate item in array JavaScript
- How to sort array by first item in subarray - JavaScript?
- Return the first duplicate number from an array in JavaScript
- Get the first and last item in an array using JavaScript?
- Find duplicate element in a progression of first n terms JavaScript
- Find the least duplicate items in an array JavaScript
- How to find duplicate values in a JavaScript array?
- How to move specific item in array list to the first item in Java?
- Two sum problem in linear time in JavaScript
- Get greatest repetitive item in array JavaScript
- Removing duplicate objects from array in JavaScript
- Sum all duplicate value in array - JavaScript
- Sum all duplicate values in array in JavaScript
- JavaScript Find the first non-consecutive number in Array
- Program to find duplicate item from a list of elements in Python

Advertisements