Algorithm Patterns

Master common problem-solving patterns to tackle a wide variety of algorithm challenges

Two Pointers Pattern

Medium

The Two Pointers pattern uses two pointers to iterate through a data structure. The pointers can move toward each other, in the same direction at different speeds, or other variations.

This pattern is particularly useful for solving problems with sorted arrays or linked lists, where we're looking for pairs or subarrays that satisfy certain conditions.

1
2
3
4
5
6
7
i
j

Common Problems

  • Two Sum (sorted array)
  • Container With Most Water
  • 3Sum
  • Remove Duplicates
  • Trapping Rain Water
Learn More

Sliding Window Pattern

Medium

The Sliding Window pattern involves creating a window that can either be a fixed length or a dynamic size. The window moves from one end to another to process subarrays of a specific size or property.

This technique is highly efficient for solving problems that require finding subarrays that satisfy certain constraints, as it reduces the time complexity from O(n²) to O(n).

3
1
2
5
8
4
7

Common Problems

  • Maximum Sum Subarray of Size K
  • Longest Substring with K Distinct Characters
  • Fruits into Baskets
  • Longest Substring Without Repeating Characters
  • Minimum Window Substring
Learn More

Fast and Slow Pointers Pattern

Medium

The Fast and Slow Pointers pattern uses two pointers that move at different speeds. This approach is particularly useful for detecting cycles in linked lists or arrays.

It's also known as the "Tortoise and Hare" algorithm, with one pointer moving faster than the other, eventually meeting if there's a cycle.

1
2
3
4
5
6
3
slow
fast

Common Problems

  • Linked List Cycle
  • Middle of the Linked List
  • Happy Number
  • Palindrome Linked List
  • Cycle in a Circular Array
Learn More

Merge Intervals Pattern

Medium

The Merge Intervals pattern deals with overlapping intervals. This pattern is useful for problems that involve intervals with start and end times or ranges.

The approach typically involves sorting the intervals by their start time and then merging overlapping intervals.

[1,3]
[2,6]
[8,10]
[1,6]

Common Problems

  • Merge Intervals
  • Insert Interval
  • Interval List Intersections
  • Maximum CPU Load
  • Employee Free Time
Learn More

Cyclic Sort Pattern

Easy

The Cyclic Sort pattern deals with problems involving arrays containing numbers in a given range. The technique iterates through the array and places each number in its correct position.

This pattern is incredibly efficient for solving problems where the array contains numbers from 1 to n or a similar range, with a time complexity of O(n) and O(1) space.

3
1
5
4
2
1
2
3
4
5

Common Problems

  • Find Missing Number
  • Find all Missing Numbers
  • Find the Duplicate Number
  • Find all Duplicates
  • First Missing Positive
Learn More