Finding the index of the first repeating character 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.

Let's say the following is our string ?

const str = 'Hello world, how are you';

We need to find the index of the first repeating character.

Understanding the Problem

In the string "Hello world, how are you", we need to find which character repeats first. The character 'l' appears at index 2 and again at index 3, making it the first repeating character at index 2.

Using Map to Track Character Positions

The most efficient approach uses a Map to store the first occurrence of each character. When we encounter a character that already exists in the Map, we return its first occurrence index.

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));
2

How It Works

The algorithm works as follows:

  1. Create a Map to store character-index pairs
  2. Iterate through each character in the string
  3. If the character exists in the Map, return its stored index (first occurrence)
  4. Otherwise, store the character with its current index
  5. Return -1 if no repeating character is found

Alternative Approach Using Object

We can also use a plain object instead of a Map:

const str = 'Hello world, how are you';
const firstRepeatingObj = str => {
    const seen = {};
    for(let i = 0; i < str.length; i++){
        if(seen[str[i]] !== undefined){
            return seen[str[i]];
        }
        seen[str[i]] = i;
    }
    return -1;
};
console.log(firstRepeatingObj(str));
2

Testing with Different Cases

const testCases = [
    'Hello world',      // 'l' at index 2
    'abcdef',          // No repeating characters
    'programming',     // 'r' at index 1
    'aabbcc'          // 'a' at index 0
];

testCases.forEach(test => {
    console.log(`"${test}" -> ${firstRepeating(test)}`);
});
"Hello world" -> 2
"abcdef" -> -1
"programming" -> 1
"aabbcc" -> 0

Comparison

Approach Time Complexity Space Complexity Advantages
Map O(n) O(n) Clean syntax, handles all characters
Object O(n) O(n) Slightly faster, more familiar syntax

Conclusion

Both Map and Object approaches efficiently find the first repeating character in O(n) time. The Map approach is cleaner and more modern, while the Object approach offers slightly better performance for string characters.

Updated on: 2026-03-15T23:19:00+05:30

648 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements