First Unique Character in String — Two-Pass Frequency Map [Amazon Easy]
Advertisement
Problem Statement
Input: s = 'leetcode' → 0 (l appears once). Input: s = 'aabb' → -1 (no unique char).
Key Insight: First pass: count frequency of every character. Second pass: return the first index where frequency equals 1.
C Solution
#include <string.h>
int firstUniqChar(char* s) {
int freq[26] = {0};
int n = strlen(s);
for (int i = 0; i < n; i++) freq[s[i]-'a']++;
for (int i = 0; i < n; i++) if (freq[s[i]-'a'] == 1) return i;
return -1;
}
C++ Solution
#include <string>
using namespace std;
class Solution {
public:
int firstUniqChar(string s) {
int freq[26] = {};
for (char c : s) freq[c-'a']++;
for (int i = 0; i < (int)s.size(); i++)
if (freq[s[i]-'a'] == 1) return i;
return -1;
}
};
Java Solution
class Solution {
public int firstUniqChar(String s) {
int[] freq = new int[26];
for (char c : s.toCharArray()) freq[c-'a']++;
for (int i = 0; i < s.length(); i++)
if (freq[s.charAt(i)-'a'] == 1) return i;
return -1;
}
}
JavaScript Solution
function firstUniqChar(s) {
const freq = new Array(26).fill(0);
for (const c of s) freq[c.charCodeAt(0)-97]++;
for (let i = 0; i < s.length; i++)
if (freq[s.charCodeAt(i)-97] === 1) return i;
return -1;
}
Python Solution
def firstUniqChar(s):
from collections import Counter
freq = Counter(s)
for i, c in enumerate(s):
if freq[c] == 1:
return i
return -1
Complexity Analysis
| O(n) time | O(1) space (26-element array) |
Streaming variant: Use LinkedHashMap to maintain insertion order while tracking counts — first key with count 1 is the answer.
Advertisement