HomeInterview QuestionsFind the index of the first non-repeating characte…

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

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

💡 Model Answer

The goal is to locate the first character that appears exactly once in the string. A two-pass approach works efficiently:

  1. First pass: Count the frequency of each character using a hash map.
  2. Second pass: Iterate the string again and return the index of the first character whose count is 1.

This guarantees O(n) time and O(1) space (for a fixed alphabet). Example in PHP:

php
function firstNonRepeatingIndex(string $s): int {
    $freq = [];
    for ($i = 0; $i < strlen($s); $i++) {
        $c = $s[$i];
        $freq[$c] = ($freq[$c] ?? 0) + 1;
    }
    for ($i = 0; $i < strlen($s); $i++) {
        if ($freq[$s[$i]] === 1) {
            return $i;
        }
    }
    return -1; // no non-repeating character
}

Edge cases: empty string returns -1; case sensitivity matters unless specified otherwise. This solution is concise, runs in linear time, and is suitable for interview settings.

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