Quick revision
The short answer
Finding the first character that does not repeat is an arrays and hashing problem: count first, then decide. One pass fills a map with the count of every character, and a second pass walks the string in its own order and returns the first index whose count is 1, or -1 if every character repeats. It takes O(n) time and O(k) space for an alphabet of k characters.
The solution
What it costs
| Approach | Time | Extra space | Reads of the string |
|---|---|---|---|
| Recount each character with a second loop | O(n^2) | O(1) | up to n per character |
indexOf equals lastIndexOf | O(n^2) | O(1) | hidden inside each call |
| Count into a map, then walk the string | O(n) | O(k) | two |
| Count into int[26], then walk the string | O(n) | O(1) for a to z | two |
What to remember
We found the first character that does not repeat by doing two simple jobs one after the other. The first pass fills a tally, a map from each character to how many times it appears. The second pass walks the string in its own order and returns the first index whose count is 1, or -1 if there is none. It takes O(n) time and O(k) space. The clue to remember is a question about how often things occur, combined with the word first: count once into a map, then make the decision while walking the original order.
1What it means to find the first character that does not repeat
Picture a teacher taking a tally of the letters on a slip of paper. She draws a small table, one line for each letter, and as she reads the slip she makes a stroke beside a letter every time she meets it. When she has finished, the table tells her, for every letter, how many times it appeared. Keep this tally sheet in mind, because it is almost the whole solution.
The problem itself is short. We are given a string, which is a row of characters, and we must find the first character that appears in it exactly once. A character repeats if it appears two or more times anywhere, not only next to itself. We return the position of that character, called its index, counting from 0 at the left. If every character repeats, we return -1, which can never be a real index.
This sounds as if it needs something clever, but it is smaller than it looks. There are only two things to know about each character: how many times it appears, and where it stands in the string. The first comes from the tally sheet, and the second is simply the order in which we read. Once we hold both, the answer falls out.
Let us keep one example for the whole article, the string loveleetcode, with twelve characters at indexes 0 to 11, and do it by hand. Read it once and tally: l appears at indexes 0 and 4, so twice; o at 1 and 9, twice; v only at 2; e at 3, 5, 6 and 11, four times; t, c and d once each. Now go back to the start and read again in order, asking of each character whether its tally is 1. l has 2, so no. o has 2, so no. v has 1, so yes, and we stop. The answer is index 2.
Each box is one character with its index above it. The marked box is the answer, v at index 2.
- input
- loveleetcode
- expected
- 2 (the letter v)
1The string loveleetcode has twelve characters. l, o and e all come back later, so the first character that appears only once is v, at index 2.
What to assume
- Do we return the character or its index?
- We return the index, because it is unambiguous and the caller can read the character from it.
- Are capital and small letters different?
- We treat them as different characters, so in Swiss the capital S appears once and wins.
- Can the string be empty?
- Yes, and then we return -1.
Notice that t, c and d also appear once, but they come after v, so they never win. The word first in the question means first in the order of the string, and that is why our second reading went from left to right.
A careful candidate asks a few questions first. Do we return the character or its index? We return the index, because it is unambiguous and the caller can read the character from it. Are capital and small letters different? We treat them as different characters, so in Swiss the capital S appears once and wins. Can the string be empty? Yes, and then we return -1. If the interviewer promises lowercase a to z only, we can use a smaller tool, which we will meet later.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to spot the counting pattern in the question
When most of us read this question for the first time, our instinct is to take each character and go looking for it elsewhere in the string. That instinct is natural, and it works; we will write it down in the next section. But the question contains a few words that point to a far less tiring method, so let us read it slowly and take those words one at a time.
The first clue is the word repeat. Whether a character repeats depends only on how many times it appears, its frequency. Whenever an answer depends on how often things occur, with words such as unique, duplicate, most common or anagram, the first move is to count each item once and write the counts where we can look them up quickly.
The second clue is the word first. It tells us that order matters, so whatever we use to count, the final decision must be made while walking the string in its own order. The counts tell us which characters qualify, and the walk tells us which of those comes first. Those are two different jobs, and it is a relief that we can do them one after the other.
Together these clues point to the arrays and hashing family. A hash map is a container that stores pairs, a key and a value, and finds the value for a key almost instantly, like the index at the back of a book that sends you straight to a page. Here the key is a character and the value is its count, so the map is our tally sheet. For lowercase letters a plain array of 26 counters does the same job, hence the name arrays and hashing. The rule to carry to new problems is short: when a question is about how often things occur, count once into a map, then answer from the map.
Some patterns look similar but do not fit. A sliding window, a range of positions moving along the string, suits questions about stretches of neighbouring characters, but here we care about the whole string. Sorting would put equal characters side by side, but it would destroy the original order that the word first needs.
3The honest first attempt, counting each character from scratch
The first solution most people write follows the instinct we described. For each index i, from left to right, we count how many times the character at i appears in the whole string, using a second loop with index j. If the count is 1, we return i straight away, because no earlier index qualified. If the loop finishes, every character repeats, and we return -1. It is correct and easy to check, a perfectly good start in an interview.
Let us run it by hand on loveleetcode. For i = 0 we read all twelve characters and count two l's. For i = 1 we read all twelve again and count two o's. For i = 2 we read all twelve once more, count one v, and return 2. That is 36 comparisons.
Now think about the unlucky case, a string in which every character repeats, such as aabbcc repeated many times. Then the outer loop never returns early. It runs n times, where n is the length of the string, and each time the inner loop reads all n characters, so we make n times n comparisons. We say the time is O(n^2), read as order n squared, which means the work grows with the square of the length. The extra memory, called the space, is only two counters, which we write O(1), constant.
So where is the waste? Look at the letter e in our example. If the loop ever reached it, it would count e at index 3, and then again at index 5, again at 6 and again at 11, four complete readings of the string, and every one of them would give the same answer, 4. The number of times a character appears never changes while we work. Counting again is like the teacher rubbing out her tally sheet for every letter.
A shorter version, s.indexOf(c) == s.lastIndexOf(c), looks neat, but each call reads the string too, so it is still O(n^2) underneath. The question that leads further is whether we could count every character once, write the counts down, and then simply look them up.
4Getting to the two-pass solution, one observation at a time
The first observation is the one the waste just showed us. The count of a character is fixed for the whole string, so we can work it out once for every character in a single reading and keep it. That is the tally sheet. In Java we keep it in a map from Character to Integer, and for each character c we call counts.merge(c, 1, Integer::sum). That one call puts c in the map with the value 1 if it is new, and adds 1 to its value if it is already there. After one reading the map holds the exact count of every character.
The second observation handles the word first. Now that the counts are written down, we read the string a second time, from index 0, and for each character we ask the map for its count. The first character whose count is 1 is the answer, because we are visiting characters in the string's own order. If we reach the end without finding one, we return -1.
Here is the question a beginner usually asks at this point. Why read the string a second time? The map already contains every character; why not just look through the map for a count of 1? Let us try it and see what goes wrong. A plain HashMap keeps its keys in an order of its own, not the order we added them, so it might hand us t or d before v. Only the string knows which character came first. Our code uses a LinkedHashMap, which remembers insertion order, but we still walk the string, because that stays correct whichever map we use.
A second worry is whether we can decide during the first reading and save a pass. At index 2 we meet v, and so far its count is 1, so it is tempting to return it at once. But the first reading cannot know the future. l also had a count of 1 when we met it at index 0, and it turned out to repeat at index 4. A count is only final after the whole string has been read, so counting and deciding must be two separate passes. This is the mistake beginners make most often here, tempting because it works on many small examples.
Why is this correct? After the first pass every count is exact, because each appearance added exactly 1, and the second pass checks indexes in increasing order, so the first index it accepts has no smaller rival.
When the interviewer promises lowercase letters a to z, the map can become an int array of 26 counters. The expression c - 'a' turns a letter into a number from 0 to 25, because characters are stored as numbers and the letters are consecutive. The logic is identical.
5Watching the two passes on loveleetcode
The picture plays the method on our example. The boxes are the twelve characters, the pointer i shows where we are reading, and the panel on the right shows the map of counts as it grows. In the first pass the boxes we have read are marked as done. In the second pass the characters that turned out to repeat fade out, and the answer is marked when we reach it.
Watch for two things. In the first pass we never stop early, even after a repeat. In the second pass the counts no longer change; we only read them.
Frames 1 to 5 are the first pass, which fills the map of counts. Frames 6 to 8 are the second pass, which reads the counts in string order.
- pass
- 1, counting
- counts
- empty
1Before the first pass the tally is empty. We will read the string from index 0 to index 11 and add one to the count of each character we meet.
- pass
- 1, counting
- counts
- l:1 o:1 v:1 e:1
2After the first four characters, l, o, v and e, each letter has been seen once, so each has a count of 1 in the map.
- pass
- 1, counting
- counts
- l:2 o:1 v:1 e:1
3At index 4 we meet l again. merge finds l already in the map and adds 1, so l now has a count of 2. We do not stop; counting goes on to the end.
- pass
- 1, counting
- counts
- l:2 o:1 v:1 e:3
4Indexes 5 and 6 are both e, so the count of e climbs from 1 to 3. Each e costs one small update, never a fresh scan of the string.
- pass
- 1 finished
- counts
- l:2 o:2 v:1 e:4 t:1 c:1 d:1
5The first pass has read all twelve characters. The map now holds the full count of every letter: l, o and e repeat, and v, t, c and d appear once.
- pass
- 2, deciding
- counts
- l:2 o:2 v:1 e:4 t:1 c:1 d:1
- count of l
- 2
- result
- not yet
6The second pass starts again at index 0. We look up l in the map, its count is 2, so l repeats and cannot be the answer. We move on.
- pass
- 2, deciding
- counts
- l:2 o:2 v:1 e:4 t:1 c:1 d:1
- count of o
- 2
- result
- not yet
7At index 1 we look up o. Its count is 2 because o comes back at index 9, so we move on to the next index.
- pass
- 2, deciding
- counts
- l:2 o:2 v:1 e:4 t:1 c:1 d:1
- count of v
- 1
- result
- 2
8At index 2 we look up v and its count is 1. It is the first character in string order that appears once, so we return 2.
Let us read the important frames back. In the third frame we meet l a second time and its count becomes 2. A moment earlier l looked unique, which is what fools a one-pass attempt. In the fifth frame the first pass is finished and the map reads l:2 o:2 v:1 e:4 t:1 c:1 d:1, which is exactly the tally we made by hand in the first section.
The last three frames are the second pass. We look up l and find 2, look up o and find 2, and look up v and find 1, so we return 2 after only three look-ups. The walk stops before it reaches t, c and d, which is the word first doing its job.
6The complete Java program
Here is the full program. It holds the general method, the array version for lowercase input, and a helper, describe, that turns an index into readable text. main runs our example and a few edge cases, and the comment on each line shows what it prints.
Let us read firstUniqueIndex in the order it runs. First we create counts, an empty LinkedHashMap, our tally sheet. The first for loop goes through s.toCharArray(), which gives us the characters one by one, and calls counts.merge(c, 1, Integer::sum) for each, so every appearance adds one stroke. When this loop ends, the first pass is complete and every count is final.
The second for loop walks the indexes from 0 upwards. For each one it reads the character with s.charAt(i) and asks the map for its count. counts.get returns an Integer, and == 1 works because Java unboxes it to an int. The first time the count is 1 we return i. If the loop finishes without returning, we reach return -1, which means every character repeats.
firstUniqueLowercase follows the same two passes with an int array of 26 counters instead of a map. The line counts[s.charAt(i) - 'a']++ is the tally stroke, and counts[s.charAt(i) - 'a'] == 1 is the look-up. A capital letter or a space would give an index outside 0 to 25 and throw an exception, so it needs the promise of lowercase input.
The output reads as we expect. leetcode gives l at 0. loveleetcode gives v at 2, as in our walk. aabb gives none, because both letters repeat. Swiss gives S at 0, since the capital S differs from the small s, and the lowercase version on swiss returns 1, the w, because both s's are small letters there and repeat.
7How much it costs, and the cases at the edges
Let us count on the example first. The first pass made twelve map updates, one per character. The second pass made three look-ups before it found v, and it can never make more than twelve. That is 15 small steps, against 36 comparisons for the brute force. For a string of length n, each pass is at most n steps, and a map update or look-up takes constant time on average, so the time is O(n).
The space is the map. It holds one entry per distinct character, and loveleetcode has seven distinct characters, so seven entries. If the alphabet has k possible characters, the map never holds more than k entries, so the space is O(k). For a fixed alphabet, such as 26 lowercase letters, that is a constant, O(1), and the int[26] version makes this plain to see.
| Approach | Time | Extra space | Reads of the string |
|---|---|---|---|
| Recount each character with a second loop | O(n^2) | O(1) | up to n per character |
indexOf equals lastIndexOf | O(n^2) | O(1) | hidden inside each call |
| Count into a map, then walk the string | O(n) | O(k) | two |
| Count into int[26], then walk the string | O(n) | O(1) for a to z | two |
The edge cases need no special code. An empty string makes both loops run zero times and returns -1. A single character has a count of 1 and returns 0. A string where every character repeats, such as aabb, passes through the second loop without returning and gives -1.
Some characters, such as many emoji, are stored in Java as two char values, and counting chars would split them in half. If the input may contain them, we count code points with s.codePoints() instead, and the same two passes work unchanged.
8Follow-up questions
Can you do it in a single pass over the string?
Yes, if we are willing to walk the map instead of the string at the end. During one pass we store, for each character, the index where we first saw it, and if we see it again we replace that index with a marker such as -2 that means it repeats. After the pass, the answer is the smallest real index left in the map. For loveleetcode the map ends with v:2, t:7, c:8 and d:10 as real indexes, and the smallest is 2. The string is read once, and the final search costs O(k) for k distinct characters, which is small for a fixed alphabet.
What if the characters arrive one at a time, as a stream, and we must answer after each one?
Then we cannot read the string twice, because it never ends. We keep the counts as before, and alongside them a queue of the characters seen exactly once, in the order they arrived; a LinkedHashSet works well. When a character arrives for the first time we add it to the end. When it arrives for the second time we remove it. The answer at any moment is the first element of the set, or none if it is empty. Each arrival costs O(1) on average.
9Conclusion
We found the first character that does not repeat by doing two simple jobs one after the other. The first pass fills a tally, a map from each character to how many times it appears. The second pass walks the string in its own order and returns the first index whose count is 1, or -1 if there is none. It takes O(n) time and O(k) space. The clue to remember is a question about how often things occur, combined with the word first: count once into a map, then make the decision while walking the original order.
Open with
Let me confirm the requirements. I return the index of the first character that appears exactly once, or -1 if every character repeats, and I treat capital and small letters as different.
Then, if they want more
Rescanning the string for each character is O(n^2), because it recounts characters whose count never changes. So I will count once. In the first pass I walk the string and fill a map from character to count with merge, adding 1 for each appearance.
In the second pass I walk the string again from index 0 and return the first index whose count is 1. The second pass must walk the string rather than the map, because only the string knows the original order, and I cannot decide during the first pass, because a character that looks unique may appear again later.
That is O(n) time and O(k) space for k distinct characters. If the input is lowercase a to z, an int array of 26 counters replaces the map and the space is constant. An empty string returns -1.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 35 times in that collection. How it is counted
- Official documentation
- LinkedHashMap (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Find the first character in a string that does not repeat.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-first-character-in-a-string-that-does-not-repeat-0324e5/