ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Two Sum Problem (Two Pointers)

Python

Goal -- WPM

Ready
Exercise Algorithm Area
1def twoSumSorted(numbers, target):
2"""Finds two numbers in a sorted array that add up to a target using two pointers."""
3left = 0
4right = len(numbers) - 1
5
6# Handle edge case: empty or single-element array
7if len(numbers) < 2:
8return []
9
10while left < right:
11current_sum = numbers[left] + numbers[right]
12
13if current_sum == target:
14# Found the pair, return their 1-based indices
15return [left + 1, right + 1]
16elif current_sum < target:
17# Sum is too small, move the left pointer to increase the sum
18left += 1
19else: # current_sum > target
20# Sum is too large, move the right pointer to decrease the sum
21right -= 1
22
23# If no solution is found after the loop
24return []
Algorithm description viewbox

Two Sum Problem (Two Pointers)

Algorithm description:

The Two Sum problem is a fundamental algorithm challenge where you need to find two numbers in an array that add up to a specific target value. This implementation uses the two-pointer technique on a sorted array, which is efficient for this task. It's a common building block for more complex problems involving finding pairs or triplets with specific sums.

Algorithm explanation:

This solution utilizes the two-pointer technique on a sorted array. One pointer (`left`) starts at the beginning of the array, and another pointer (`right`) starts at the end. The sum of the elements at these pointers is compared to the target. If the sum equals the target, the indices are returned. If the sum is less than the target, the `left` pointer is moved to the right to increase the sum. If the sum is greater than the target, the `right` pointer is moved to the left to decrease the sum. This process continues until the pointers meet or cross. The time complexity is O(n) because each pointer traverses the array at most once. The space complexity is O(1) as it uses a constant amount of extra space. Edge cases include empty or single-element arrays, and cases where no pair sums to the target.

Pseudocode:

function twoSumSorted(numbers, target):
  left = 0
  right = length of numbers - 1

  if length of numbers < 2:
    return empty list

  while left < right:
    current_sum = numbers[left] + numbers[right]
    if current_sum == target:
      return [left + 1, right + 1]
    else if current_sum < target:
      left = left + 1
    else: # current_sum > target
      right = right - 1

  return empty list