Find pairs in an integer array whose sum is equal to n (bonus: do it in linear time)
Clash 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)
python
add a comment |Â
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)
python
add a comment |Â
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)
python
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)
python
edited Jan 28 at 6:04
Jamalâ¦
30.1k11114225
30.1k11114225
asked Jan 28 at 5:57
Anonymous3.1415
376212
376212
add a comment |Â
add a comment |Â
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/2
for 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.
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
add a comment |Â
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.
map
only returns alist
in Python 2. In Python 3 it returns amap
object that is lazily evaluated.
â Graipher
Jan 28 at 19:34
set
containment check isO(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
add a comment |Â
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/2
for 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.
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
add a comment |Â
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/2
for 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.
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
add a comment |Â
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/2
for 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.
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/2
for 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.
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
add a comment |Â
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
add a comment |Â
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.
map
only returns alist
in Python 2. In Python 3 it returns amap
object that is lazily evaluated.
â Graipher
Jan 28 at 19:34
set
containment check isO(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
add a comment |Â
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.
map
only returns alist
in Python 2. In Python 3 it returns amap
object that is lazily evaluated.
â Graipher
Jan 28 at 19:34
set
containment check isO(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
add a comment |Â
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.
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.
edited Jan 29 at 11:50
answered Jan 28 at 11:09
hjpotter92
4,97611539
4,97611539
map
only returns alist
in Python 2. In Python 3 it returns amap
object that is lazily evaluated.
â Graipher
Jan 28 at 19:34
set
containment check isO(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
add a comment |Â
map
only returns alist
in Python 2. In Python 3 it returns amap
object that is lazily evaluated.
â Graipher
Jan 28 at 19:34
set
containment check isO(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
add a comment |Â
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password