Programmers / Pick Two and Add

Programmers / Pick Two and Add

Problem

Solution 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.TreeSet;
import java.util.Iterator;

class Solution {
    public int[] solution(int[] numbers) {
        // Init treeset
        TreeSet<Integer> set = new TreeSet<>();
        
        // Add
        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                int sum = numbers[i] + numbers[j];
           		set.add(sum);
            }
        }
        
        // Set result
        Iterator<Integer> it = set.iterator();
        int[] result = new int[set.size()];
        for (int i = 0; i < set.size(); i++) {
            result[i] = it.next();
        }
        return result;
    }
}
Solution 1
  • Description
    • Uses TreeSet for deduplication and sorting functionality
  • Time Complexity
    • O(len(numbers)^2)
    • Two nested for loops of size len(numbers)
  • Space Complexity
    • O(len(numbers))
    • Memory usage proportional to len(numbers) for function input