Two Sum Resource - aloalgo

Two Sum Pattern

Two Sum is the quintessential hash map problem. Given an array and a target, find two elements that sum to the target. The pattern extends to many variations.

Classic Two Sum

Variations

Two Sum II - Sorted Array

When array is sorted, use two pointers instead of hash map for O(1) space.

Two Sum - Count Pairs

Two Sum - Data Structure Design

Three Sum

Four Sum

K Sum (General)

Key Insights

  • Unsorted array: Use hash map for O(n) time
  • Sorted array: Use two pointers for O(1) space
  • Finding indices: Store index in hash map
  • Counting pairs: Store count in hash map
  • K-sum (k≥3): Reduce to Two Sum with sorting + recursion
  • Avoid duplicates: Sort first, skip equal consecutive elements
Was this helpful?
© 2026 aloalgo. All rights reserved.