00:00

Problem Statement

Input/Output Examples

Visual Explanation

Skipping numbers that have a predecessor is what keeps the algorithm linear: each run is walked only from its first element, so every value is visited a constant number of times.

Approaches

The set approach meets the O(n) requirement. Sorting is simpler but takes O(n log n).

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 number of elements. The set approach visits each value a constant number of times; sorting dominates the second approach.

Interview Tips and Recommended Approach

  • Only count from run starts. Counting from every value makes the algorithm quadratic.
  • Handle duplicates. They must not break or extend a run.
  • Iterate over the set. Iterating over the original array repeats work for duplicates.
  • Mention union-find as another way to merge neighbouring values.

Recommended Approach: HashSet With Run Starts

Why: it meets the linear-time requirement with a single set and a simple "is this a start?" check.