DEV Community

Jonah Blessy
Jonah Blessy

Posted on

Two Sum & Sorted Two Sum

Problem Statement 1: here

  • The goal is to find two numbers in the list that add up to the given target.
  • Instead of checking every pair, we keep track of the numbers already seen.
  • For each number, we see what value is needed to reach the target.
  • Then check if that required value has already appeared in the list.
  • If it has, the solution is found using the index of those two numbers.
  • If not, store the current number so it can be used for future checks.
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
Enter fullscreen mode Exit fullscreen mode

Problem Statement2:

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
  • The array is already sorted, so instead of checking every pair, we can use pointers at the beginning and end.
  • At each step, the sum of these two numbers is checked.
  • If the sum is equal to the target, the answer is found.
  • If the sum is smaller than the target, left++ to increase the sum.
  • If the sum is larger, right-- to decrease the sum.
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)