def first_non_repeating_char(s): count = {} for ch in s: count[ch] = count.get(ch, 0) + 1 for i, ch in enumerate(s): if count[ch] == 1: return i return -1 print(first_non_repeating_char("swiss"))
The function counts each character's occurrences. 's' appears multiple times, 'w' appears once at index 1, the first character 's' repeats. The first non-repeating character is 'w' at index 1. The code returns the index of the first character with count 1, which is index 1.
The string is "swiss". Characters and counts: s:3, w:1, i:1. The first non-repeating character is 'w' at index 1. So output is 1.
def first_non_repeating_char(s): count = {} for ch in s: count[ch] = count.get(ch, 0) + 1 for i, ch in enumerate(s): if count[ch] == 1: return i return -1 print(first_non_repeating_char("leetcode"))
Counting characters in "leetcode": l:1, e:3, t:1, c:1, o:1, d:1.
First character 'l' appears once at index 0.
The correct output is 0.
def first_non_repeating_char(s): count = {} for ch in s: count[ch] += 1 for i, ch in enumerate(s): if count[ch] == 1: return i return -1 print(first_non_repeating_char("apple"))
The code tries to increment count[ch] without initializing it first.
Since count is empty, count[ch] += 1 causes a KeyError on first occurrence.
A hash map lets us count how many times each character appears in one pass.
Then we can check each character in order to find the first with count 1.
This approach is efficient and simple.
def first_non_repeating_char(s): count = {} for ch in s: count[ch] = count.get(ch, 0) + 1 for i, ch in enumerate(s): if count[ch] == 1: return i return -1 print(first_non_repeating_char('aáa'))
The string is 'aáa'.
Characters: 'a' appears twice (index 0 and 2), 'á' appears once at index 1.
The first non-repeating character is 'á' at index 1.