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
- Teaching Kids Programming - Two Sum in Binary Search Tree via Inorder and Two Pointer Algorithm
- Teaching Kids Programming - Count Pairs Whose Sum is Less than Target (Two Pointer Algorithm)
- Teaching Kids Programming - Sum of Two Numbers Less Than Target using Two Pointer Algorithm
- Teaching Kids Programming - Two Pointer Algorithm to Solve Four Sum Problem
- Teaching Kids Programming - Recursive Algorithm to Find the Sum of Two Numbers in BSTs
- Two Pointer Algorithm to Count the Sum of Three Numbers Less than Target
- Recursive and Two Pointer Algorithms to Determine Four Sum
- Algorithms to Check Sum of Two Numbers in Binary Search Trees
- Teaching Kids Programming - 3 Different Approaches to Solve Two-Sum Problem
- How to Design a Two-Sum Data Structure?
- How to Find the Closest Sum of Three in an Array using Two Pointer Algorithm? (3Sum Closest)
- Teaching Kids Programming - Three Sum Algorithm
- Teaching Kids Programming – Two Sum Algorithm when Input Array is Sorted
- Teaching Kids Programming – Two Sum Algorithm
- Two Pointer Algorithm to Find Maximum Two Sum Less Than K
- The Two Sum Algorithm using HashMap in C++/Java
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
301 wordsloading...
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