1

I have came up with this code when I try to find indexes of unique pairs whose total equals to target number. Time complexity and Space complexity both are O(n) for this solution. Is there any other efficient way to solve it? or what would be follow up questions for this one ?

    public static ArrayList<int[]> findingTwoSum(int arr[], int target){

    if (arr == null || arr.length < 1){
        throw new IllegalArgumentException();
    }
    HashMap<Integer, Integer> map = new HashMap<>();
    ArrayList<int[]> result = new ArrayList<>();


    for (int i = 0 ; i < arr.length ; i++){

        if (!map.containsKey(arr[i])){
            map.put(target-arr[i], i);
        }
        else{

            if(!result.contains(map.get(arr[i]))){
            result.add(new int[]{i,map.get(arr[i])});
            }
        }
    }           

    return result;          
}
Gökhan Akduğan
  • 483
  • 1
  • 6
  • 15
  • 2
    Time complexity is not O(n). Look inside your loop. You do result.contains() which itself is O(n). – Peter L Oct 09 '15 at 01:40
  • 1
    Possible duplicate of [Find a pair of elements from an array whose sum equals a given number](http://stackoverflow.com/questions/4720271/find-a-pair-of-elements-from-an-array-whose-sum-equals-a-given-number) – Peter L Oct 09 '15 at 01:42

0 Answers0