Skip to main content

17. First Unique Character in a String

easyAsked at Quora

Find the first non-repeating character in a string — Quora applies this frequency-then-scan pattern to surface the first truly distinctive keyword in a question title for their search-ranking pipeline.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a string s, find the first non-repeating character and return its index. If no such character exists, return -1.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of only lowercase English letters

Examples

Example 1

Input
s = "leetcode"
Output
0

Explanation: 'l' appears once and is at index 0.

Example 2

Input
s = "aabb"
Output
-1

Approaches

1. Two-pass frequency count

First pass: count character frequencies. Second pass: return index of first character with frequency 1.

Time
O(n)
Space
O(1)
function firstUniqChar(s) {
  const freq = {};
  for (const ch of s) freq[ch] = (freq[ch] || 0) + 1;
  for (let i = 0; i < s.length; i++) {
    if (freq[s[i]] === 1) return i;
  }
  return -1;
}

Tradeoff:

2. Index-comparison trick

A character is unique if indexOf and lastIndexOf return the same position. Avoids explicit frequency storage at the cost of O(26n) passes.

Time
O(n)
Space
O(1)
function firstUniqChar(s) {
  let minIdx = Infinity;
  for (let c = 97; c <= 122; c++) {
    const ch = String.fromCharCode(c);
    const first = s.indexOf(ch);
    if (first !== -1 && first === s.lastIndexOf(ch)) {
      minIdx = Math.min(minIdx, first);
    }
  }
  return minIdx === Infinity ? -1 : minIdx;
}

Tradeoff:

Quora-specific tips

Quora expects you to note that the alphabet-fixed O(26n) approach is still O(n) with a better constant in practice; they then ask you to extend to arbitrary Unicode, where a Map replaces the fixed-alphabet trick — a real scenario in their multilingual Q&A platform.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill First Unique Character in a String and other Quora interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →