First Unique Character in a String explained
To find the first character in a string that appears exactly once, count every character in one pass, then scan the string again from the left and return the index of the first character whose count is 1, or -1 if none is. That is O(n) time, and the counts take O(1) space when the alphabet is fixed, such as 26 lowercase letters. A one-pass variant records each character's first index and marks repeats, then picks the smallest index among characters seen once.
By Evin JohnPublished 7 min read
The problem, in plain terms
Given a string, find the first character, reading left to right, that occurs nowhere else in the string. Return its index. If every character repeats somewhere, return -1. Many versions limit the input to lowercase English letters; ask, because the answer to that question changes the data structure and the space bound.
"cocoa" counts: c 2, o 2, a 1 -> 4 (the final "a")
"swiss" counts: s 3, w 1, i 1 -> 1 ("w" comes before "i")
"noon" counts: n 2, o 2 -> -1
"z" -> 0
"" -> -1The cocoa example is worth having ready: the answer is the last character, which catches code that gives up early. The swiss example shows that you want the earliest unique character by position, not by alphabet or by when its count was settled.
Brute force: count each character separately
For each position, count how many times that character occurs in the whole string and return the first position whose count is 1. In Python, s.count(ch) scans the full string, so a string of length n costs O(n²). It is short, obviously correct and useful as a reference when you test a faster version.
def first_unique_brute(s):
for i, ch in enumerate(s):
if s.count(ch) == 1:
return i
return -1The standard answer: count, then scan
Separate the two jobs. A first pass builds a table from character to count. A second pass walks the string in order and returns the first index whose character has count 1. The second pass is what preserves left-to-right order, so you never need to sort or remember positions in the table.
from collections import Counter
def first_unique_index(s):
counts = Counter(s)
for i, ch in enumerate(s):
if counts[ch] == 1:
return i
return -1If the input is limited to lowercase letters, an array of 26 integers indexed by ord(ch) - ord('a') replaces the Counter. It is faster in practice and makes the O(1) space claim concrete. With an unrestricted alphabet, space is O(k) for k distinct characters.
One pass over the string
Some interviewers ask whether you can avoid reading the string twice, for example because it is very long and stored somewhere slow. Keep one slot per letter holding the index where it first appeared, or a marker meaning not seen yet, or a different marker meaning repeated. After the single pass, the answer is the smallest stored index among letters still marked as seen once. That final scan touches 26 slots, not n characters.
function firstUniqueIndex(s) {
const first = new Array(26).fill(-1); // -1 = not seen yet
const REPEATED = -2;
for (let i = 0; i < s.length; i++) {
const k = s.charCodeAt(i) - 97;
if (first[k] === -1) first[k] = i;
else first[k] = REPEATED;
}
let best = -1;
for (const idx of first) {
if (idx >= 0 && (best === -1 || idx < best)) best = idx;
}
return best;
}This version reads n characters once plus 26 slots, against the two-pass version's up to 2n reads. Both are O(n). The difference matters only when n is huge compared with the alphabet, so present it as a trade-off rather than a strict improvement.
Follow-up: characters arrive as a stream
A common extension feeds characters one at a time and asks, after each one, which character seen so far is the first that has appeared only once. Recounting each time would be O(n) per query. Instead, keep counts plus a queue of characters in the order they were first seen. When asked, drop characters from the front of the queue while their count is above 1; the front is then the answer. Each character enters and leaves the queue at most once, so the cost is O(1) amortized per character.
from collections import Counter, deque
class FirstUniqueStream:
def __init__(self):
self.counts = Counter()
self.waiting = deque() # characters seen once, oldest first
def add(self, ch):
self.counts[ch] += 1
if self.counts[ch] == 1:
self.waiting.append(ch)
def first_unique(self):
while self.waiting and self.counts[self.waiting[0]] > 1:
self.waiting.popleft() # repeated since it was queued; drop it for good
return self.waiting[0] if self.waiting else NoneDropping a character permanently is safe because counts only go up: once a character has repeated, it can never become unique again. If the stream also allowed deletions, that argument breaks and you would want an ordered map or a doubly linked list keyed by character.
What an index means beyond plain ASCII
Python strings index by code point, so an emoji or an accented letter counts as one position. JavaScript strings index by UTF-16 code unit, so characters outside the Basic Multilingual Plane, such as many emoji, take two positions, and s.length counts both halves. The charCodeAt version above assumes a to z and gives nonsense for anything else. For general text in JavaScript, count with a Map keyed by s[i] if the interviewer accepts code-unit indexes, or convert with Array.from(s) first if the index should count whole characters. Saying this unprompted is an easy way to show care.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Count each character separately | O(n²) | O(1) |
| Count, then scan | O(n) | O(k), or O(1) for a fixed 26-letter alphabet |
| One pass with first-seen indexes | O(n + k) | O(k) |
| Stream with counts and a queue | O(1) amortized per character | O(k) |
Edge cases to test
- The empty string: -1.
- A single character: 0.
- Every character repeated, such as noon: -1.
- The only unique character at the very end, such as cocoa.
- Characters that become repeated after their first appearance, such as aba, where b at index 1 is the answer.
Common mistakes
- Scanning a 26-slot count array for the answer instead of the string. That finds the alphabetically first unique letter, not the leftmost one.
- Returning the character when the question asks for the index, or the reverse.
- Using a set of seen characters only, which cannot tell a character seen once from one seen three times.
- In the one-pass version, writing the index again when a character repeats, so it never gets marked as repeated.
- Claiming O(1) space without stating the fixed-alphabet assumption.
How to explain it out loud
Fictional example
- Candidate
- Is it lowercase letters only? Then I'll use an array of 26 counts. First pass counts, second pass walks the string and returns the first index with count 1. Linear time, constant space.
- Candidate
- The second pass is over the string, not the counts, because that's what keeps the left-to-right order.
- Candidate
- If characters came in as a stream, I'd keep the counts plus a queue in first-seen order and pop repeated ones off the front lazily. Each character leaves the queue once, so that's amortized constant per character.
Related problems
Counting characters over a moving window instead of the whole string is the core of Find All Anagrams in a String. Counting two lists and comparing their counts appears in Intersection of Two Arrays. A count map also drives the duplicate-free search in Permutations II.
Natively for warm-up problems
Easy problems are often the first question in a screen, and the follow-ups decide how it goes. While you practice, Natively on Mac or Windows can read a short problem from a screenshot and suggest an approach and code to compare with yours. Its transcript shows whether you raised the alphabet question before coding. See LeetCode practice with AI.
Questions people ask
How do you find the first unique character in a string?
Count every character in one pass, then walk the string again from the left and return the first index whose character has count 1. Return -1 if there is none.
What is the time and space complexity?
O(n) time. Space is O(1) for a fixed alphabet such as 26 lowercase letters, or O(k) for k distinct characters in general.
Can you find the first unique character in one pass?
Yes. Store each letter's first index and mark letters that repeat, then return the smallest stored index among letters seen once. The final scan is over the alphabet, not the string.
How do you find the first unique character in a stream?
Keep counts plus a queue of characters in first-seen order. When asked, pop characters from the front while their count is above 1; the front is the answer. That is O(1) amortized per character.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
