← Questions

First unique character in a string

0
AmazonCodingLast asked Jul 2025

A coding interview question asked in Amazon's technical phone screen, last asked Jul 2025. It tests hashing and strings.

Given a string s, return the index of the first character that appears exactly once in it. If every character repeats, return -1. Give an O(n) solution and compare it with a sorting-based one.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • first_unique(s: str) -> int — comparison is case-sensitive, so "a" and "A" differ.

Example

"planet"        ->  0    # "p"
"swisswatch"    ->  2    # "i"; "s" and "w" repeat
"aabb"          ->  -1
"aA"            ->  0

Constraints

  • 0 <= len(s) <= 10^5
  • s holds letters and digits, upper and lower case.

Clarifying questions

  • Is the comparison case-sensitive?
  • What is the character set: ASCII letters and digits, or any Unicode?
  • What should an empty string return?

What a strong answer covers

  • Two passes: count every character in a hash map or a fixed-size array, then walk the string again and return the first index whose count is 1. O(n) time, O(alphabet) space.
  • Why the second pass walks the string, not the map: that keeps the original order.
  • The sorting alternative groups equal characters in O(n log n) but loses positions unless it carries indices.
  • Tests: empty, one character, all repeated, the unique character last.

Follow-ups

  • The characters arrive as a stream; return the first unique character after each one in O(1) (a count plus a queue or linked list).
  • The string is too large to hold in memory, and you can read it only once.
  • Return the first character that appears exactly k times.

Where it's asked

  • Amazon · Technical phone screen · Last asked Jul 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

hashing · strings

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding