Skip to content
Discussion options

You must be logged in to vote

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:

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

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@codechallenger000
Comment options

@codechallenger000
Comment options

Answer selected by codechallenger000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
help wanted Extra attention is needed
2 participants