How to optimize this LeetCode solution for Two Sum #2
-
I’m working on the classic Two Sum problem from LeetCode:
Here’s my current solution in Python: def twoSum(nums, target):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j] |
Beta Was this translation helpful? Give feedback.
Answered by
SpringStar-dev
Sep 12, 2025
Replies: 1 comment 2 replies
-
You’re right that your current solution is O(n²) because it checks every pair. Here’s the Python version: def twoSum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
codechallenger000
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You’re right that your current solution is O(n²) because it checks every pair.
A more optimal approach is to use a hash map (dictionary) so you can check in constant time if the complement exists.
Here’s the Python version: