How to optimize this LeetCode solution for Two Sum #1
-
This works, but the time complexity is O(n²). 👉 Could someone explain how to improve this solution and reduce the complexity?
|
Beta Was this translation helpful? Give feedback.
Answered by
SpringStar-dev
Sep 12, 2025
Replies: 1 comment 1 reply
-
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.
1 reply
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: