Find all pairs in an array that sum to a given number without using HashMap

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
1
down vote

favorite













Find all pairs in an array that sum to a given number without using HashMap.
Duplicate pairs are not allowed. Input array cannot be modified.



input: -2, -1, -1, 5, 7, 7, 7, 7, 8, target = 7



output: (-1, 8)




As it is mentioned, using HashMap is not allowed, so I decided to use binary search.



GitHub



public class TwoSumProblemUsingBinarySearch 

public static class Pair

private final int x;
private final int y;

public Pair(int x, int y)
this.x = x;
this.y = y;


@Override
public int hashCode()
return Objects.hash(x, y);


@Override
public boolean equals(Object other)
if (other instanceof Pair)
Pair o = (Pair) other;
return this.x == o.x && this.y == o.y;


return false;


@Override
public String toString()
return String.format("(%d, %d)", x, y);



public static Set<Pair> findAllParis(int input, int target)
int numbers = Arrays.copyOf(input, input.length);
Set<Pair> pairs = new HashSet<>();

Arrays.sort(numbers);

for (int low = 0, high = input.length - 1; low < high; )
int sum = input[low] + input[high];

if (sum > target)
high--;
else if (sum < target)
low++;
else
pairs.add(new Pair(input[low], input[high]));
high--;
low++;



return pairs;



@Test
public void findAllParis() throws Exception

System.out.println(TwoSumProblemUsingBinarySearch.findAllParis(new int-2, -1, -1, 5, 7, 7, 7, 7, 8, 7));
assertEquals(1, TwoSumProblemUsingBinarySearch.findAllParis(new int-2, -1, -1, 5, 7, 7, 7, 7, 8, 7).size());







