Teaching Kids Programming – Three Sum Algorithm


Teaching Kids Programming: Videos on Data Structures and Algorithms

Given an array of numbers and a target, find out if there is any three numbers that sum up to target.

Three Sum Algorithm

We can sort the array in O(NLogN) time. Then, iterate the first number with O(N), and then we can apply Two Sum on the subarray on the right.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def threeSum(nums, target):
  nums.sort() # O(NLogN)
  n = len(nums)
  for i in range(n):
    j, k = i + 1, n - 1
    while j < k:  # two sum
      s = nums[i] + nums[j] + nums[i]
      if s == target:
        return True
      elif s > target:
        k -= 1
      else:
        j += 1
  return False
def threeSum(nums, target):
  nums.sort() # O(NLogN)
  n = len(nums)
  for i in range(n):
    j, k = i + 1, n - 1
    while j < k:  # two sum
      s = nums[i] + nums[j] + nums[i]
      if s == target:
        return True
      elif s > target:
        k -= 1
      else:
        j += 1
  return False

Time complexity is O(N^2). The sorting is trivial O(NLogN) compared to Three Sum algorithm O(N^2). The space complexity is O(1) constant.

See also: How to Find the Closest Sum of Three in an Array using Two Pointer Algorithm? (3Sum Closest)

Two Sum Variation Problems

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
301 words
Last Post: Counting the Only Child in the Binary Tree using Breadth First Search Algorithm
Next Post: Dynamic Programming Algorithm to Count Contiguous Arithmetic Sequences

The Permanent URL is: Teaching Kids Programming – Three Sum Algorithm

Leave a Reply