Introduction
The Two Sum problem is one of the most popular questions in programming interviews. It helps in understanding arrays, hashing, and two-pointer techniques.
Problem Statement
Two Sum
Given an array of integers and a target value, return the indices of the two numbers such that they add up to the target.
Two Sum II (Sorted Array)
Given a sorted array, find two numbers such that they add up to a target. Return their indices.
💡 Approach 1: Two Sum (Using Hash Map)
- Create a dictionary to store numbers and their indices
- For each element:
- Find complement = target - element
- Check if complement exists in dictionary
- If yes → return indices
Python Code (Two Sum)
python
def two_sum(nums, target):
hashmap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
Approach 2: Two Sum II (Sorted Array - Two Pointer)
Use two pointers:
left = 0
right = n - 1
Calculate sum:
If sum == target → return indices
If sum < target → move left
If sum > target → move right
python code (sorted Two sum)
def two_sum_sorted(nums, target):
left, right = 0, len(nums) - 1
while left < right:
total = nums[left] + nums[right]
if total == target:
return [left, right]
elif total < target:
left += 1
else:
right -= 1
## Input
nums = [2, 7, 11, 15]
target = 9
## output
[0,1]
Top comments (0)