00:00

Problem Statement

Input/Output Examples

Visual Explanation

The first pass finds the counts and the highest count. The second pass walks the string from the left and stops at the first character with that count, which settles any tie by position.

Approaches

Both approaches apply the same tie rule. One uses an ASCII array; the other a map and a stream.

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 then search a structure of at most n elements.

Interview Tips and Recommended Approach

  • Always state the tie rule. Without it, two correct programs can return different answers.
  • Know why a plain HashMap is risky. Its iteration order is not defined, so ties could be broken differently from run to run of the code base.
  • Use ++counts[c] to track the maximum in the same pass. It saves a separate scan over the array.
  • Ask about case and spaces. They change the answer for inputs like "Aa a".

Recommended Approach: Counting Array, Two Passes

Why: it runs in linear time with a fixed-size array and makes the tie rule explicit through the second pass over the string.