Given a string, find the index of the first character that does not repeat. If all…
- User
Given a string, find the index of the first character that does not repeat. If all characters repeat, return -1.
Assistant
Here's a solution to find the index of the first non-repeating character:
def first_non_repeating_char(s): # Count frequency of each character char_count = {} for char in s: char_count[char] = char_count.get(char, 0) + 1 # Find first character with count 1 for i, char in enumerate(s): if char_count[char] == 1: return i return -1 # Examples print(first_non_repeating_char("leetcode")) # Output: 0 ('l') print(first_non_repeating_char("loveleetcode")) # Output: 2 ('v') print(first_non_repeating_char("aabb")) # Output: -1 print(first_non_repeating_char("abccba")) # Output: -1Algorithm:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.