Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Return the index of first character that appears twice in a string in JavaScript
We are required to write a JavaScript function that takes in a string and returns the index of the first character that appears twice in the string.
If there is no such character then we should return -1.
Syntax
function firstRepeating(str) {
// Implementation here
}
Example
The code for this will be ?
const str = 'Hello world, how are you';
const firstRepeating = str => {
const map = new Map();
for(let i = 0; i < str.length; i++){
if(map.has(str[i])){
return map.get(str[i]);
};
map.set(str[i], i);
};
return -1;
};
console.log(firstRepeating(str));
Output
Following is the output on console ?
2
How It Works
The function uses a Map to track character positions. When it encounters a character for the second time, it returns the index of the first occurrence. In the example, 'l' appears at index 2 and repeats at index 3, so the function returns 2.
Alternative Approach Using indexOf and lastIndexOf
const findFirstRepeating = str => {
for(let i = 0; i < str.length; i++){
if(str.indexOf(str[i]) !== str.lastIndexOf(str[i])){
return i;
}
}
return -1;
};
console.log(findFirstRepeating('Hello world'));
console.log(findFirstRepeating('abcdef')); // No repeating character
2 -1
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Map approach | O(n) | O(n) | High |
| indexOf/lastIndexOf | O(n²) | O(1) | Medium |
Conclusion
The Map-based approach is more efficient with O(n) time complexity, making it ideal for longer strings. Use indexOf/lastIndexOf for simpler implementations with shorter strings.
Advertisements
