Leetcode Two Sum code in Python












10












$begingroup$


Here's my solution for the Leet Code's Two Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting.



Problem:




Given an array of integers, return indices of the two numbers such
that they add up to a specific target.



You may assume that each input would have exactly one solution, and
you may not use the same element twice.



Example:



Given nums = [2, 7, 11, 15], target = 9,



Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].




My solution:



def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

num_lst = list(range(len(nums)))

for indx, num in enumerate(num_lst):
for num_other in num_lst[indx+1:]:
if nums[num] + nums[num_other] == target:
return [num, num_other]
else:
continue
return None









share|improve this question











$endgroup$








  • 2




    $begingroup$
    Would any of the lists contain negative numbers?
    $endgroup$
    – MSeifert
    yesterday










  • $begingroup$
    @MSeifert I don't know, but feel free to assume yes
    $endgroup$
    – zthomas.nc
    11 hours ago
















10












$begingroup$


Here's my solution for the Leet Code's Two Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting.



Problem:




Given an array of integers, return indices of the two numbers such
that they add up to a specific target.



You may assume that each input would have exactly one solution, and
you may not use the same element twice.



Example:



Given nums = [2, 7, 11, 15], target = 9,



Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].




My solution:



def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

num_lst = list(range(len(nums)))

for indx, num in enumerate(num_lst):
for num_other in num_lst[indx+1:]:
if nums[num] + nums[num_other] == target:
return [num, num_other]
else:
continue
return None









share|improve this question











$endgroup$








  • 2




    $begingroup$
    Would any of the lists contain negative numbers?
    $endgroup$
    – MSeifert
    yesterday










  • $begingroup$
    @MSeifert I don't know, but feel free to assume yes
    $endgroup$
    – zthomas.nc
    11 hours ago














10












10








10


1



$begingroup$


Here's my solution for the Leet Code's Two Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting.



Problem:




Given an array of integers, return indices of the two numbers such
that they add up to a specific target.



You may assume that each input would have exactly one solution, and
you may not use the same element twice.



Example:



Given nums = [2, 7, 11, 15], target = 9,



Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].




My solution:



def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

num_lst = list(range(len(nums)))

for indx, num in enumerate(num_lst):
for num_other in num_lst[indx+1:]:
if nums[num] + nums[num_other] == target:
return [num, num_other]
else:
continue
return None









share|improve this question











$endgroup$




Here's my solution for the Leet Code's Two Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting.



Problem:




Given an array of integers, return indices of the two numbers such
that they add up to a specific target.



You may assume that each input would have exactly one solution, and
you may not use the same element twice.



Example:



Given nums = [2, 7, 11, 15], target = 9,



Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].




My solution:



def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

num_lst = list(range(len(nums)))

for indx, num in enumerate(num_lst):
for num_other in num_lst[indx+1:]:
if nums[num] + nums[num_other] == target:
return [num, num_other]
else:
continue
return None






python python-3.x k-sum






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago









200_success

129k15153415




129k15153415










asked 2 days ago









zthomas.nczthomas.nc

263311




263311








  • 2




    $begingroup$
    Would any of the lists contain negative numbers?
    $endgroup$
    – MSeifert
    yesterday










  • $begingroup$
    @MSeifert I don't know, but feel free to assume yes
    $endgroup$
    – zthomas.nc
    11 hours ago














  • 2




    $begingroup$
    Would any of the lists contain negative numbers?
    $endgroup$
    – MSeifert
    yesterday










  • $begingroup$
    @MSeifert I don't know, but feel free to assume yes
    $endgroup$
    – zthomas.nc
    11 hours ago








2




2




$begingroup$
Would any of the lists contain negative numbers?
$endgroup$
– MSeifert
yesterday




$begingroup$
Would any of the lists contain negative numbers?
$endgroup$
– MSeifert
yesterday












$begingroup$
@MSeifert I don't know, but feel free to assume yes
$endgroup$
– zthomas.nc
11 hours ago




$begingroup$
@MSeifert I don't know, but feel free to assume yes
$endgroup$
– zthomas.nc
11 hours ago










4 Answers
4






active

oldest

votes


















11












$begingroup$

Code Style





  • Your code contains a few lines that accomplish nothing and obfuscate your intent:



        else: 
    continue


    If the conditional is false, you'll automatically continue on to the next iteration without having to tell the program to do that.



        return None


    All Python functions implicitly return None; however, PEP 8 recommends this practice.




  • num_lst = list(range(len(nums))) effectively generates a list of all the indices in the nums input list. Then, you immediately enumerate this list, which produces pairs of identical indices indx, num. If all you're attempting to do is iterate, this is significant obfuscation; simply call enumerate directly on nums to produce index-element tuples:



    def twoSum(self, nums, target):
    for i, num in enumerate(nums):
    for j in range(i + 1, len(nums)):
    if num + nums[j] == target:
    return [i, j]


    This makes the intent much clearer: there are no duplicate variables with different names representing the same thing. It also saves unnecessary space and overhead associated with creating a list from a range.



  • Following on the previous item, indx, num and num_lst are confusing variable names, especially when they're all actually indices (which are technically numbers).




