I'm practicing some problems and started trying different solutions for the two-sum problem.
My first solution is the following:
nums = [2,7,11,15]
target = 9
def twoSum(nums: List[int], target: int) -> List[int]:
"""Given an array and a target, return the indexes of the elements adding to the target"""
nums_len = len(nums)
result = []
for first in range(nums_len):
for second in range(first + 1, nums_len):
if len(result) == 2: break
if nums[first] + nums[second] == target:
result.extend([first, second])
else:
continue
break
return result
twoSum(nums, target) # returns [0,1] (sum of 2 and 7 = 9)
This solution got a runtime and memory usage of 8385 ms and 15.1 MB, respectively.
When trying to improve the code and readability, I decided to use a generator instead of having those else, continue, break statements at the end of the loops. Here's the code:
def double_loop(arr):
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
yield [i, j]
def twoSum(nums: List[int], target: int) -> List[int]:
for result in double_loop(nums):
if nums[result[0]] + nums[result[1]] == target:
break
return result
nums = [2,7,11,15]
target = 9
twoSum(nums, target) # returns the same as above
The issue is when I submit to Leetcode and it runs different inputs. Especially one where nums = [1, 2, 3, ..., 9999,10000]
and target = 19999
. I get a Time Limit Exceeded
error.
Why is the second solution apparently wasting more resources and timing out? Can someone explain what's wrong with that approach?