Print all the unique 2 digit combinations of given numbers

We will implement a simple algorithm to print all the unique 2 digit combinations of given numbers in Javascript.

Example

Input:
[1, 2, 3]
[1, 2, 3, 4, 5]

Output:
1 2
1 3
2 3

1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5

Implementation

  • We will first remove the duplicate numbers from the given list of numbers using SET.
  • Then we will loop through each item of the array and print its combinations with every next element using inner loop.
  • We will use ES6.
let  combinations = (arr) => {
   //remove duplicate numbers
   let set = new Set(arr);
      
   //create new error from the unique numbers
   arr = [...set];
     
   //print all the combinations
   for(let i = 0; i < arr.length - 1; i++){       
     for(let j = i + 1; j < arr.length; j++){ 
          console.log(arr[i], arr[j]);
     }
         
   }
     
}
Input:
combinations([1, 2, 3]);
combinations([1, 2, 3, 4, 5]);

Output:
1 2
1 3
2 3

1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5

Learn more about SET and ... spread operator.

Time complexity: O(n^2).

Space complexity: O(n).

Time and Space complexity

  • We are remove duplicate numbers from array which will take O(n) and then creating an array of unique numbers in O(n). After that printing the combinations of numbers will take n * n - 1 * n - 2 * ... i.e O(n^2), so Time complexity is O(n^2).
  • We are using SET to store the unique numbers, so Space complexity is O(n).

Leave a Reply

Your email address will not be published. Required fields are marked *