share|improve this question



























    up vote
    1
    down vote

    favorite













    Find all pairs in an array that sum to a given number without using HashMap.
    Duplicate pairs are not allowed. Input array cannot be modified.



    input: -2, -1, -1, 5, 7, 7, 7, 7, 8, target = 7



    output: (-1, 8)




    As it is mentioned, using HashMap is not allowed, so I decided to use binary search.



    GitHub



    public class TwoSumProblemUsingBinarySearch 

    public static class Pair

    private final int x;
    private final int y;

    public Pair(int x, int y)
    this.x = x;
    this.y = y;


    @Override
    public int hashCode()
    return Objects.hash(x, y);


    @Override
    public boolean equals(Object other)
    if (other instanceof Pair)
    Pair o = (Pair) other;
    return this.x == o.x && this.y == o.y;


    return false;


    @Override
    public String toString()
    return String.format("(%d, %d)", x, y);



    public static Set<Pair> findAllParis(int input, int target)
    int numbers = Arrays.copyOf(input, input.length);
    Set<Pair> pairs = new HashSet<>();

    Arrays.sort(numbers);

    for (int low = 0, high = input.length - 1; low < high; )
    int sum = input[low] + input[high];

    if (sum > target)
    high--;
    else if (sum < target)
    low++;
    else
    pairs.add(new Pair(input[low], input[high]));
    high--;
    low++;



    return pairs;



    @Test
    public void findAllParis() throws Exception

    System.out.println(TwoSumProblemUsingBinarySearch.findAllParis(new int-2, -1, -1, 5, 7, 7, 7, 7, 8, 7));
    assertEquals(1, TwoSumProblemUsingBinarySearch.findAllParis(new int-2, -1, -1, 5, 7, 7, 7, 7, 8, 7).size());







    share|improve this question























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite












      Find all pairs in an array that sum to a given number without using HashMap.
      Duplicate pairs are not allowed. Input array cannot be modified.



      input: -2, -1, -1, 5, 7, 7, 7, 7, 8, target = 7



      output: (-1, 8)




      As it is mentioned, using HashMap is not allowed, so I decided to use binary search.



      GitHub



      public class TwoSumProblemUsingBinarySearch 

      public static class Pair

      private final int x;
      private final int y;

      public Pair(int x, int y)
      this.x = x;
      this.y = y;


      @Override
      public int hashCode()
      return Objects.hash(x, y);


      @Override
      public boolean equals(Object other)
      if (other instanceof Pair)
      Pair o = (Pair) other;
      return this.x == o.x && this.y == o.y;


      return false;


      @Override
      public String toString()
      return String.format("(%d, %d)", x, y);



      public static Set<Pair> findAllParis(int input, int target)
      int numbers = Arrays.copyOf(input, input.length);
      Set<Pair> pairs = new HashSet<>();

      Arrays.sort(numbers);

      for (int low = 0, high = input.length - 1; low < high; )
      int sum = input[low] + input[high];

      if (sum > target)
      high--;
      else if (sum < target)
      low++;
      else
      pairs.add(new Pair(input[low], input[high]));
      high--;
      low++;



      return pairs;



      @Test
      public void findAllParis() throws Exception

      System.out.println(TwoSumProblemUsingBinarySearch.findAllParis(new int-2, -1, -1, 5, 7, 7, 7, 7, 8, 7));
      assertEquals(1, TwoSumProblemUsingBinarySearch.findAllParis(new int-2, -1, -1, 5, 7, 7, 7, 7, 8, 7).size());







      share|improve this question














      Find all pairs in an array that sum to a given number without using HashMap.
      Duplicate pairs are not allowed. Input array cannot be modified.



      input: -2, -1, -1, 5, 7, 7, 7, 7, 8, target = 7



      output: (-1, 8)




      As it is mentioned, using HashMap is not allowed, so I decided to use binary search.



      GitHub



      public class TwoSumProblemUsingBinarySearch 

      public static class Pair

      private final int x;
      private final int y;

      public Pair(int x, int y)
      this.x = x;
      this.y = y;


      @Override
      public int hashCode()
      return Objects.hash(x, y);


      @Override
      public boolean equals(Object other)
      if (other instanceof Pair)
      Pair o = (Pair) other;
      return this.x == o.x && this.y == o.y;


      return false;


      @Override
      public String toString()
      return String.format("(%d, %d)", x, y);



      public static Set<Pair> findAllParis(int input, int target)
      int numbers = Arrays.copyOf(input, input.length);
      Set<Pair> pairs = new HashSet<>();

      Arrays.sort(numbers);

      for (int low = 0, high = input.length - 1; low < high; )
      int sum = input[low] + input[high];

      if (sum > target)
      high--;
      else if (sum < target)
      low++;
      else
      pairs.add(new Pair(input[low], input[high]));
      high--;
      low++;



      return pairs;



      @Test
      public void findAllParis() throws Exception

      System.out.println(TwoSumProblemUsingBinarySearch.findAllParis(new int-2, -1, -1, 5, 7, 7, 7, 7, 8, 7));
      assertEquals(1, TwoSumProblemUsingBinarySearch.findAllParis(new int-2, -1, -1, 5, 7, 7, 7, 7, 8, 7).size());









      share|improve this question












      share|improve this question




      share|improve this question








      edited Aug 2 at 4:48









      200_success

      123k14142399




      123k14142399









      asked Mar 24 at 18:30









      Exploring

      20512




      20512




















          4 Answers
          4






          active

          oldest

          votes

















          up vote
          3
          down vote













          1. Typo in method name as pointed out by @Stingy. Should be findAllPairs.

          2. Accessing wrong array: You are reading values from input instead of your sorted copy numbers. This is probably a typo. E.g. int sum = input[low] + input[high]; should be int sum = numbers[low] + numbers[high];


          3. Your for loop has an empty update statement, this isn't wrong per-se but a bit unusual. Consider an alternative using while instead:



            int low = 0, high = numbers.length-1;
            while (low < high)
            int sum = numbers[low] + numbers[high];
            //...



          4. Insufficient test: As evidenced by its failure to catch the bug in 2. the test is too limited to be of much help. Consider checking more than one example (especially corner-cases like an empty input array) and checking against the expected output instead of just its size.





          share|improve this answer





















          • ooooo...indeed typo it should be numbers :-)
            – Exploring
            Mar 25 at 13:23

















          up vote
          1
          down vote













          You can prevent duplicate pairs by incrementing/decrementing your counters not only once, but until they point to a number that is greater/lesser than the number they previously pointed to. That way, you can store the pairs in a List instead of a Set, which will probably be faster, because the List doesn't need to check whether it already contains a pair that is equal to the one being added.



          Also, there is a typo in your method names findAllParis.






          share|improve this answer




























            up vote
            0
            down vote



            accepted











            Incorporating the feedbacks, here is the answer




            Github: https://github.com/Ramblers-Code/CodeKata/blob/master/src/main/java/kata/array/TwoSumProblemUsingBinarySearch.java#18



            public class TwoSumProblemUsingBinarySearch 

            public static class Pair
            private final int x;
            private final int y;

            public Pair(int x, int y)
            this.x = x;
            this.y = y;


            @Override
            public int hashCode()
            return Objects.hash(x, y);


            @Override
            public boolean equals(Object other)
            if (other instanceof Pair)
            Pair o = (Pair) other;
            return this.x == o.x && this.y == o.y;


            return false;


            @Override
            public String toString()
            return String.format("(%d, %d)", x, y);



            public static Set<Pair> findAllPairs(int input, int target)
            int numbers = Arrays.copyOf(input, input.length);
            Set<Pair> pairs = new HashSet<>();

            Arrays.sort(numbers);

            for (int low = 0, high = numbers.length - 1; low < high; )
            int sum = numbers[low] + numbers[high];

            if (sum > target)
            high--;
            else if (sum < target)
            low++;
            else
            pairs.add(new Pair(input[low], input[high]));
            high--;
            low++;



            return pairs;







            share|improve this answer




























              up vote
              -2
              down vote













              You would also have to add this to the findAllPairs method to sort the initial list which is the input:



              Arrays.sort(input);





              share|improve this answer























                Your Answer




                StackExchange.ifUsing("editor", function ()
                return StackExchange.using("mathjaxEditing", function ()
                StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
                StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
                );
                );
                , "mathjax-editing");

                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "196"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                convertImagesToLinks: false,
                noModals: false,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );








                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190395%2ffind-all-pairs-in-an-array-that-sum-to-a-given-number-without-using-hashmap%23new-answer', 'question_page');

                );

                Post as a guest






























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                3
                down vote













                1. Typo in method name as pointed out by @Stingy. Should be findAllPairs.

                2. Accessing wrong array: You are reading values from input instead of your sorted copy numbers. This is probably a typo. E.g. int sum = input[low] + input[high]; should be int sum = numbers[low] + numbers[high];


                3. Your for loop has an empty update statement, this isn't wrong per-se but a bit unusual. Consider an alternative using while instead:



                  int low = 0, high = numbers.length-1;
                  while (low < high)
                  int sum = numbers[low] + numbers[high];
                  //...



                4. Insufficient test: As evidenced by its failure to catch the bug in 2. the test is too limited to be of much help. Consider checking more than one example (especially corner-cases like an empty input array) and checking against the expected output instead of just its size.





                share|improve this answer





















                • ooooo...indeed typo it should be numbers :-)
                  – Exploring
                  Mar 25 at 13:23














                up vote
                3
                down vote













                1. Typo in method name as pointed out by @Stingy. Should be findAllPairs.

                2. Accessing wrong array: You are reading values from input instead of your sorted copy numbers. This is probably a typo. E.g. int sum = input[low] + input[high]; should be int sum = numbers[low] + numbers[high];


                3. Your for loop has an empty update statement, this isn't wrong per-se but a bit unusual. Consider an alternative using while instead:



                  int low = 0, high = numbers.length-1;
                  while (low < high)
                  int sum = numbers[low] + numbers[high];
                  //...



                4. Insufficient test: As evidenced by its failure to catch the bug in 2. the test is too limited to be of much help. Consider checking more than one example (especially corner-cases like an empty input array) and checking against the expected output instead of just its size.





                share|improve this answer





















                • ooooo...indeed typo it should be numbers :-)
                  – Exploring
                  Mar 25 at 13:23












                up vote
                3
                down vote










                up vote
                3
                down vote









                1. Typo in method name as pointed out by @Stingy. Should be findAllPairs.

                2. Accessing wrong array: You are reading values from input instead of your sorted copy numbers. This is probably a typo. E.g. int sum = input[low] + input[high]; should be int sum = numbers[low] + numbers[high];


                3. Your for loop has an empty update statement, this isn't wrong per-se but a bit unusual. Consider an alternative using while instead:



                  int low = 0, high = numbers.length-1;
                  while (low < high)
                  int sum = numbers[low] + numbers[high];
                  //...



                4. Insufficient test: As evidenced by its failure to catch the bug in 2. the test is too limited to be of much help. Consider checking more than one example (especially corner-cases like an empty input array) and checking against the expected output instead of just its size.





                share|improve this answer













                1. Typo in method name as pointed out by @Stingy. Should be findAllPairs.

                2. Accessing wrong array: You are reading values from input instead of your sorted copy numbers. This is probably a typo. E.g. int sum = input[low] + input[high]; should be int sum = numbers[low] + numbers[high];


                3. Your for loop has an empty update statement, this isn't wrong per-se but a bit unusual. Consider an alternative using while instead:



                  int low = 0, high = numbers.length-1;
                  while (low < high)
                  int sum = numbers[low] + numbers[high];
                  //...



                4. Insufficient test: As evidenced by its failure to catch the bug in 2. the test is too limited to be of much help. Consider checking more than one example (especially corner-cases like an empty input array) and checking against the expected output instead of just its size.






                share|improve this answer













                share|improve this answer



                share|improve this answer











                answered Mar 25 at 11:33









                Wingblade

                1786




                1786











                • ooooo...indeed typo it should be numbers :-)
                  – Exploring
                  Mar 25 at 13:23
















                • ooooo...indeed typo it should be numbers :-)
                  – Exploring
                  Mar 25 at 13:23















                ooooo...indeed typo it should be numbers :-)
                – Exploring
                Mar 25 at 13:23




                ooooo...indeed typo it should be numbers :-)
                – Exploring
                Mar 25 at 13:23












                up vote
                1
                down vote













                You can prevent duplicate pairs by incrementing/decrementing your counters not only once, but until they point to a number that is greater/lesser than the number they previously pointed to. That way, you can store the pairs in a List instead of a Set, which will probably be faster, because the List doesn't need to check whether it already contains a pair that is equal to the one being added.



                Also, there is a typo in your method names findAllParis.






                share|improve this answer

























                  up vote
                  1
                  down vote













                  You can prevent duplicate pairs by incrementing/decrementing your counters not only once, but until they point to a number that is greater/lesser than the number they previously pointed to. That way, you can store the pairs in a List instead of a Set, which will probably be faster, because the List doesn't need to check whether it already contains a pair that is equal to the one being added.



                  Also, there is a typo in your method names findAllParis.






                  share|improve this answer























                    up vote
                    1
                    down vote










                    up vote
                    1
                    down vote









                    You can prevent duplicate pairs by incrementing/decrementing your counters not only once, but until they point to a number that is greater/lesser than the number they previously pointed to. That way, you can store the pairs in a List instead of a Set, which will probably be faster, because the List doesn't need to check whether it already contains a pair that is equal to the one being added.



                    Also, there is a typo in your method names findAllParis.






                    share|improve this answer













                    You can prevent duplicate pairs by incrementing/decrementing your counters not only once, but until they point to a number that is greater/lesser than the number they previously pointed to. That way, you can store the pairs in a List instead of a Set, which will probably be faster, because the List doesn't need to check whether it already contains a pair that is equal to the one being added.



                    Also, there is a typo in your method names findAllParis.







                    share|improve this answer













                    share|improve this answer



                    share|improve this answer











                    answered Mar 25 at 10:42









                    Stingy

                    1,888212




                    1,888212




















                        up vote
                        0
                        down vote



                        accepted











                        Incorporating the feedbacks, here is the answer




                        Github: https://github.com/Ramblers-Code/CodeKata/blob/master/src/main/java/kata/array/TwoSumProblemUsingBinarySearch.java#18



                        public class TwoSumProblemUsingBinarySearch 

                        public static class Pair
                        private final int x;
                        private final int y;

                        public Pair(int x, int y)
                        this.x = x;
                        this.y = y;


                        @Override
                        public int hashCode()
                        return Objects.hash(x, y);


                        @Override
                        public boolean equals(Object other)
                        if (other instanceof Pair)
                        Pair o = (Pair) other;
                        return this.x == o.x && this.y == o.y;


                        return false;


                        @Override
                        public String toString()
                        return String.format("(%d, %d)", x, y);



                        public static Set<Pair> findAllPairs(int input, int target)
                        int numbers = Arrays.copyOf(input, input.length);
                        Set<Pair> pairs = new HashSet<>();

                        Arrays.sort(numbers);

                        for (int low = 0, high = numbers.length - 1; low < high; )
                        int sum = numbers[low] + numbers[high];

                        if (sum > target)
                        high--;
                        else if (sum < target)
                        low++;
                        else
                        pairs.add(new Pair(input[low], input[high]));
                        high--;
                        low++;



                        return pairs;







                        share|improve this answer

























                          up vote
                          0
                          down vote



                          accepted











                          Incorporating the feedbacks, here is the answer




                          Github: https://github.com/Ramblers-Code/CodeKata/blob/master/src/main/java/kata/array/TwoSumProblemUsingBinarySearch.java#18



                          public class TwoSumProblemUsingBinarySearch 

                          public static class Pair
                          private final int x;
                          private final int y;

                          public Pair(int x, int y)
                          this.x = x;
                          this.y = y;


                          @Override
                          public int hashCode()
                          return Objects.hash(x, y);


                          @Override
                          public boolean equals(Object other)
                          if (other instanceof Pair)
                          Pair o = (Pair) other;
                          return this.x == o.x && this.y == o.y;


                          return false;


                          @Override
                          public String toString()
                          return String.format("(%d, %d)", x, y);



                          public static Set<Pair> findAllPairs(int input, int target)
                          int numbers = Arrays.copyOf(input, input.length);
                          Set<Pair> pairs = new HashSet<>();

                          Arrays.sort(numbers);

                          for (int low = 0, high = numbers.length - 1; low < high; )
                          int sum = numbers[low] + numbers[high];

                          if (sum > target)
                          high--;
                          else if (sum < target)
                          low++;
                          else
                          pairs.add(new Pair(input[low], input[high]));
                          high--;
                          low++;



                          return pairs;







                          share|improve this answer























                            up vote
                            0
                            down vote



                            accepted







                            up vote
                            0
                            down vote



                            accepted







                            Incorporating the feedbacks, here is the answer




                            Github: https://github.com/Ramblers-Code/CodeKata/blob/master/src/main/java/kata/array/TwoSumProblemUsingBinarySearch.java#18



                            public class TwoSumProblemUsingBinarySearch 

                            public static class Pair
                            private final int x;
                            private final int y;

                            public Pair(int x, int y)
                            this.x = x;
                            this.y = y;


                            @Override
                            public int hashCode()
                            return Objects.hash(x, y);


                            @Override
                            public boolean equals(Object other)
                            if (other instanceof Pair)
                            Pair o = (Pair) other;
                            return this.x == o.x && this.y == o.y;


                            return false;


                            @Override
                            public String toString()
                            return String.format("(%d, %d)", x, y);



                            public static Set<Pair> findAllPairs(int input, int target)
                            int numbers = Arrays.copyOf(input, input.length);
                            Set<Pair> pairs = new HashSet<>();

                            Arrays.sort(numbers);

                            for (int low = 0, high = numbers.length - 1; low < high; )
                            int sum = numbers[low] + numbers[high];

                            if (sum > target)
                            high--;
                            else if (sum < target)
                            low++;
                            else
                            pairs.add(new Pair(input[low], input[high]));
                            high--;
                            low++;



                            return pairs;







                            share|improve this answer














                            Incorporating the feedbacks, here is the answer




                            Github: https://github.com/Ramblers-Code/CodeKata/blob/master/src/main/java/kata/array/TwoSumProblemUsingBinarySearch.java#18



                            public class TwoSumProblemUsingBinarySearch 

                            public static class Pair
                            private final int x;
                            private final int y;

                            public Pair(int x, int y)
                            this.x = x;
                            this.y = y;


                            @Override
                            public int hashCode()
                            return Objects.hash(x, y);


                            @Override
                            public boolean equals(Object other)
                            if (other instanceof Pair)
                            Pair o = (Pair) other;
                            return this.x == o.x && this.y == o.y;


                            return false;


                            @Override
                            public String toString()
                            return String.format("(%d, %d)", x, y);



                            public static Set<Pair> findAllPairs(int input, int target)
                            int numbers = Arrays.copyOf(input, input.length);
                            Set<Pair> pairs = new HashSet<>();

                            Arrays.sort(numbers);

                            for (int low = 0, high = numbers.length - 1; low < high; )
                            int sum = numbers[low] + numbers[high];

                            if (sum > target)
                            high--;
                            else if (sum < target)
                            low++;
                            else
                            pairs.add(new Pair(input[low], input[high]));
                            high--;
                            low++;



                            return pairs;








                            share|improve this answer













                            share|improve this answer



                            share|improve this answer











                            answered Mar 26 at 18:29









                            Exploring

                            20512




                            20512




















                                up vote
                                -2
                                down vote













                                You would also have to add this to the findAllPairs method to sort the initial list which is the input:



                                Arrays.sort(input);





                                share|improve this answer



























                                  up vote
                                  -2
                                  down vote













                                  You would also have to add this to the findAllPairs method to sort the initial list which is the input:



                                  Arrays.sort(input);





                                  share|improve this answer

























                                    up vote
                                    -2
                                    down vote










                                    up vote
                                    -2
                                    down vote









                                    You would also have to add this to the findAllPairs method to sort the initial list which is the input:



                                    Arrays.sort(input);





                                    share|improve this answer















                                    You would also have to add this to the findAllPairs method to sort the initial list which is the input:



                                    Arrays.sort(input);






                                    share|improve this answer















                                    share|improve this answer



                                    share|improve this answer








                                    edited Aug 2 at 4:40









                                    Jamal♦

                                    30.1k11114225




                                    30.1k11114225











                                    answered Aug 1 at 23:30









                                    Megha

                                    1




                                    1






















                                         

                                        draft saved


                                        draft discarded


























                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190395%2ffind-all-pairs-in-an-array-that-sum-to-a-given-number-without-using-hashmap%23new-answer', 'question_page');

                                        );

                                        Post as a guest













































































                                        Popular posts from this blog

                                        Python Lists

                                        Aion

                                        JavaScript Array Iteration Methods