Find the First Non-Repeating Character in a String
Solve this Problem
Given a string
s, find the first character that never repeats anywhere else in the string, and return its index. If every character repeats, return -1.
Checking each character against every other character works, but it's quadratic. The faster approach counts every character's frequency in one pass, then makes a second pass in order and returns the index of the first character whose frequency is exactly 1 — the first one that was never seen again.
Test Case 1:
Input:s = "swiss"
Output:1
Explanation:'s' appears 3 times, but 'w' at index 1 appears only once — it's the first non-repeating character.
Test Case 2:
Input:s = "aabb"
Output:-1
Explanation:Every character repeats — there's no non-repeating character.
Test Case 3:
Input:s = "leetcode"
Output:0
Explanation:'l' at index 0 never repeats anywhere else in the string.
Constraints
- ◆
1 ≤ s.length ≤ 10⁵ - ◆
s consists only of lowercase English letters
🚀
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
🧪Try your own test case
| 1 | class Solution { |
| 2 | public int firstUniqChar(String s) { |
| 3 | Map<Character, Integer> freq = new HashMap<>(); |
| 4 | for (char c : s.toCharArray()) { |
| 5 | freq.put(c, freq.getOrDefault(c, 0) + 1); |
| 6 | } |
| 7 | for (int i = 0; i < s.length(); i++) { |
| 8 | if (freq.get(s.charAt(i)) == 1) return i; |
| 9 | } |
| 10 | return -1; |
| 11 | } |
| 12 | } |
| 13 |
String
s
w
i
s
s
↑i
HashMap
s→1
Variables
c
sfreq[c]
1UPDATE
s[0] = 's' — freq['s'] becomes 1.
Step 1 / 7
Approach & Solutions
Brute Force — Check Every Character Against the Rest
BruteFor each character, scan the entire rest of the string to check whether it appears again. The first character that matches nothing else is the answer. Simple, but comparing every character against every other character is quadratic.
Time
O(n²)Space
O(1)Java
1class Solution {
2 public int firstUniqChar(String s) {
3 for (int i = 0; i < s.length(); i++) {
4 boolean unique = true;
5 for (int j = 0; j < s.length(); j++) {
6 if (i != j && s.charAt(i) == s.charAt(j)) {
7 unique = false;
8 break;
9 }
10 }
11 if (unique) return i;
12 }
13 return -1;
14 }
15}Optimal — Frequency Map, Two Passes
OptimalCount every character's frequency in one pass. Then scan the string a second time, in order, and return the index of the first character whose frequency is exactly 1. Since the alphabet is fixed (26 lowercase letters), the map holds at most 26 entries — effectively constant space.
Time
O(n)Space
O(1)Java
1class Solution {
2 public int firstUniqChar(String s) {
3 Map<Character, Integer> freq = new HashMap<>();
4 for (char c : s.toCharArray()) {
5 freq.put(c, freq.getOrDefault(c, 0) + 1);
6 }
7 for (int i = 0; i < s.length(); i++) {
8 if (freq.get(s.charAt(i)) == 1) return i;
9 }
10 return -1;
11 }
12}