![]() |
VOOZH | about |
Given an array arr[] of integers. In one operation you can choose an index i, and increment the element arr[i] by 1. The task is to return the minimum number of operations needed to make every value in the array arr[] unique.
Examples:
Input: arr[] = [3, 2, 1, 2, 1, 7]
Output: 6
Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. It can be shown that it is impossible for the array to have all unique values with 5 or less operations.Input: arr[] = [1, 2, 2]
Output: 1
Explanation: After 1 operation [2 -> 3], the array could be [1, 2, 3].Input: arr[] = [5, 4, 3, 2, 1]
Output: 0
Explanation: All elements are unique.
Table of Content
The idea is to sort the array and then build a strictlyincreasingarray by performing increment operations. Because elements in a strictly increasing array will always be unique.
Follow the given steps to solve the problem:
Illustration:
6
The idea is to use a frequency array to count occurrences of each number in arr[], to make all elements unique. First, we create a sufficiently large frequency array based on the maximum element and size of array. Then, we iterate over this frequency array and check if the current number's frequency is greater than 1. If it is, we increment all extra occurrences by 1 to make the current number unique. This process continues until all numbers are unique. Also we will count these increment operations during the iteration.
5
Time Complexity: O(n + max), where n is the size of the array and max is its maximum element.
Auxiliary Space: O(n + max)