Hashing · Easy
First Non-Repeating Character
Solve it on DeVert Campus - free code runner
Problem
Given a string s consisting of lowercase English letters, find the first character that does not repeat (i.e., the first character that appears exactly once) when scanning the string from left to right. Print the 1-indexed position of that character in s. If every character repeats, print -1.
Input and output
Input: A single line containing the string s.
Output: A single integer: the 1-indexed position of the first non-repeating character, or -1 if none exists.
Example
Input: aabbc Output: 5
Constraints
1 <= |s| <= 10^5. s consists only of lowercase English letters ('a'-'z').
Key observation
Needing TWO passes here (one to count, one to find the first qualifying position) rather than one is a direct consequence of not knowing a character's FINAL count until the whole string has been scanned - a useful reminder that some counting problems genuinely need two passes.
Intuition
Find the position of the first character in a string that doesn't repeat anywhere else in it.
Brute force: For every character, scan the REST of the string directly checking for a duplicate - this costs O(n²), unnecessary when a single counting pass followed by a second scan achieves the same result in linear time.
Optimised: Since there are only 26 possible lowercase letters, one pass to build a frequency count and a second pass to find the first count-of-1 character both run in O(n), with the fixed-size 26-slot array making lookups instant - no need to compare every character against every other one.
Step by step
1. Count how many times each character appears using a hash map or a fixed-size array of 26 counters (one full pass).
2. Scan the string a SECOND time, left to right, and return the 1-indexed position of the first character whose count is exactly 1.
3. If every character repeats, print -1.
Complexity
Time: O(n) - two linear passes (one to count, one to find the answer).
Space: O(1) - a fixed 26-slot frequency array, regardless of the string's length.
Edge cases
A string of length 1 always outputs 1. If every character repeats at least twice, the output is -1.
Interview tip
Be ready to mention the streaming variant of this exact idea ('First Non-Repeating Character From a Stream', solved with a doubly linked list) as a natural, harder follow-up when the string arrives incrementally rather than all at once.