Scrivio Interview library
CodingFoundations8 min read · updated 12 November 2026

Write a Java method that returns the index of the first non-repeating character in a String (for "swiss" the answer is 1, for 'w'), or -1 if none. Give its complexity and say how your solution behaves with text that contains emoji.

We make two passes: the first counts how often each character occurs, and the second walks the string again and returns the first index whose count is 1, so "swiss" gives 1 for 'w'. Both passes are linear, so the method is O(n) time and O(k) space for an alphabet of k characters. Emoji outside the Basic Multilingual Plane are stored as two chars, so a char-based count can return the middle of an emoji; to be correct we count code points with codePoints() and step through the string with codePointAt() and Character.charCount().

Background to this question

This is a small exercise, but it checks several habits at once: whether we reach for counting instead of a nested loop, whether we can state the complexity with a reason, and whether we know that a Java String is not really a sequence of characters as people see them. That last point matters in real work, because user names, chat messages and product reviews are full of emoji. In this answer, we will recap what a char is, write the two-pass solution, look at the LinkedHashMap variant, see how emoji break the simple version and fix it with code points, and finish with case-insensitive rules and an endless stream of characters.

1A Quick Recap of chars and Code Points

A Java String stores its text as UTF-16 code units, and each code unit is one char, a 16-bit value. For most text we meet, such as English, accented Latin letters, Greek or Chinese, one character as a person sees it is exactly one char, because those characters live in the Basic Multilingual Plane, the first 65,536 Unicode values.

Unicode has more characters than that. Each character has a number called its code point, and code points above U+FFFF, which include most emoji, do not fit in one char. Java stores them as a surrogate pair: two chars, a high surrogate followed by a low surrogate, that only mean something together. So length() counts chars, not characters, and charAt(i) can hand us half of an emoji.

For the question itself, a non-repeating character is one that occurs exactly once in the whole string. In "swiss", s occurs three times, w once and i once. The first of the unique ones, reading from the left, is w at index 1.

2The Two-Pass Solution

The natural first idea is to take each character and scan the rest of the string for a duplicate. That works, but it compares every pair, which is O(n^2): for a 100,000-character text it is about five billion comparisons. Counting removes the inner loop.

Java
static int firstUniqueChar(String s) {
int[] counts = new int[128]; // enough for ASCII text
for (int i = 0; i < s.length(); i++) {
counts[s.charAt(i)]++; // pass 1: s -> 3, w -> 1, i -> 1
}
for (int i = 0; i < s.length(); i++) {
if (counts[s.charAt(i)] == 1) { // pass 2: index 0 's' has 3, index 1 'w' has 1
return i; // 1
}
}
return -1;
}
firstUniqueChar("swiss"); // 1
firstUniqueChar("aabb"); // -1
firstUniqueChar(""); // -1
Step throughTwo passes over "swiss"
  1. Pass 1: count every chars = 3, w = 1, i = 1
  2. Pass 2: start at index 0read the string in its original order
  3. Count of this char is 1?
    YesReturn its index (1 for 'w')NoMove to the next index
  4. Reached the end?
    YesReturn -1NoCheck the next char

4 steps in order. Play them, or step through them one at a time.

Notice why we need the second pass over the string rather than over the counts: the counts tell us which characters are unique, but not which one came first. Walking the string in its original order gives us the leftmost unique character for free.

Each pass touches every char once, so the time is O(n). The array has a fixed size, so the space is O(1) for ASCII, or more precisely O(k) for an alphabet of size k. If the text can hold any char, we can use a HashMap<Character, Integer> instead, or an int[65536], which costs 256 KB but no boxing. The int[128] version above would throw ArrayIndexOutOfBoundsException for a character such as U+00E9, so we only use it when the input is known to be ASCII.

3A One-Pass Variant With LinkedHashMap

A LinkedHashMap remembers the order in which keys were first inserted. If we count into one, the first key with a count of 1 is the first unique character, so the second pass can walk the map instead of the string. That helps when the string is long but the alphabet is small: the second loop then touches k entries instead of n chars.

Java
static int firstUniqueIndex(String s) {
Map<Character, int[]> seen = new LinkedHashMap<>(); // char -> {count, firstIndex}
for (int i = 0; i < s.length(); i++) {
int[] info = seen.computeIfAbsent(s.charAt(i), c -> new int[] {0, 0});
if (info[0]++ == 0) info[1] = i; // remember where it first appeared
}
for (int[] info : seen.values()) { // s, w, i in first-seen order
if (info[0] == 1) return info[1]; // w -> 1
}
return -1;
}

We store the first index next to the count, because the map's order tells us which unique character came first but the method must return a position. The total is still O(n), with a larger constant than the int[] version because of boxing and map nodes.

4What Happens With Emoji

Now take two different emoji that sit next to each other in the Unicode table, U+1F600 and U+1F601. Both start with the same high surrogate, \uD83D. Counting chars sees that high surrogate twice and each low surrogate once.

