00:00

Problem Statement

Input/Output Examples

Visual Explanation

Counting first means a value repeated three times is still reported only once. The sorted keys of the TreeMap give the required ascending order directly.

Approaches

Both approaches report the duplicates in ascending order. One counts in a map; the other sorts a copy.

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. Both approaches are dominated by O(n log n) ordering work. If the order does not matter, a HashMap gives O(n) time.

Interview Tips and Recommended Approach

  • Report each duplicate once. Printing inside the first loop prints 8 twice for three 8s.
  • Clarify the output order. Sorted, first-appearance and second-appearance orders can all differ.
  • Know the bounded-range trick. If values are in 0..n-1, index marking finds duplicates in O(1) extra space.
  • Avoid changing the input. Sort a copy unless modifying the array is allowed.

Recommended Approach: TreeMap Counts

Why: it counts each value once, reports each duplicate once and gives sorted output without a separate sort step.