Write a function that returns the index of the first non-repeating character in a given string.
1Times asked
Apr 2026Last seen
Apr 2026First seen
💡 Model Answer
To find the first non-repeating character, first count the frequency of each character using a hash map. Then iterate through the string again and return the index of the first character whose frequency is one. In PHP:
php
function firstNonRepeatingIndex(string $s): int {
$freq = [];
// Count frequencies
for ($i = 0; $i < strlen($s); $i++) {
$c = $s[$i];
$freq[$c] = ($freq[$c] ?? 0) + 1;
}
// Find first unique
for ($i = 0; $i < strlen($s); $i++) {
if ($freq[$s[$i]] === 1) {
return $i;
}
}
return -1; // no unique character
}Time complexity is O(n) and space complexity is O(1) for the alphabet size (or O(k) where k is number of distinct characters).
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