r/LeetcodeChallenge • u/aryandev87 • 3h ago
STREAK🔥🔥🔥 LeetCode 1: Two Sum | My Approach in Python
Hey everyone!
I recently started documenting my DSA journey, and I'm sharing my solution to the first LeetCode problem — Two Sum.
Honestly, I've solved this problem before, so it didn't take me long to figure out the approach. Still, I wanted to explain how I approached it.
Problem
Given an array of integers nums and an integertarget, return the indices of two numbers whose sum equals the target.
We cannot use the same element twice, and exactly one valid solution is guaranteed.
My Approach
I used a Python dictionary (HashMap) to solve this problem.
The idea is simple:
Create a dictionary named
seento store numbers and their corresponding indices.Traverse the array starting from the second element.
Calculate the complement using
target - nums[i].Check whether the complement already exists in the dictionary.
If it exists, return the indices of both elements.
Otherwise, store the current number and its index in the dictionary.
This way, we don't need to check every possible pair using nested loops.
Python Code
class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
seen = {nums[0]: 0}
for i in range(1, len(nums)):
complement = target - nums[i]
if complement in seen:
return [seen[complement], i]
seen[nums[i]] = i
return []Complexity Analysis
Time Complexity: O(n) average
Space Complexity: O(n)
We traverse the array once and use a dictionary for efficient lookups.
LeetCode Solution
View my submitted solution here
I'm still learning and trying to improve my problem-solving skills.
I'd appreciate feedback on my approach, explanation, or code. Is there anything I could have explained better?
Thanks!



