DEV Community

Sharmila devi
Sharmila devi

Posted on

Two Sum & Sorted Two Sum

✅ Problem Statement 1: Two Sum using Dictionary
Objective

Identify two values in a list whose sum equals a given target.

Approach

Rather than examining every possible pair, we use a dictionary to remember values we have already processed.

For each element, compute the difference (target - current value)
Check whether this difference already exists in the dictionary
If it does, we have found the required pair
If not, store the current value along with its index for future reference Code
def two_sum(nums, target):
seen = {}
for i in range(len(nums)):
needed = target - nums[i]
if needed in seen:
return [seen[needed], i]
seen[nums[i]] = i

✅ Problem Statement 2: Two Sum using Two Pointers (Sorted List) Objective

Find two elements in a sorted list whose total equals the target value.

Approach

Because the list is already sorted, we apply the two-pointer technique:

Initialize one pointer at the start (left) and another at the end (right)
Add the values at both pointers
If the sum matches the target → return the indices
If the sum is smaller → move the left pointer forward to increase the sum
If the sum is larger → move the right pointer backward to reduce the sum
Code
def two_sum(numbers, target):
left = 0
right = len(numbers) - 1

while left < right:
    s = numbers[left] + numbers[right]

    if s == target:
        return [left + 1, right + 1]
    elif s < target:
        left += 1
    else:
        right -= 1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)