00:00

Problem Statement

Input/Output Examples

Visual Explanation

The first pass builds the full count; the second pass walks the string in its original order, so the first character with count 1 is automatically the earliest unique one.

Approaches

Both approaches count first. They differ in what the second pass walks: the string or the map.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string and k is the number of distinct characters. Both approaches count in one pass and search in a second pass.

Interview Tips and Recommended Approach

  • Avoid indexOf(c) == lastIndexOf(c) in a loop. It looks neat but scans the string twice for every character: O(n²).
  • Decide what "no answer" returns. null, an Optional<Character> or a sentinel such as '_' are all fine if stated.
  • Ask about case. If S and s should match, lowercase while counting.
  • Know the streaming variant. For a stream of characters, a LinkedHashMap lets you answer at any moment.

Recommended Approach: HashMap and Two Passes

Why: it is linear, easy to verify and uses the most common Java collection. The order of the answer comes directly from the input string.