Home β€Ί Interview Questions β€Ί Find the index of the first repeating character in…

Find the index of the first repeating character in a string.

🟑 Medium Coding Junior level
1Times asked
Apr 2026Last seen
Apr 2026First seen

πŸ’‘ Model Answer

To find the index of the first repeating character, iterate through the string while maintaining a hash map that records the first index at which each character appears. For each character, check if it already exists in the map. If it does, the current index is the second occurrence of a repeating character, and the stored index is the first occurrence. Return the stored index as the answer. If the loop completes without finding a repeat, return -1. This algorithm runs in O(n) time and uses O(1) additional space (since the map size is bounded by the alphabet). Example in PHP:

php
function firstRepeatingIndex(string $s): int {
    $map = [];
    for ($i = 0; $i < strlen($s); $i++) {
        $c = $s[$i];
        if (isset($map[$c])) {
            return $map[$c]; // first occurrence index
        }
        $map[$c] = $i;
    }
    return -1;
}

This returns the index of the first character that repeats, which is often what interviewers expect.

This answer was generated by AI for study purposes. Use it as a starting point β€” personalize it with your own experience.

🎀 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers β€” invisible to screen sharing.

Get Assisting AI β€” Starts at β‚Ή500