Making array unique in JavaScript

In JavaScript, making array elements unique by incrementing duplicates is a common problem. This approach finds the minimum number of incremental moves needed to ensure all array elements are unique.

Problem Statement

Given an array of numbers, we need to find the minimum number of moves to make all elements unique. A move consists of incrementing any element by 1.

For example, with the array [12, 15, 7, 15], we need 1 move to make it unique by changing one 15 to 16.

Algorithm Approach

The strategy is to sort the array first, then iterate through it. For each element that's less than or equal to the previous element, increment it to be one more than the previous element.

Example Implementation

const arr = [12, 15, 7, 15];

const makeUnique = (arr = []) => {
    // Sort array to handle duplicates in order
    arr.sort((a, b) => a - b);
    let count = 0;
    
    for (let i = 1; i 

1
Final array: [7, 12, 15, 16]

Step-by-Step Execution

Let's trace through the algorithm with our example:

const arr2 = [3, 3, 3, 5];

const makeUniqueDetailed = (arr = []) => {
    console.log("Original array:", [...arr]);
    arr.sort((a, b) => a - b);
    console.log("Sorted array:", [...arr]);
    
    let count = 0;
    
    for (let i = 1; i 

Original array: [3, 3, 3, 5]
Sorted array: [3, 3, 3, 5]
Move 1: Changed 3 to 4
Move 3: Changed 3 to 5
Move 3: Changed 5 to 6
Final unique array: [3, 4, 5, 6]
Total moves needed: 3

Alternative Approaches

Method Time Complexity Space Complexity Modifies Original
Sort & Increment O(n log n) O(1) Yes
Hash Map Count O(n) O(n) No

Key Points

  • Sorting ensures we handle duplicates in ascending order
  • Each element only needs to be one greater than the previous
  • The algorithm modifies the original array
  • Time complexity is O(n log n) due to sorting

Conclusion

This greedy approach efficiently finds the minimum moves by sorting first and incrementing duplicates to the next available value. The algorithm ensures optimal results by processing elements in order.

Updated on: 2026-03-15T23:19:00+05:30

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements