First Unique Character in a String

Easy · Stack & Strings · Hash Table · String · Queue · Counting

Problem

Given a string s, find the first character that appears exactly once in it and return its index. If every character repeats, return -1.

Examples

Input: s = "swiss"
Output: 1

's' repeats, so the first unique character is 'w' at index 1.

Input: s = "abab"
Output: -1

Both letters appear twice.

Input: s = "z"
Output: 0

The only character is unique.

Constraints

Approaches

Follow-up

The characters arrive one at a time as a stream, and after each one you must report the first unique character so far. Keep the counts plus a queue of candidates in arrival order, and pop from the front while the front has repeated: each character enters and leaves the queue at most once.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…