Efficiency





  • This code is inefficient, running in quadratic time, or $mathcal{O}(n^2)$. Leetcode is generous to let this pass (but won't be so forgiving in the future!). The reason for this is the nested loop; for every element in your list, you iterate over every other element to draw comparisons. A linear solution should finish in ~65 ms, while this takes ~4400 ms.



    Here is an efficient solution that runs in $mathcal{O}(n)$ time:



    hist = {}

    for i, n in enumerate(nums):
    if target - n in hist:
    return [hist[target-n], i]
    hist[n] = i


    How does this work? The magic of hashing. The dictionary hist offers constant $mathcal{O}(1)$ lookup time. Whenever we visit a new element in nums, we check to see if its sum complement is in the dictionary; else, we store it in the dictionary as a num => index pair.



    This is the classic time-space tradeoff: the quadratic solution is slow but space efficient, while this solution takes more space but gains a huge boost in speed. In almost every case, choose speed over space.



    For completeness, even if you were in a space-constrained environment, there is a fast solution that uses $mathcal{O}(1)$ space and $mathcal{O}(nlog{}n)$ time. This solution is worth knowing about for the practicality of the technique and the fact that it's a common interview follow-up. The way it works is:




    1. Sort nums.

    2. Create two pointers representing an index at 0 and an index at len(nums) - 1.

    3. Sum the elements at the pointers.


      • If they produce the desired sum, return the pointer indices.

      • Otherwise, if the sum is less than the target, increment the left pointer

      • Otherwise, decrement the right pointer.



    4. Go back to step 3 unless the pointers are pointing to the same element, in which case return failure.



  • Be wary of list slicing; it's often a hidden linear performance hit. Removing this slice as the nested loop code above illustrates doesn't improve the quadratic time complexity, but it does reduce overhead.



Now you're ready to try 3 Sum!






share|improve this answer











$endgroup$









  • 2




    $begingroup$
    As for returning None, see the relevant section of PEP 8.
    $endgroup$
    – Solomon Ucko
    2 days ago










  • $begingroup$
    That's true, Python does say "explicit is better than implicit". I can amend my recommendation to be "at least be aware that Python statements implicitly return None". Maybe Python should also put else: continue at the end of every loop, just to be explicit :-)
    $endgroup$
    – ggorlen
    2 days ago










  • $begingroup$
    Python should, but doesn't know not to copy the entire thing. It has no such optimisation.
    $endgroup$
    – wizzwizz4
    yesterday










  • $begingroup$
    @wizzwizz4 No lazy copying? E.g. return a pointer in O(1) to the slice element and then wait for mutation to perform a copy? I'd like to update if incorrect here.
    $endgroup$
    – ggorlen
    yesterday










  • $begingroup$
    @ggorlen Apparently not. Try it online! Rule of thumb: Python performs no optimisations at all.
    $endgroup$
    – wizzwizz4
    yesterday





















3












$begingroup$

num_lst = list(range(len(nums)))

for indx, num in enumerate(num_lst):


I'm not sure if I'm missing something, but I think not. I ran this code



nums = [2,5,7,9]
num_lst = list(range(len(nums)))
list(enumerate(num_lst))

output : [(0, 0), (1, 1), (2, 2), (3, 3)]


So why do you create the list and then enumerate it? Maybe what you want to do is simply : enumerate(nums) then enumerate(nums[index+1:]) on your other loop? A simpler way would be to only use the ranges, as I'll show below.



Also, given your input, there's a possibility that a single number would be higher than the target, in this case you shouldn't make the second iteration.



You also don't need the else: continue , as it's going to continue either way.



I'd end up with :



def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for i1 in range(len(nums)):
if nums[i1] >= target:
continue

for i2 in range(i1, len(nums)):
if nums[i1] + nums[i2] == target:
return [i1, i2]

return None


This offers a potential performance boost, and in my opinion the code is clearer.






share|improve this answer









$endgroup$









  • 1




    $begingroup$
    Your code is still O(n**2), so I wouldn't say it offers any significant performance boost.
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    Also, your code has a few bugs. It doesn't work with negative numbers, it doesn't even work with 0 reliably (twoSum([2,0], 2)) and it uses the same number twice (twoSum([1, 1], 2)). :-/
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    @EricDuminil The latter is fine; number != element.
    $endgroup$
    – wizzwizz4
    yesterday






  • 1




    $begingroup$
    @wizzwizz4: Thanks for the comment. You're right. I meant to write twoSum([1], 2), which should return None, not [0, 0]. The bug is here, my description was incorrect.
    $endgroup$
    – Eric Duminil
    yesterday





















2












$begingroup$

You can use itertools.combinations for a more readable (and likely faster) for loop. As long as returning a list isn't a requirement, I would consider it better style to return a tuple instead. (Especially since it allows you to convey the list length.) Also, as long as the current name isn't a requirement, it is preferable to use snake_case for function and variable names.



from itertools import combinations


def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for (i, first), (j, second) in combinations(enumerate(nums), 2):
if first + second == target:
return [i, j]

return None





share|improve this answer











$endgroup$









  • 1




    $begingroup$
    You don't need to create num_list anymore. Also, combinations requires (at least in Python 3.6) a second argument r which specifies the length of the combinations. Here, r should be 2.
    $endgroup$
    – Schmuddi
    yesterday












  • $begingroup$
    Oops, thanks for pointing those out.
    $endgroup$
    – Solomon Ucko
    yesterday



















-1












$begingroup$

Based on the solution by Solomon Ucko, I suggest this solution:



from itertools import combinations

def two_sums(nums, target):
solutions = [(i,j) for (i,x), (j,y) in combinations(enumerate(nums), 2) if x+y==target]
return solutions[0] if len(solutions) > 0 else None





share|improve this answer










New contributor




md2perpe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$



We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.










  • 3




    $begingroup$
    Welcome to Code Review! Please read How do I write a good answer?: "Every answer must make at least one insightful observation about the code in the question." You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    yesterday










  • $begingroup$
    I suppose len(all_solutions) should read len(solutions)?
    $endgroup$
    – Schmuddi
    yesterday










  • $begingroup$
    @Schmuddi. Of course. I've fixed it.
    $endgroup$
    – md2perpe
    21 hours ago











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',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
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%2f212228%2fleetcode-two-sum-code-in-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























4 Answers
4






active

oldest

votes








4 Answers
4






active

oldest

votes









active

oldest

votes






active

oldest

votes









11












$begingroup$

Code Style





  • Your code contains a few lines that accomplish nothing and obfuscate your intent:



        else: 
    continue


    If the conditional is false, you'll automatically continue on to the next iteration without having to tell the program to do that.



        return None


    All Python functions implicitly return None; however, PEP 8 recommends this practice.




  • num_lst = list(range(len(nums))) effectively generates a list of all the indices in the nums input list. Then, you immediately enumerate this list, which produces pairs of identical indices indx, num. If all you're attempting to do is iterate, this is significant obfuscation; simply call enumerate directly on nums to produce index-element tuples:



    def twoSum(self, nums, target):
    for i, num in enumerate(nums):
    for j in range(i + 1, len(nums)):
    if num + nums[j] == target:
    return [i, j]


    This makes the intent much clearer: there are no duplicate variables with different names representing the same thing. It also saves unnecessary space and overhead associated with creating a list from a range.



  • Following on the previous item, indx, num and num_lst are confusing variable names, especially when they're all actually indices (which are technically numbers).




Efficiency





  • This code is inefficient, running in quadratic time, or $mathcal{O}(n^2)$. Leetcode is generous to let this pass (but won't be so forgiving in the future!). The reason for this is the nested loop; for every element in your list, you iterate over every other element to draw comparisons. A linear solution should finish in ~65 ms, while this takes ~4400 ms.



    Here is an efficient solution that runs in $mathcal{O}(n)$ time:



    hist = {}

    for i, n in enumerate(nums):
    if target - n in hist:
    return [hist[target-n], i]
    hist[n] = i


    How does this work? The magic of hashing. The dictionary hist offers constant $mathcal{O}(1)$ lookup time. Whenever we visit a new element in nums, we check to see if its sum complement is in the dictionary; else, we store it in the dictionary as a num => index pair.



    This is the classic time-space tradeoff: the quadratic solution is slow but space efficient, while this solution takes more space but gains a huge boost in speed. In almost every case, choose speed over space.



    For completeness, even if you were in a space-constrained environment, there is a fast solution that uses $mathcal{O}(1)$ space and $mathcal{O}(nlog{}n)$ time. This solution is worth knowing about for the practicality of the technique and the fact that it's a common interview follow-up. The way it works is:




    1. Sort nums.

    2. Create two pointers representing an index at 0 and an index at len(nums) - 1.

    3. Sum the elements at the pointers.


      • If they produce the desired sum, return the pointer indices.

      • Otherwise, if the sum is less than the target, increment the left pointer

      • Otherwise, decrement the right pointer.



    4. Go back to step 3 unless the pointers are pointing to the same element, in which case return failure.



  • Be wary of list slicing; it's often a hidden linear performance hit. Removing this slice as the nested loop code above illustrates doesn't improve the quadratic time complexity, but it does reduce overhead.



Now you're ready to try 3 Sum!






share|improve this answer











$endgroup$









  • 2




    $begingroup$
    As for returning None, see the relevant section of PEP 8.
    $endgroup$
    – Solomon Ucko
    2 days ago










  • $begingroup$
    That's true, Python does say "explicit is better than implicit". I can amend my recommendation to be "at least be aware that Python statements implicitly return None". Maybe Python should also put else: continue at the end of every loop, just to be explicit :-)
    $endgroup$
    – ggorlen
    2 days ago










  • $begingroup$
    Python should, but doesn't know not to copy the entire thing. It has no such optimisation.
    $endgroup$
    – wizzwizz4
    yesterday










  • $begingroup$
    @wizzwizz4 No lazy copying? E.g. return a pointer in O(1) to the slice element and then wait for mutation to perform a copy? I'd like to update if incorrect here.
    $endgroup$
    – ggorlen
    yesterday










  • $begingroup$
    @ggorlen Apparently not. Try it online! Rule of thumb: Python performs no optimisations at all.
    $endgroup$
    – wizzwizz4
    yesterday


















11












$begingroup$

Code Style





  • Your code contains a few lines that accomplish nothing and obfuscate your intent:



        else: 
    continue


    If the conditional is false, you'll automatically continue on to the next iteration without having to tell the program to do that.



        return None


    All Python functions implicitly return None; however, PEP 8 recommends this practice.




  • num_lst = list(range(len(nums))) effectively generates a list of all the indices in the nums input list. Then, you immediately enumerate this list, which produces pairs of identical indices indx, num. If all you're attempting to do is iterate, this is significant obfuscation; simply call enumerate directly on nums to produce index-element tuples:



    def twoSum(self, nums, target):
    for i, num in enumerate(nums):
    for j in range(i + 1, len(nums)):
    if num + nums[j] == target:
    return [i, j]


    This makes the intent much clearer: there are no duplicate variables with different names representing the same thing. It also saves unnecessary space and overhead associated with creating a list from a range.



  • Following on the previous item, indx, num and num_lst are confusing variable names, especially when they're all actually indices (which are technically numbers).




Efficiency





  • This code is inefficient, running in quadratic time, or $mathcal{O}(n^2)$. Leetcode is generous to let this pass (but won't be so forgiving in the future!). The reason for this is the nested loop; for every element in your list, you iterate over every other element to draw comparisons. A linear solution should finish in ~65 ms, while this takes ~4400 ms.



    Here is an efficient solution that runs in $mathcal{O}(n)$ time:



    hist = {}

    for i, n in enumerate(nums):
    if target - n in hist:
    return [hist[target-n], i]
    hist[n] = i


    How does this work? The magic of hashing. The dictionary hist offers constant $mathcal{O}(1)$ lookup time. Whenever we visit a new element in nums, we check to see if its sum complement is in the dictionary; else, we store it in the dictionary as a num => index pair.



    This is the classic time-space tradeoff: the quadratic solution is slow but space efficient, while this solution takes more space but gains a huge boost in speed. In almost every case, choose speed over space.



    For completeness, even if you were in a space-constrained environment, there is a fast solution that uses $mathcal{O}(1)$ space and $mathcal{O}(nlog{}n)$ time. This solution is worth knowing about for the practicality of the technique and the fact that it's a common interview follow-up. The way it works is:




    1. Sort nums.

    2. Create two pointers representing an index at 0 and an index at len(nums) - 1.

    3. Sum the elements at the pointers.


      • If they produce the desired sum, return the pointer indices.

      • Otherwise, if the sum is less than the target, increment the left pointer

      • Otherwise, decrement the right pointer.



    4. Go back to step 3 unless the pointers are pointing to the same element, in which case return failure.



  • Be wary of list slicing; it's often a hidden linear performance hit. Removing this slice as the nested loop code above illustrates doesn't improve the quadratic time complexity, but it does reduce overhead.



Now you're ready to try 3 Sum!






share|improve this answer











$endgroup$









  • 2




    $begingroup$
    As for returning None, see the relevant section of PEP 8.
    $endgroup$
    – Solomon Ucko
    2 days ago










  • $begingroup$
    That's true, Python does say "explicit is better than implicit". I can amend my recommendation to be "at least be aware that Python statements implicitly return None". Maybe Python should also put else: continue at the end of every loop, just to be explicit :-)
    $endgroup$
    – ggorlen
    2 days ago










  • $begingroup$
    Python should, but doesn't know not to copy the entire thing. It has no such optimisation.
    $endgroup$
    – wizzwizz4
    yesterday










  • $begingroup$
    @wizzwizz4 No lazy copying? E.g. return a pointer in O(1) to the slice element and then wait for mutation to perform a copy? I'd like to update if incorrect here.
    $endgroup$
    – ggorlen
    yesterday










  • $begingroup$
    @ggorlen Apparently not. Try it online! Rule of thumb: Python performs no optimisations at all.
    $endgroup$
    – wizzwizz4
    yesterday
















11












11








11





$begingroup$

Code Style





  • Your code contains a few lines that accomplish nothing and obfuscate your intent:



        else: 
    continue


    If the conditional is false, you'll automatically continue on to the next iteration without having to tell the program to do that.



        return None


    All Python functions implicitly return None; however, PEP 8 recommends this practice.




  • num_lst = list(range(len(nums))) effectively generates a list of all the indices in the nums input list. Then, you immediately enumerate this list, which produces pairs of identical indices indx, num. If all you're attempting to do is iterate, this is significant obfuscation; simply call enumerate directly on nums to produce index-element tuples:



    def twoSum(self, nums, target):
    for i, num in enumerate(nums):
    for j in range(i + 1, len(nums)):
    if num + nums[j] == target:
    return [i, j]


    This makes the intent much clearer: there are no duplicate variables with different names representing the same thing. It also saves unnecessary space and overhead associated with creating a list from a range.



  • Following on the previous item, indx, num and num_lst are confusing variable names, especially when they're all actually indices (which are technically numbers).




Efficiency





  • This code is inefficient, running in quadratic time, or $mathcal{O}(n^2)$. Leetcode is generous to let this pass (but won't be so forgiving in the future!). The reason for this is the nested loop; for every element in your list, you iterate over every other element to draw comparisons. A linear solution should finish in ~65 ms, while this takes ~4400 ms.



    Here is an efficient solution that runs in $mathcal{O}(n)$ time:



    hist = {}

    for i, n in enumerate(nums):
    if target - n in hist:
    return [hist[target-n], i]
    hist[n] = i


    How does this work? The magic of hashing. The dictionary hist offers constant $mathcal{O}(1)$ lookup time. Whenever we visit a new element in nums, we check to see if its sum complement is in the dictionary; else, we store it in the dictionary as a num => index pair.



    This is the classic time-space tradeoff: the quadratic solution is slow but space efficient, while this solution takes more space but gains a huge boost in speed. In almost every case, choose speed over space.



    For completeness, even if you were in a space-constrained environment, there is a fast solution that uses $mathcal{O}(1)$ space and $mathcal{O}(nlog{}n)$ time. This solution is worth knowing about for the practicality of the technique and the fact that it's a common interview follow-up. The way it works is:




    1. Sort nums.

    2. Create two pointers representing an index at 0 and an index at len(nums) - 1.

    3. Sum the elements at the pointers.


      • If they produce the desired sum, return the pointer indices.

      • Otherwise, if the sum is less than the target, increment the left pointer

      • Otherwise, decrement the right pointer.



    4. Go back to step 3 unless the pointers are pointing to the same element, in which case return failure.



  • Be wary of list slicing; it's often a hidden linear performance hit. Removing this slice as the nested loop code above illustrates doesn't improve the quadratic time complexity, but it does reduce overhead.



Now you're ready to try 3 Sum!






share|improve this answer











$endgroup$



Code Style





  • Your code contains a few lines that accomplish nothing and obfuscate your intent:



        else: 
    continue


    If the conditional is false, you'll automatically continue on to the next iteration without having to tell the program to do that.



        return None


    All Python functions implicitly return None; however, PEP 8 recommends this practice.




  • num_lst = list(range(len(nums))) effectively generates a list of all the indices in the nums input list. Then, you immediately enumerate this list, which produces pairs of identical indices indx, num. If all you're attempting to do is iterate, this is significant obfuscation; simply call enumerate directly on nums to produce index-element tuples:



    def twoSum(self, nums, target):
    for i, num in enumerate(nums):
    for j in range(i + 1, len(nums)):
    if num + nums[j] == target:
    return [i, j]


    This makes the intent much clearer: there are no duplicate variables with different names representing the same thing. It also saves unnecessary space and overhead associated with creating a list from a range.



  • Following on the previous item, indx, num and num_lst are confusing variable names, especially when they're all actually indices (which are technically numbers).




Efficiency





  • This code is inefficient, running in quadratic time, or $mathcal{O}(n^2)$. Leetcode is generous to let this pass (but won't be so forgiving in the future!). The reason for this is the nested loop; for every element in your list, you iterate over every other element to draw comparisons. A linear solution should finish in ~65 ms, while this takes ~4400 ms.



    Here is an efficient solution that runs in $mathcal{O}(n)$ time:



    hist = {}

    for i, n in enumerate(nums):
    if target - n in hist:
    return [hist[target-n], i]
    hist[n] = i


    How does this work? The magic of hashing. The dictionary hist offers constant $mathcal{O}(1)$ lookup time. Whenever we visit a new element in nums, we check to see if its sum complement is in the dictionary; else, we store it in the dictionary as a num => index pair.



    This is the classic time-space tradeoff: the quadratic solution is slow but space efficient, while this solution takes more space but gains a huge boost in speed. In almost every case, choose speed over space.



    For completeness, even if you were in a space-constrained environment, there is a fast solution that uses $mathcal{O}(1)$ space and $mathcal{O}(nlog{}n)$ time. This solution is worth knowing about for the practicality of the technique and the fact that it's a common interview follow-up. The way it works is:




    1. Sort nums.

    2. Create two pointers representing an index at 0 and an index at len(nums) - 1.

    3. Sum the elements at the pointers.


      • If they produce the desired sum, return the pointer indices.

      • Otherwise, if the sum is less than the target, increment the left pointer

      • Otherwise, decrement the right pointer.



    4. Go back to step 3 unless the pointers are pointing to the same element, in which case return failure.



  • Be wary of list slicing; it's often a hidden linear performance hit. Removing this slice as the nested loop code above illustrates doesn't improve the quadratic time complexity, but it does reduce overhead.



Now you're ready to try 3 Sum!







share|improve this answer














share|improve this answer



share|improve this answer








edited yesterday

























answered 2 days ago









ggorlenggorlen

3738




3738








  • 2




    $begingroup$
    As for returning None, see the relevant section of PEP 8.
    $endgroup$
    – Solomon Ucko
    2 days ago










  • $begingroup$
    That's true, Python does say "explicit is better than implicit". I can amend my recommendation to be "at least be aware that Python statements implicitly return None". Maybe Python should also put else: continue at the end of every loop, just to be explicit :-)
    $endgroup$
    – ggorlen
    2 days ago










  • $begingroup$
    Python should, but doesn't know not to copy the entire thing. It has no such optimisation.
    $endgroup$
    – wizzwizz4
    yesterday










  • $begingroup$
    @wizzwizz4 No lazy copying? E.g. return a pointer in O(1) to the slice element and then wait for mutation to perform a copy? I'd like to update if incorrect here.
    $endgroup$
    – ggorlen
    yesterday










  • $begingroup$
    @ggorlen Apparently not. Try it online! Rule of thumb: Python performs no optimisations at all.
    $endgroup$
    – wizzwizz4
    yesterday
















  • 2




    $begingroup$
    As for returning None, see the relevant section of PEP 8.
    $endgroup$
    – Solomon Ucko
    2 days ago










  • $begingroup$
    That's true, Python does say "explicit is better than implicit". I can amend my recommendation to be "at least be aware that Python statements implicitly return None". Maybe Python should also put else: continue at the end of every loop, just to be explicit :-)
    $endgroup$
    – ggorlen
    2 days ago










  • $begingroup$
    Python should, but doesn't know not to copy the entire thing. It has no such optimisation.
    $endgroup$
    – wizzwizz4
    yesterday










  • $begingroup$
    @wizzwizz4 No lazy copying? E.g. return a pointer in O(1) to the slice element and then wait for mutation to perform a copy? I'd like to update if incorrect here.
    $endgroup$
    – ggorlen
    yesterday










  • $begingroup$
    @ggorlen Apparently not. Try it online! Rule of thumb: Python performs no optimisations at all.
    $endgroup$
    – wizzwizz4
    yesterday










2




2




$begingroup$
As for returning None, see the relevant section of PEP 8.
$endgroup$
– Solomon Ucko
2 days ago




$begingroup$
As for returning None, see the relevant section of PEP 8.
$endgroup$
– Solomon Ucko
2 days ago












$begingroup$
That's true, Python does say "explicit is better than implicit". I can amend my recommendation to be "at least be aware that Python statements implicitly return None". Maybe Python should also put else: continue at the end of every loop, just to be explicit :-)
$endgroup$
– ggorlen
2 days ago




$begingroup$
That's true, Python does say "explicit is better than implicit". I can amend my recommendation to be "at least be aware that Python statements implicitly return None". Maybe Python should also put else: continue at the end of every loop, just to be explicit :-)
$endgroup$
– ggorlen
2 days ago












$begingroup$
Python should, but doesn't know not to copy the entire thing. It has no such optimisation.
$endgroup$
– wizzwizz4
yesterday




$begingroup$
Python should, but doesn't know not to copy the entire thing. It has no such optimisation.
$endgroup$
– wizzwizz4
yesterday












$begingroup$
@wizzwizz4 No lazy copying? E.g. return a pointer in O(1) to the slice element and then wait for mutation to perform a copy? I'd like to update if incorrect here.
$endgroup$
– ggorlen
yesterday




$begingroup$
@wizzwizz4 No lazy copying? E.g. return a pointer in O(1) to the slice element and then wait for mutation to perform a copy? I'd like to update if incorrect here.
$endgroup$
– ggorlen
yesterday












$begingroup$
@ggorlen Apparently not. Try it online! Rule of thumb: Python performs no optimisations at all.
$endgroup$
– wizzwizz4
yesterday






$begingroup$
@ggorlen Apparently not. Try it online! Rule of thumb: Python performs no optimisations at all.
$endgroup$
– wizzwizz4
yesterday















3












$begingroup$

num_lst = list(range(len(nums)))

for indx, num in enumerate(num_lst):


I'm not sure if I'm missing something, but I think not. I ran this code



nums = [2,5,7,9]
num_lst = list(range(len(nums)))
list(enumerate(num_lst))

output : [(0, 0), (1, 1), (2, 2), (3, 3)]


So why do you create the list and then enumerate it? Maybe what you want to do is simply : enumerate(nums) then enumerate(nums[index+1:]) on your other loop? A simpler way would be to only use the ranges, as I'll show below.



Also, given your input, there's a possibility that a single number would be higher than the target, in this case you shouldn't make the second iteration.



You also don't need the else: continue , as it's going to continue either way.



I'd end up with :



def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for i1 in range(len(nums)):
if nums[i1] >= target:
continue

for i2 in range(i1, len(nums)):
if nums[i1] + nums[i2] == target:
return [i1, i2]

return None


This offers a potential performance boost, and in my opinion the code is clearer.






share|improve this answer









$endgroup$









  • 1




    $begingroup$
    Your code is still O(n**2), so I wouldn't say it offers any significant performance boost.
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    Also, your code has a few bugs. It doesn't work with negative numbers, it doesn't even work with 0 reliably (twoSum([2,0], 2)) and it uses the same number twice (twoSum([1, 1], 2)). :-/
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    @EricDuminil The latter is fine; number != element.
    $endgroup$
    – wizzwizz4
    yesterday






  • 1




    $begingroup$
    @wizzwizz4: Thanks for the comment. You're right. I meant to write twoSum([1], 2), which should return None, not [0, 0]. The bug is here, my description was incorrect.
    $endgroup$
    – Eric Duminil
    yesterday


















3












$begingroup$

num_lst = list(range(len(nums)))

for indx, num in enumerate(num_lst):


I'm not sure if I'm missing something, but I think not. I ran this code



nums = [2,5,7,9]
num_lst = list(range(len(nums)))
list(enumerate(num_lst))

output : [(0, 0), (1, 1), (2, 2), (3, 3)]


So why do you create the list and then enumerate it? Maybe what you want to do is simply : enumerate(nums) then enumerate(nums[index+1:]) on your other loop? A simpler way would be to only use the ranges, as I'll show below.



Also, given your input, there's a possibility that a single number would be higher than the target, in this case you shouldn't make the second iteration.



You also don't need the else: continue , as it's going to continue either way.



I'd end up with :



def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for i1 in range(len(nums)):
if nums[i1] >= target:
continue

for i2 in range(i1, len(nums)):
if nums[i1] + nums[i2] == target:
return [i1, i2]

return None


This offers a potential performance boost, and in my opinion the code is clearer.






share|improve this answer









$endgroup$









  • 1




    $begingroup$
    Your code is still O(n**2), so I wouldn't say it offers any significant performance boost.
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    Also, your code has a few bugs. It doesn't work with negative numbers, it doesn't even work with 0 reliably (twoSum([2,0], 2)) and it uses the same number twice (twoSum([1, 1], 2)). :-/
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    @EricDuminil The latter is fine; number != element.
    $endgroup$
    – wizzwizz4
    yesterday






  • 1




    $begingroup$
    @wizzwizz4: Thanks for the comment. You're right. I meant to write twoSum([1], 2), which should return None, not [0, 0]. The bug is here, my description was incorrect.
    $endgroup$
    – Eric Duminil
    yesterday
















3












3








3





$begingroup$

num_lst = list(range(len(nums)))

for indx, num in enumerate(num_lst):


I'm not sure if I'm missing something, but I think not. I ran this code



nums = [2,5,7,9]
num_lst = list(range(len(nums)))
list(enumerate(num_lst))

output : [(0, 0), (1, 1), (2, 2), (3, 3)]


So why do you create the list and then enumerate it? Maybe what you want to do is simply : enumerate(nums) then enumerate(nums[index+1:]) on your other loop? A simpler way would be to only use the ranges, as I'll show below.



Also, given your input, there's a possibility that a single number would be higher than the target, in this case you shouldn't make the second iteration.



You also don't need the else: continue , as it's going to continue either way.



I'd end up with :



def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for i1 in range(len(nums)):
if nums[i1] >= target:
continue

for i2 in range(i1, len(nums)):
if nums[i1] + nums[i2] == target:
return [i1, i2]

return None


This offers a potential performance boost, and in my opinion the code is clearer.






share|improve this answer









$endgroup$



num_lst = list(range(len(nums)))

for indx, num in enumerate(num_lst):


I'm not sure if I'm missing something, but I think not. I ran this code



nums = [2,5,7,9]
num_lst = list(range(len(nums)))
list(enumerate(num_lst))

output : [(0, 0), (1, 1), (2, 2), (3, 3)]


So why do you create the list and then enumerate it? Maybe what you want to do is simply : enumerate(nums) then enumerate(nums[index+1:]) on your other loop? A simpler way would be to only use the ranges, as I'll show below.



Also, given your input, there's a possibility that a single number would be higher than the target, in this case you shouldn't make the second iteration.



You also don't need the else: continue , as it's going to continue either way.



I'd end up with :



def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for i1 in range(len(nums)):
if nums[i1] >= target:
continue

for i2 in range(i1, len(nums)):
if nums[i1] + nums[i2] == target:
return [i1, i2]

return None


This offers a potential performance boost, and in my opinion the code is clearer.







share|improve this answer












share|improve this answer



share|improve this answer










answered 2 days ago









IEatBagelsIEatBagels

8,90623278




8,90623278








  • 1




    $begingroup$
    Your code is still O(n**2), so I wouldn't say it offers any significant performance boost.
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    Also, your code has a few bugs. It doesn't work with negative numbers, it doesn't even work with 0 reliably (twoSum([2,0], 2)) and it uses the same number twice (twoSum([1, 1], 2)). :-/
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    @EricDuminil The latter is fine; number != element.
    $endgroup$
    – wizzwizz4
    yesterday






  • 1




    $begingroup$
    @wizzwizz4: Thanks for the comment. You're right. I meant to write twoSum([1], 2), which should return None, not [0, 0]. The bug is here, my description was incorrect.
    $endgroup$
    – Eric Duminil
    yesterday
















  • 1




    $begingroup$
    Your code is still O(n**2), so I wouldn't say it offers any significant performance boost.
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    Also, your code has a few bugs. It doesn't work with negative numbers, it doesn't even work with 0 reliably (twoSum([2,0], 2)) and it uses the same number twice (twoSum([1, 1], 2)). :-/
    $endgroup$
    – Eric Duminil
    yesterday










  • $begingroup$
    @EricDuminil The latter is fine; number != element.
    $endgroup$
    – wizzwizz4
    yesterday






  • 1




    $begingroup$
    @wizzwizz4: Thanks for the comment. You're right. I meant to write twoSum([1], 2), which should return None, not [0, 0]. The bug is here, my description was incorrect.
    $endgroup$
    – Eric Duminil
    yesterday










1




1




$begingroup$
Your code is still O(n**2), so I wouldn't say it offers any significant performance boost.
$endgroup$
– Eric Duminil
yesterday




$begingroup$
Your code is still O(n**2), so I wouldn't say it offers any significant performance boost.
$endgroup$
– Eric Duminil
yesterday












$begingroup$
Also, your code has a few bugs. It doesn't work with negative numbers, it doesn't even work with 0 reliably (twoSum([2,0], 2)) and it uses the same number twice (twoSum([1, 1], 2)). :-/
$endgroup$
– Eric Duminil
yesterday




$begingroup$
Also, your code has a few bugs. It doesn't work with negative numbers, it doesn't even work with 0 reliably (twoSum([2,0], 2)) and it uses the same number twice (twoSum([1, 1], 2)). :-/
$endgroup$
– Eric Duminil
yesterday












$begingroup$
@EricDuminil The latter is fine; number != element.
$endgroup$
– wizzwizz4
yesterday




$begingroup$
@EricDuminil The latter is fine; number != element.
$endgroup$
– wizzwizz4
yesterday




1




1




$begingroup$
@wizzwizz4: Thanks for the comment. You're right. I meant to write twoSum([1], 2), which should return None, not [0, 0]. The bug is here, my description was incorrect.
$endgroup$
– Eric Duminil
yesterday






$begingroup$
@wizzwizz4: Thanks for the comment. You're right. I meant to write twoSum([1], 2), which should return None, not [0, 0]. The bug is here, my description was incorrect.
$endgroup$
– Eric Duminil
yesterday













2












$begingroup$

You can use itertools.combinations for a more readable (and likely faster) for loop. As long as returning a list isn't a requirement, I would consider it better style to return a tuple instead. (Especially since it allows you to convey the list length.) Also, as long as the current name isn't a requirement, it is preferable to use snake_case for function and variable names.



from itertools import combinations


def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for (i, first), (j, second) in combinations(enumerate(nums), 2):
if first + second == target:
return [i, j]

return None





share|improve this answer











$endgroup$









  • 1




    $begingroup$
    You don't need to create num_list anymore. Also, combinations requires (at least in Python 3.6) a second argument r which specifies the length of the combinations. Here, r should be 2.
    $endgroup$
    – Schmuddi
    yesterday












  • $begingroup$
    Oops, thanks for pointing those out.
    $endgroup$
    – Solomon Ucko
    yesterday
















2












$begingroup$

You can use itertools.combinations for a more readable (and likely faster) for loop. As long as returning a list isn't a requirement, I would consider it better style to return a tuple instead. (Especially since it allows you to convey the list length.) Also, as long as the current name isn't a requirement, it is preferable to use snake_case for function and variable names.



from itertools import combinations


def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for (i, first), (j, second) in combinations(enumerate(nums), 2):
if first + second == target:
return [i, j]

return None





share|improve this answer











$endgroup$









  • 1




    $begingroup$
    You don't need to create num_list anymore. Also, combinations requires (at least in Python 3.6) a second argument r which specifies the length of the combinations. Here, r should be 2.
    $endgroup$
    – Schmuddi
    yesterday












  • $begingroup$
    Oops, thanks for pointing those out.
    $endgroup$
    – Solomon Ucko
    yesterday














2












2








2





$begingroup$

You can use itertools.combinations for a more readable (and likely faster) for loop. As long as returning a list isn't a requirement, I would consider it better style to return a tuple instead. (Especially since it allows you to convey the list length.) Also, as long as the current name isn't a requirement, it is preferable to use snake_case for function and variable names.



from itertools import combinations


def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for (i, first), (j, second) in combinations(enumerate(nums), 2):
if first + second == target:
return [i, j]

return None





share|improve this answer











$endgroup$



You can use itertools.combinations for a more readable (and likely faster) for loop. As long as returning a list isn't a requirement, I would consider it better style to return a tuple instead. (Especially since it allows you to convey the list length.) Also, as long as the current name isn't a requirement, it is preferable to use snake_case for function and variable names.



from itertools import combinations


def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

for (i, first), (j, second) in combinations(enumerate(nums), 2):
if first + second == target:
return [i, j]

return None






share|improve this answer














share|improve this answer



share|improve this answer








edited yesterday

























answered 2 days ago









Solomon UckoSolomon Ucko

1,060415




1,060415








  • 1




    $begingroup$
    You don't need to create num_list anymore. Also, combinations requires (at least in Python 3.6) a second argument r which specifies the length of the combinations. Here, r should be 2.
    $endgroup$
    – Schmuddi
    yesterday












  • $begingroup$
    Oops, thanks for pointing those out.
    $endgroup$
    – Solomon Ucko
    yesterday














  • 1




    $begingroup$
    You don't need to create num_list anymore. Also, combinations requires (at least in Python 3.6) a second argument r which specifies the length of the combinations. Here, r should be 2.
    $endgroup$
    – Schmuddi
    yesterday












  • $begingroup$
    Oops, thanks for pointing those out.
    $endgroup$
    – Solomon Ucko
    yesterday








1




1




$begingroup$
You don't need to create num_list anymore. Also, combinations requires (at least in Python 3.6) a second argument r which specifies the length of the combinations. Here, r should be 2.
$endgroup$
– Schmuddi
yesterday






$begingroup$
You don't need to create num_list anymore. Also, combinations requires (at least in Python 3.6) a second argument r which specifies the length of the combinations. Here, r should be 2.
$endgroup$
– Schmuddi
yesterday














$begingroup$
Oops, thanks for pointing those out.
$endgroup$
– Solomon Ucko
yesterday




$begingroup$
Oops, thanks for pointing those out.
$endgroup$
– Solomon Ucko
yesterday











-1












$begingroup$

Based on the solution by Solomon Ucko, I suggest this solution:



from itertools import combinations

def two_sums(nums, target):
solutions = [(i,j) for (i,x), (j,y) in combinations(enumerate(nums), 2) if x+y==target]
return solutions[0] if len(solutions) > 0 else None





share|improve this answer










New contributor




md2perpe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$



We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.










  • 3




    $begingroup$
    Welcome to Code Review! Please read How do I write a good answer?: "Every answer must make at least one insightful observation about the code in the question." You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    yesterday










  • $begingroup$
    I suppose len(all_solutions) should read len(solutions)?
    $endgroup$
    – Schmuddi
    yesterday










  • $begingroup$
    @Schmuddi. Of course. I've fixed it.
    $endgroup$
    – md2perpe
    21 hours ago
















-1












$begingroup$

Based on the solution by Solomon Ucko, I suggest this solution:



from itertools import combinations

def two_sums(nums, target):
solutions = [(i,j) for (i,x), (j,y) in combinations(enumerate(nums), 2) if x+y==target]
return solutions[0] if len(solutions) > 0 else None





share|improve this answer










New contributor




md2perpe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$



We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.










  • 3




    $begingroup$
    Welcome to Code Review! Please read How do I write a good answer?: "Every answer must make at least one insightful observation about the code in the question." You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    yesterday










  • $begingroup$
    I suppose len(all_solutions) should read len(solutions)?
    $endgroup$
    – Schmuddi
    yesterday










  • $begingroup$
    @Schmuddi. Of course. I've fixed it.
    $endgroup$
    – md2perpe
    21 hours ago














-1












-1








-1





$begingroup$

Based on the solution by Solomon Ucko, I suggest this solution:



from itertools import combinations

def two_sums(nums, target):
solutions = [(i,j) for (i,x), (j,y) in combinations(enumerate(nums), 2) if x+y==target]
return solutions[0] if len(solutions) > 0 else None





share|improve this answer










New contributor




md2perpe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$



Based on the solution by Solomon Ucko, I suggest this solution:



from itertools import combinations

def two_sums(nums, target):
solutions = [(i,j) for (i,x), (j,y) in combinations(enumerate(nums), 2) if x+y==target]
return solutions[0] if len(solutions) > 0 else None






share|improve this answer










New contributor




md2perpe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this answer



share|improve this answer








edited 21 hours ago





















New contributor




md2perpe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









answered yesterday









md2perpemd2perpe

992




992




New contributor




md2perpe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





md2perpe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






md2perpe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.



We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.




We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.









  • 3




    $begingroup$
    Welcome to Code Review! Please read How do I write a good answer?: "Every answer must make at least one insightful observation about the code in the question." You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    yesterday










  • $begingroup$
    I suppose len(all_solutions) should read len(solutions)?
    $endgroup$
    – Schmuddi
    yesterday










  • $begingroup$
    @Schmuddi. Of course. I've fixed it.
    $endgroup$
    – md2perpe
    21 hours ago














  • 3




    $begingroup$
    Welcome to Code Review! Please read How do I write a good answer?: "Every answer must make at least one insightful observation about the code in the question." You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    yesterday










  • $begingroup$
    I suppose len(all_solutions) should read len(solutions)?
    $endgroup$
    – Schmuddi
    yesterday










  • $begingroup$
    @Schmuddi. Of course. I've fixed it.
    $endgroup$
    – md2perpe
    21 hours ago








3




3




$begingroup$
Welcome to Code Review! Please read How do I write a good answer?: "Every answer must make at least one insightful observation about the code in the question." You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
yesterday




$begingroup$
Welcome to Code Review! Please read How do I write a good answer?: "Every answer must make at least one insightful observation about the code in the question." You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
yesterday












$begingroup$
I suppose len(all_solutions) should read len(solutions)?
$endgroup$
– Schmuddi
yesterday




$begingroup$
I suppose len(all_solutions) should read len(solutions)?
$endgroup$
– Schmuddi
yesterday












$begingroup$
@Schmuddi. Of course. I've fixed it.
$endgroup$
– md2perpe
21 hours ago




$begingroup$
@Schmuddi. Of course. I've fixed it.
$endgroup$
– md2perpe
21 hours ago


















draft saved

draft discarded




















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212228%2fleetcode-two-sum-code-in-python%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

"Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

Alcedinidae

RAC Tourist Trophy