Skip to main content
Beginnercoding Verified

Given a string, find its first non-repeating character.

ReportedSource: GeeksforGeeks interview experience: Microsoft SDE

Quick answer

Count characters, then scan the string again and return the first with count 1. For a stream, keep a queue of once-seen characters and pop when a count hits 2. O(n).

Constraints

  • Input: one line with the string (0 to 100000 characters, no line break inside; may be empty). Comparison is case sensitive.
  • Output: the 0-based index of the first character that appears exactly once, or -1 if there is none.

Sample I/O

in: leetcode

out: 0

in: loveleetcode

out: 2

in: aabb

out: -1

Loading editor…
Output

Sign up to run your code in the sandbox.

Sign up to run code and get an AI review

You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.

Sign up free

Hints

Reference solution

Two passes with counts.

main.py
from collections import Counter
def first_unique(s):
    counts = Counter(s)
    for i, ch in enumerate(s):
        if counts[ch] == 1:
            return i      # or ch
    return -1

O(n) time; O(k) space where k is the alphabet size (O(1) for fixed ASCII).

Single pass for a stream. Keep counts plus an ordered structure (queue or ordered dict) of characters seen once; when a character's count reaches 2, drop it. The front of the queue is the answer at any moment, which is the follow-up for characters arriving one by one.

Clarify with the interviewer. Case sensitivity, Unicode vs ASCII, and what to return when every character repeats.

Discussion