Java
String s = "😀😁"; // two different emoji, 4 chars
s.length(); // 4
s.codePointCount(0, s.length()); // 2
firstUniqueChar16(s); // 1: the low half of the first emoji (wrong)
static int firstUniqueCodePoint(String s) {
Map<Integer, Integer> counts = new HashMap<>();
s.codePoints().forEach(cp -> counts.merge(cp, 1, Integer::sum));
for (int i = 0; i < s.length(); ) {
int cp = s.codePointAt(i); // whole code point, both halves
if (counts.get(cp) == 1) return i; // char index where it starts
i += Character.charCount(cp); // 2 for an emoji, 1 otherwise
}
return -1;
}
firstUniqueCodePoint(s); // 0: the first emoji (correct)

Here firstUniqueChar16 is the same two-pass method using a HashMap<Character, Integer> so it accepts any char. It returns index 1, which points into the middle of the first emoji, and substring(1) would produce a broken string. The fixed version counts code points, so each emoji is one key, and it advances through the string by Character.charCount(cp), which is 2 for a supplementary code point and 1 otherwise.

Notice that we still return a char index, because that is what substring() and the rest of the String API expect. We should say this in the interview, because a caller could equally expect the position counted in code points. And there is a further level we can mention: some things a person sees as one symbol, such as a flag or a thumbs-up with a skin tone, are several code points. Treating those as one unit needs grapheme clusters, which we get from BreakIterator or the regex \X.

5Case-Insensitive Rules and an Endless Stream

If the rule says that 'S' and 's' are the same letter, we normalize before counting with toLowerCase(Locale.ROOT). Passing Locale.ROOT matters, because the no-argument toLowerCase() uses the default locale of the machine, and in a Turkish locale "I".toLowerCase() becomes a dotless i (U+0131). That is a classic bug that appears only on some servers.

For a stream of characters that never ends, we cannot do a second pass. Instead we keep the answer up to date as each character arrives: a LinkedHashSet of characters seen exactly once, in arrival order, and a set of characters seen more than once. When a character arrives, if it is in the repeated set we ignore it, if it is in the once set we move it to the repeated set, and otherwise we add it to the once set. The first unique character at any moment is the first element of the once set. Each update is O(1) on average, and memory is bounded by the alphabet, not by the length of the stream.

6Follow-up questions

What does your method return for an empty string or a null input?

For an empty string both loops do nothing and we return -1, which is the contract for no unique character. For null, the method throws NullPointerException at s.length(). I would either document that null is not allowed and check it with Objects.requireNonNull at the start, which gives a clearer failure, or return -1 if the callers treat null as empty. What I would not do is silently mix the two meanings without saying so.

How would you do it for a stream of characters that never ends?

I keep two structures that are updated as each character arrives: a LinkedHashSet of characters seen once, in arrival order, and a HashSet of characters seen more than once. A new character goes into the once set; a second occurrence moves it to the repeated set; later occurrences are ignored. The current answer is the first element of the once set, available in O(1). Memory grows with the number of distinct characters, never with the stream length, so it works for an endless input.

7Conclusion

In this answer, we saw that the first non-repeating character is found with two linear passes: count every character, then walk the string in order and return the first index with a count of 1. A LinkedHashMap lets the second pass walk the distinct characters instead of the whole string. We also saw why counting chars fails for emoji stored as surrogate pairs, and how counting code points and stepping with Character.charCount fixes it, how Locale.ROOT avoids locale surprises in case-insensitive rules, and how an ordered once-seen set answers the question for an endless stream.

What to say in the interviewAbout 100 seconds aloud

Open with

I would solve it with two passes. In the first pass I count how often each character appears, using an int array of 128 if the input is known to be ASCII, or a HashMap otherwise.

Then, if they want more

In the second pass I walk the string from the left again and return the first index whose count is one, so for swiss I return 1, the w. If nothing is unique I return minus one. Both passes are linear, so it is O(n) time, and the extra space is bounded by the alphabet.

A variant counts into a LinkedHashMap, which keeps insertion order, so the second loop can walk the distinct characters instead of the full string. The catch is emoji. A Java String is UTF-16, and most emoji are surrogate pairs, two chars.

If I count chars, two different emoji that share a high surrogate make me return the index of the second half of the first emoji, which is nonsense. So for real user text I count code points with codePoints, walk with codePointAt, and advance by Character.charCount, still returning a char index so substring works.

If the comparison must ignore case, I lowercase with Locale.ROOT so a Turkish default locale cannot change the result. And if the input were an endless stream, I would keep an ordered set of characters seen once and a set of repeated ones, so the answer is always the head of that ordered set.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "Write a Java method that returns the index of the first non-repeating character in a...": https://scrivio-interview-library.netlify.app/java/coding-problems/877f2fe6f8/