Find pairs in an integer array whose sum is equal to n (bonus: do it in linear time)

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
2
down vote

favorite












I gave this one a shot, and the code works. Am I on the right track? How can the code be improved? Also, I am unaware of how to determine if this would be linear time or not. Could someone maybe break that determination down for me?



'''
Problem statement: Find pairs in an integer array whose sum is equal to n (bonus: do it in linear time)

@author: Anonymous3.1415
'''

def pair_sum_to_n(integer_list, n):
pairs =
#checks for the occurence of halfs
if not n % 2:
if integer_list.count(n/2) > 1:
pairs.append((n/2, n/2))
integer_set = set(integer_list) - n/2
#finds pairs of integers where x + (n - x) = n
for x in integer_set:
if (n - x) in integer_set:
if (n - x, x) not in pairs:
pairs.append((x, n - x))
return pairs

integer_list = list(map(int, raw_input().strip().split(" ")))
pairs = pair_sum_to_n(integer_list, 10)
print(pairs)






share|improve this question



























    up vote
    2
    down vote

    favorite












    I gave this one a shot, and the code works. Am I on the right track? How can the code be improved? Also, I am unaware of how to determine if this would be linear time or not. Could someone maybe break that determination down for me?



    '''
    Problem statement: Find pairs in an integer array whose sum is equal to n (bonus: do it in linear time)

    @author: Anonymous3.1415
    '''

    def pair_sum_to_n(integer_list, n):
    pairs =
    #checks for the occurence of halfs
    if not n % 2:
    if integer_list.count(n/2) > 1:
    pairs.append((n/2, n/2))
    integer_set = set(integer_list) - n/2
    #finds pairs of integers where x + (n - x) = n
    for x in integer_set:
    if (n - x) in integer_set:
    if (n - x, x) not in pairs:
    pairs.append((x, n - x))
    return pairs

    integer_list = list(map(int, raw_input().strip().split(" ")))
    pairs = pair_sum_to_n(integer_list, 10)
    print(pairs)






    share|improve this question























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I gave this one a shot, and the code works. Am I on the right track? How can the code be improved? Also, I am unaware of how to determine if this would be linear time or not. Could someone maybe break that determination down for me?



      '''
      Problem statement: Find pairs in an integer array whose sum is equal to n (bonus: do it in linear time)

      @author: Anonymous3.1415
      '''

      def pair_sum_to_n(integer_list, n):
      pairs =
      #checks for the occurence of halfs
      if not n % 2:
      if integer_list.count(n/2) > 1:
      pairs.append((n/2, n/2))
      integer_set = set(integer_list) - n/2
      #finds pairs of integers where x + (n - x) = n
      for x in integer_set:
      if (n - x) in integer_set:
      if (n - x, x) not in pairs:
      pairs.append((x, n - x))
      return pairs

      integer_list = list(map(int, raw_input().strip().split(" ")))
      pairs = pair_sum_to_n(integer_list, 10)
      print(pairs)






      share|improve this question













      I gave this one a shot, and the code works. Am I on the right track? How can the code be improved? Also, I am unaware of how to determine if this would be linear time or not. Could someone maybe break that determination down for me?



      '''
      Problem statement: Find pairs in an integer array whose sum is equal to n (bonus: do it in linear time)

      @author: Anonymous3.1415
      '''

      def pair_sum_to_n(integer_list, n):
      pairs =
      #checks for the occurence of halfs
      if not n % 2:
      if integer_list.count(n/2) > 1:
      pairs.append((n/2, n/2))
      integer_set = set(integer_list) - n/2
      #finds pairs of integers where x + (n - x) = n
      for x in integer_set:
      if (n - x) in integer_set:
      if (n - x, x) not in pairs:
      pairs.append((x, n - x))
      return pairs

      integer_list = list(map(int, raw_input().strip().split(" ")))
      pairs = pair_sum_to_n(integer_list, 10)
      print(pairs)








      share|improve this question












      share|improve this question




      share|improve this question








      edited Jan 28 at 6:04









      Jamal♦

      30.1k11114225




      30.1k11114225









      asked Jan 28 at 5:57









      Anonymous3.1415

      376212




      376212




















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Problem definition



          it is not clearly defined whether pair_sum_to_n([1, 9, 9, 1, 9], 10) shall result in. your implementation suggests (1, 9) as desired result. other possibilites include



          • (1, 9)

          • (9, 1)

          • (9, 1), (1, 9)

          • [(1, 9), (1, 9)]

          • [(1, 9), (9, 1)]

          • [(9, 1), (1, 9)]

          • [(1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9)]

          • ...

          Indentation



          integer_set is not defined for odd n



          Special case handling n/2for even n



          always prove it is necessary/useful to do extra code. the best implementation (given that it matches the requirements) is the one that is most easy to understand, implement and test. your special looks like a fine shortcut but requires extra testing odd/even. the indentation error would probably not be there when this case had been omitted. however it is needed as you copy all values from the parameter to a set.



          Parameter name integer_list



          this suggests the imput parameter is a list. however your algorithm could work on every iterable (if you omit the special case) so a name like integers or values would be less suggestive.



          Copy iterable to set



          this is a good strategy if the operations beeing performed on the values lateron are expensive and the values are expected to contain many duplicates. if one of these conditions is false - don't do it. as your test is quite cheap (the set containment check is more or less the same as an insert to a set), you could omit all that special case handling and iterate over the parameter once. however if you work on an iterable with duplicates you have to sort out duplicate pairs by using a set as storage for the sorted pairs. also if you avoid the filtering on the input you could adapt to different problem definitions (see problem definition above) easily.






          share|improve this answer





















          • so I fixed the code above to include a non even n, and after looking up the complexity of the containment operator for sets (which I wrongfully assumed it to be O(n)) I am convinced then that this implementation is indeed linear given that I have O(1) in O(1) with a list containment O(n)... am I mistaken? thank you for the more in depth answer by the way
            – Anonymous3.1415
            Jan 29 at 11:06

















          up vote
          2
          down vote













          The map by default returns a list. You do not need another wrapper around it.



          Your current implementation is of $ O(n^2) $ complexity. The statement:



          (n - x, x) not in pairs


          is of $ O(n) $ time, which lies inside a loop with $ O(n) $.



          To do this in linear time, generate a dict/hash where you store simply the $ n - x $ values in first iteration. In the second (and independent) iteration, simply append the pair $$ left( min(x, n - x), max(x, n - x) right) $$ for each x in your list, if the $ O(1) $ lookup in the dict is true.






          share|improve this answer























          • map only returns a list in Python 2. In Python 3 it returns a map object that is lazily evaluated.
            – Graipher
            Jan 28 at 19:34










          • set containment check is O(1). Ther is no need for two iterations.
            – stefan
            Jan 29 at 6:07










          • @stefan sorry, I meant for that to be (n - x, x) not in pairs. Thanks for pointing that out
            – hjpotter92
            Jan 29 at 11:50











          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%2f186179%2ffind-pairs-in-an-integer-array-whose-sum-is-equal-to-n-bonus-do-it-in-linear-t%23new-answer', 'question_page');

          );

          Post as a guest






























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          Problem definition



          it is not clearly defined whether pair_sum_to_n([1, 9, 9, 1, 9], 10) shall result in. your implementation suggests (1, 9) as desired result. other possibilites include



          • (1, 9)

          • (9, 1)

          • (9, 1), (1, 9)

          • [(1, 9), (1, 9)]

          • [(1, 9), (9, 1)]

          • [(9, 1), (1, 9)]

          • [(1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9)]

          • ...

          Indentation



          integer_set is not defined for odd n



          Special case handling n/2for even n



          always prove it is necessary/useful to do extra code. the best implementation (given that it matches the requirements) is the one that is most easy to understand, implement and test. your special looks like a fine shortcut but requires extra testing odd/even. the indentation error would probably not be there when this case had been omitted. however it is needed as you copy all values from the parameter to a set.



          Parameter name integer_list



          this suggests the imput parameter is a list. however your algorithm could work on every iterable (if you omit the special case) so a name like integers or values would be less suggestive.



          Copy iterable to set



          this is a good strategy if the operations beeing performed on the values lateron are expensive and the values are expected to contain many duplicates. if one of these conditions is false - don't do it. as your test is quite cheap (the set containment check is more or less the same as an insert to a set), you could omit all that special case handling and iterate over the parameter once. however if you work on an iterable with duplicates you have to sort out duplicate pairs by using a set as storage for the sorted pairs. also if you avoid the filtering on the input you could adapt to different problem definitions (see problem definition above) easily.






          share|improve this answer





















          • so I fixed the code above to include a non even n, and after looking up the complexity of the containment operator for sets (which I wrongfully assumed it to be O(n)) I am convinced then that this implementation is indeed linear given that I have O(1) in O(1) with a list containment O(n)... am I mistaken? thank you for the more in depth answer by the way
            – Anonymous3.1415
            Jan 29 at 11:06














          up vote
          1
          down vote



          accepted










          Problem definition



          it is not clearly defined whether pair_sum_to_n([1, 9, 9, 1, 9], 10) shall result in. your implementation suggests (1, 9) as desired result. other possibilites include



          • (1, 9)

          • (9, 1)

          • (9, 1), (1, 9)

          • [(1, 9), (1, 9)]

          • [(1, 9), (9, 1)]

          • [(9, 1), (1, 9)]

          • [(1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9)]

          • ...

          Indentation



          integer_set is not defined for odd n



          Special case handling n/2for even n



          always prove it is necessary/useful to do extra code. the best implementation (given that it matches the requirements) is the one that is most easy to understand, implement and test. your special looks like a fine shortcut but requires extra testing odd/even. the indentation error would probably not be there when this case had been omitted. however it is needed as you copy all values from the parameter to a set.



          Parameter name integer_list



          this suggests the imput parameter is a list. however your algorithm could work on every iterable (if you omit the special case) so a name like integers or values would be less suggestive.



          Copy iterable to set



          this is a good strategy if the operations beeing performed on the values lateron are expensive and the values are expected to contain many duplicates. if one of these conditions is false - don't do it. as your test is quite cheap (the set containment check is more or less the same as an insert to a set), you could omit all that special case handling and iterate over the parameter once. however if you work on an iterable with duplicates you have to sort out duplicate pairs by using a set as storage for the sorted pairs. also if you avoid the filtering on the input you could adapt to different problem definitions (see problem definition above) easily.






          share|improve this answer





















          • so I fixed the code above to include a non even n, and after looking up the complexity of the containment operator for sets (which I wrongfully assumed it to be O(n)) I am convinced then that this implementation is indeed linear given that I have O(1) in O(1) with a list containment O(n)... am I mistaken? thank you for the more in depth answer by the way
            – Anonymous3.1415
            Jan 29 at 11:06












          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          Problem definition



          it is not clearly defined whether pair_sum_to_n([1, 9, 9, 1, 9], 10) shall result in. your implementation suggests (1, 9) as desired result. other possibilites include



          • (1, 9)

          • (9, 1)

          • (9, 1), (1, 9)

          • [(1, 9), (1, 9)]

          • [(1, 9), (9, 1)]

          • [(9, 1), (1, 9)]

          • [(1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9)]

          • ...

          Indentation



          integer_set is not defined for odd n



          Special case handling n/2for even n



          always prove it is necessary/useful to do extra code. the best implementation (given that it matches the requirements) is the one that is most easy to understand, implement and test. your special looks like a fine shortcut but requires extra testing odd/even. the indentation error would probably not be there when this case had been omitted. however it is needed as you copy all values from the parameter to a set.



          Parameter name integer_list



          this suggests the imput parameter is a list. however your algorithm could work on every iterable (if you omit the special case) so a name like integers or values would be less suggestive.



          Copy iterable to set



          this is a good strategy if the operations beeing performed on the values lateron are expensive and the values are expected to contain many duplicates. if one of these conditions is false - don't do it. as your test is quite cheap (the set containment check is more or less the same as an insert to a set), you could omit all that special case handling and iterate over the parameter once. however if you work on an iterable with duplicates you have to sort out duplicate pairs by using a set as storage for the sorted pairs. also if you avoid the filtering on the input you could adapt to different problem definitions (see problem definition above) easily.






          share|improve this answer













          Problem definition



          it is not clearly defined whether pair_sum_to_n([1, 9, 9, 1, 9], 10) shall result in. your implementation suggests (1, 9) as desired result. other possibilites include



          • (1, 9)

          • (9, 1)

          • (9, 1), (1, 9)

          • [(1, 9), (1, 9)]

          • [(1, 9), (9, 1)]

          • [(9, 1), (1, 9)]

          • [(1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9)]

          • ...

          Indentation



          integer_set is not defined for odd n



          Special case handling n/2for even n



          always prove it is necessary/useful to do extra code. the best implementation (given that it matches the requirements) is the one that is most easy to understand, implement and test. your special looks like a fine shortcut but requires extra testing odd/even. the indentation error would probably not be there when this case had been omitted. however it is needed as you copy all values from the parameter to a set.



          Parameter name integer_list



          this suggests the imput parameter is a list. however your algorithm could work on every iterable (if you omit the special case) so a name like integers or values would be less suggestive.



          Copy iterable to set



          this is a good strategy if the operations beeing performed on the values lateron are expensive and the values are expected to contain many duplicates. if one of these conditions is false - don't do it. as your test is quite cheap (the set containment check is more or less the same as an insert to a set), you could omit all that special case handling and iterate over the parameter once. however if you work on an iterable with duplicates you have to sort out duplicate pairs by using a set as storage for the sorted pairs. also if you avoid the filtering on the input you could adapt to different problem definitions (see problem definition above) easily.







          share|improve this answer













          share|improve this answer



          share|improve this answer











          answered Jan 29 at 7:09









          stefan

          1,201110




          1,201110











          • so I fixed the code above to include a non even n, and after looking up the complexity of the containment operator for sets (which I wrongfully assumed it to be O(n)) I am convinced then that this implementation is indeed linear given that I have O(1) in O(1) with a list containment O(n)... am I mistaken? thank you for the more in depth answer by the way
            – Anonymous3.1415
            Jan 29 at 11:06
















          • so I fixed the code above to include a non even n, and after looking up the complexity of the containment operator for sets (which I wrongfully assumed it to be O(n)) I am convinced then that this implementation is indeed linear given that I have O(1) in O(1) with a list containment O(n)... am I mistaken? thank you for the more in depth answer by the way
            – Anonymous3.1415
            Jan 29 at 11:06















          so I fixed the code above to include a non even n, and after looking up the complexity of the containment operator for sets (which I wrongfully assumed it to be O(n)) I am convinced then that this implementation is indeed linear given that I have O(1) in O(1) with a list containment O(n)... am I mistaken? thank you for the more in depth answer by the way
          – Anonymous3.1415
          Jan 29 at 11:06




          so I fixed the code above to include a non even n, and after looking up the complexity of the containment operator for sets (which I wrongfully assumed it to be O(n)) I am convinced then that this implementation is indeed linear given that I have O(1) in O(1) with a list containment O(n)... am I mistaken? thank you for the more in depth answer by the way
          – Anonymous3.1415
          Jan 29 at 11:06












          up vote
          2
          down vote













          The map by default returns a list. You do not need another wrapper around it.



          Your current implementation is of $ O(n^2) $ complexity. The statement:



          (n - x, x) not in pairs


          is of $ O(n) $ time, which lies inside a loop with $ O(n) $.



          To do this in linear time, generate a dict/hash where you store simply the $ n - x $ values in first iteration. In the second (and independent) iteration, simply append the pair $$ left( min(x, n - x), max(x, n - x) right) $$ for each x in your list, if the $ O(1) $ lookup in the dict is true.






          share|improve this answer























          • map only returns a list in Python 2. In Python 3 it returns a map object that is lazily evaluated.
            – Graipher
            Jan 28 at 19:34










          • set containment check is O(1). Ther is no need for two iterations.
            – stefan
            Jan 29 at 6:07










          • @stefan sorry, I meant for that to be (n - x, x) not in pairs. Thanks for pointing that out
            – hjpotter92
            Jan 29 at 11:50















          up vote
          2
          down vote













          The map by default returns a list. You do not need another wrapper around it.



          Your current implementation is of $ O(n^2) $ complexity. The statement:



          (n - x, x) not in pairs


          is of $ O(n) $ time, which lies inside a loop with $ O(n) $.



          To do this in linear time, generate a dict/hash where you store simply the $ n - x $ values in first iteration. In the second (and independent) iteration, simply append the pair $$ left( min(x, n - x), max(x, n - x) right) $$ for each x in your list, if the $ O(1) $ lookup in the dict is true.






          share|improve this answer























          • map only returns a list in Python 2. In Python 3 it returns a map object that is lazily evaluated.
            – Graipher
            Jan 28 at 19:34










          • set containment check is O(1). Ther is no need for two iterations.
            – stefan
            Jan 29 at 6:07










          • @stefan sorry, I meant for that to be (n - x, x) not in pairs. Thanks for pointing that out
            – hjpotter92
            Jan 29 at 11:50













          up vote
          2
          down vote










          up vote
          2
          down vote









          The map by default returns a list. You do not need another wrapper around it.



          Your current implementation is of $ O(n^2) $ complexity. The statement:



          (n - x, x) not in pairs


          is of $ O(n) $ time, which lies inside a loop with $ O(n) $.



          To do this in linear time, generate a dict/hash where you store simply the $ n - x $ values in first iteration. In the second (and independent) iteration, simply append the pair $$ left( min(x, n - x), max(x, n - x) right) $$ for each x in your list, if the $ O(1) $ lookup in the dict is true.






          share|improve this answer















          The map by default returns a list. You do not need another wrapper around it.



          Your current implementation is of $ O(n^2) $ complexity. The statement:



          (n - x, x) not in pairs


          is of $ O(n) $ time, which lies inside a loop with $ O(n) $.



          To do this in linear time, generate a dict/hash where you store simply the $ n - x $ values in first iteration. In the second (and independent) iteration, simply append the pair $$ left( min(x, n - x), max(x, n - x) right) $$ for each x in your list, if the $ O(1) $ lookup in the dict is true.







          share|improve this answer















          share|improve this answer



          share|improve this answer








          edited Jan 29 at 11:50


























          answered Jan 28 at 11:09









          hjpotter92

          4,97611539




          4,97611539











          • map only returns a list in Python 2. In Python 3 it returns a map object that is lazily evaluated.
            – Graipher
            Jan 28 at 19:34










          • set containment check is O(1). Ther is no need for two iterations.
            – stefan
            Jan 29 at 6:07










          • @stefan sorry, I meant for that to be (n - x, x) not in pairs. Thanks for pointing that out
            – hjpotter92
            Jan 29 at 11:50

















          • map only returns a list in Python 2. In Python 3 it returns a map object that is lazily evaluated.
            – Graipher
            Jan 28 at 19:34










          • set containment check is O(1). Ther is no need for two iterations.
            – stefan
            Jan 29 at 6:07










          • @stefan sorry, I meant for that to be (n - x, x) not in pairs. Thanks for pointing that out
            – hjpotter92
            Jan 29 at 11:50
















          map only returns a list in Python 2. In Python 3 it returns a map object that is lazily evaluated.
          – Graipher
          Jan 28 at 19:34




          map only returns a list in Python 2. In Python 3 it returns a map object that is lazily evaluated.
          – Graipher
          Jan 28 at 19:34












          set containment check is O(1). Ther is no need for two iterations.
          – stefan
          Jan 29 at 6:07




          set containment check is O(1). Ther is no need for two iterations.
          – stefan
          Jan 29 at 6:07












          @stefan sorry, I meant for that to be (n - x, x) not in pairs. Thanks for pointing that out
          – hjpotter92
          Jan 29 at 11:50





          @stefan sorry, I meant for that to be (n - x, x) not in pairs. Thanks for pointing that out
          – hjpotter92
          Jan 29 at 11:50













           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186179%2ffind-pairs-in-an-integer-array-whose-sum-is-equal-to-n-bonus-do-it-in-linear-t%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Chat program with C++ and SFML

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          Will my employers contract hold up in court?