1342. Distinct Under a Cap

Medium3.5 points estimatedCounting SortArrayGreedy

A conference gives each attendee a seat number between 0 and limit, but several attendees were handed the same number. The array nums holds the current seat numbers. In one move you may add 1 to the seat number of one attendee. Return the minimum total number of moves after which all seat numbers are pairwise distinct and none exceeds limit. If that cannot be done, return -1.

The answer can exceed the 32-bit range, so return it as a 64-bit value. Use counting sort over the values 0 to limit: sweep upward keeping a surplus of copies that still need a seat, give one copy the current value, carry the others to the next value, and add the surplus size to the total at each step. If a surplus is left after value limit, return -1. Time O(n + limit), space O(limit).

Example 1

Input:
nums = [3,2,1,2,1,7], limit = 10
Output:
6
Explanation:

The sorted seats 1, 1, 2, 2, 3, 7 become 1, 2, 3, 4, 5, 7 using 0 + 1 + 1 + 2 + 2 + 0 = 6 moves.

Example 2

Input:
nums = [5,5,5], limit = 6
Output:
-1
Explanation:

Three equal seats need the numbers 5, 6, 7, but 7 exceeds the limit 6, so it is impossible.

Example 3

Input:
nums = [2,2,2], limit = 4
Output:
3
Explanation:

The seats become 2, 3, 4 using 0 + 1 + 2 = 3 moves.

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ nums[i] ≤ limit ≤ 2 * 105

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n + limit)
Space
O(limit)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…