leetcode algorithms

0.0(0)
Studied by 0 people
call kaiCall Kai
Locked
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/19

flashcard set

Earn XP

Description and Tags

description, when to use, time complexity, template, visual aid - https://blog.algomaster.io/p/20-dsa-patterns

Last updated 2:05 AM on 7/7/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai
Chat

No analytics yet

Send a link to your students to track their progress

20 Terms

1
New cards

prefix sum

  • preprocessing an array to create a new array where each element at index i represents the sum of all elements from the start up to i

  • time complexity: allows for O(1) sum queries on any subarray

  • when to use

    • multiple sum queries on subarrays

    • finding subarrays with a target sum

    • calculating cumulative totals

<ul><li><p>preprocessing an array to create a new array where each element at index i represents the sum of all elements from the start up to i</p></li><li><p>time complexity: allows for <strong>O(1)</strong> sum queries on any subarray</p></li><li><p>when to use</p><ul><li><p>multiple sum queries on subarrays</p></li><li><p>finding subarrays with a target sum</p></li><li><p>calculating cumulative totals</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/61c6f42f-d05b-4c2a-90cb-13c4f1a0ddaa.png" data-width="100%" data-align="center"><p></p>
2
New cards

two pointers

  • two pointers to traverse an array or list, typically from opposite ends or both moving in the same direction.

  • time complexity: reduces from O(n²) to O(n) for many problems

  • when to use

    • finding pairs in sorted arrays

    • comparing elements from both ends

    • partitioning arrays

    • palindrome checkschecks

<ul><li><p>two pointers to traverse an array or list, typically from opposite ends or both moving in the same direction.</p></li><li><p>time complexity: reduces from O(n²) to O(n) for many problems</p></li><li><p>when to use</p><ul><li><p>finding pairs in sorted arrays</p></li><li><p>comparing elements from both ends</p></li><li><p>partitioning arrays</p></li><li><p>palindrome checkschecks</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/af4c2e24-2b8b-4c15-a2ac-511d73ad9e62.png" data-width="100%" data-align="center"><p></p>
3
New cards

sliding window

  • maintains a window of elements and slides it across the array to find subarrays/substrings that satisfy a given condition. avoids recalculating overlapping parts of consecutive windows

  • when to use

    • contiguous subarray/substring problems

    • max/min in window of size k

    • longest/shortest substring with certain properties

    • problems involving consecutive elements

<ul><li><p>maintains a window of elements and slides it across the array to find subarrays/substrings that satisfy a given condition. avoids recalculating overlapping parts of consecutive windows</p></li><li><p>when to use</p><ul><li><p>contiguous subarray/substring problems</p></li><li><p>max/min in window of size k</p></li><li><p>longest/shortest substring with certain properties</p></li><li><p>problems involving consecutive elements</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/940fd283-8f2f-46cb-a49b-d347e9eba289.png" data-width="100%" data-align="center"><p></p>
4
New cards

fast & slow pointers

  • two pointers moving at different speeds; when there is a cycle, the fast pointer will eventually meet the slow pointer

  • when to use

    • detecting cycles in linked lists or arrays

    • finding the middle of a linked list

    • finding the start of a cycle

<ul><li><p>two pointers moving at different speeds; when there is a cycle, the fast pointer will eventually meet the slow pointer</p></li><li><p>when to use</p><ul><li><p>detecting cycles in linked lists or arrays</p></li><li><p>finding the middle of a linked list</p></li><li><p>finding the start of a cycle</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/6a5fd9cf-f48d-44d3-b20c-ea41c61da0c9.png" data-width="100%" data-align="center"><p></p>
5
New cards

linkedlist in-place reversal

  • reverses parts of a linked list without using extra space. manipulates pointers to reverse the direction of links

  • when to use

    • reversing a linked list or a portion of it

    • reversing nodes in groups

    • checking for palindromes in linked list

<ul><li><p>reverses parts of a linked list without using extra space. manipulates pointers to reverse the direction of links</p></li><li><p>when to use</p><ul><li><p>reversing a linked list or a portion of it</p></li><li><p>reversing nodes in groups</p></li><li><p>checking for palindromes in linked list</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/9b7206fd-d55a-4b33-bb74-4e8a3eaee35f.png" data-width="100%" data-align="center"><p></p>
6
New cards

frequency counting

  • hashmaps or arrays to count occurrences of elements

  • time complexity: transforms O(n²) to O(n) by trading space for time

  • when to use

    • finding duplicates or unique elements

    • checking if two collections have the same elements

    • finding elements that appear k times

    • anagram problems

<ul><li><p>hashmaps or arrays to count occurrences of elements</p></li><li><p>time complexity: transforms O(n²) to O(n) by trading space for time</p></li><li><p>when to use</p><ul><li><p>finding duplicates or unique elements</p></li><li><p>checking if two collections have the same elements</p></li><li><p>finding elements that appear k times</p></li><li><p>anagram problems</p></li></ul></li></ul><p></p>
7
New cards

monotonic stack

  • maintains elements in either increasing or decreasing order. as you iterate, you pop elements that violate the order, which reveals relationships between elements

  • when to use

    • finding the next/previous greater/smaller element

    • problems involving spans or ranges

    • histogram problems

<ul><li><p>maintains elements in either increasing or decreasing order. as you iterate, you pop elements that violate the order, which reveals relationships between elements</p></li><li><p>when to use</p><ul><li><p>finding the next/previous greater/smaller element</p></li><li><p>problems involving spans or ranges</p></li><li><p>histogram problems</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/05ea4860-a530-4894-9d60-def67e0df955.png" data-width="100%" data-align="center"><p></p>
8
New cards

bit manipulation

  • uses binary operations (AND, OR, XOP, NOT, shifts) to solve problems efficiently

  • when to use

    • finding unique numbers (XOR)

    • checking power of 2

    • counting bits

    • generating subsets using bit masks

    • space optimization

<ul><li><p>uses binary operations (AND, OR, XOP, NOT, shifts) to solve problems efficiently</p></li><li><p>when to use</p><ul><li><p>finding unique numbers (XOR)</p></li><li><p>checking power of 2</p></li><li><p>counting bits</p></li><li><p>generating subsets using bit masks</p></li><li><p>space optimization</p></li></ul></li></ul><p></p>
9
New cards

top ‘K’ elements

  • finds k largest or smallest elements using heaps (PQ). a min-heap of size k keeps track of k largest elements, and a max-heap keeps k smallest

  • when to use

    • finding k largest/smallest elements

    • finding kth largest/smallest element

    • finding k most/least frequent elements

    • merging k sorted lists

<ul><li><p>finds k largest or smallest elements using heaps (PQ). a min-heap of size k keeps track of k largest elements, and a max-heap keeps k smallest</p></li><li><p>when to use</p><ul><li><p>finding k largest/smallest elements</p></li><li><p>finding kth largest/smallest element</p></li><li><p>finding k most/least frequent elements</p></li><li><p>merging k sorted lists</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/30e15c44-0c54-4424-95d4-32d6fafa8a41.png" data-width="100%" data-align="center"><p></p>
10
New cards

overlapping intervals

  • handles problems involving intervals that may overlap. key insight is that after sorting by start time, two intervals [a, b] and [c, d] overlap if b >= c

  • when to use

    • merging overlapping intervals

    • finding interval intersections

    • scheduling problems (meeting rooms)

    • inserting into sorted intervals

<ul><li><p>handles problems involving intervals that may overlap. key insight is that after sorting by start time, two intervals [a, b] and [c, d] overlap if b &gt;= c</p></li><li><p>when to use</p><ul><li><p>merging overlapping intervals</p></li><li><p>finding interval intersections</p></li><li><p>scheduling problems (meeting rooms)</p></li><li><p>inserting into sorted intervals</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/6205e93b-ea4f-4a13-b4cc-fd5da8271cf4.png" data-width="100%" data-align="center"><p></p>
11
New cards

modified binary search

  • adaps binary search to handle rotated arrays, finding boundaries, or searching for conditions rather than exact values

  • when to use

    • searching in rotated sorted arrays

    • finding first/last occurrence of element

    • finding minimum/maximum satisfying a condition

    • peak finding problems

<ul><li><p>adaps binary search to handle rotated arrays, finding boundaries, or searching for conditions rather than exact values</p></li><li><p>when to use</p><ul><li><p>searching in rotated sorted arrays</p></li><li><p>finding first/last occurrence of element</p></li><li><p>finding minimum/maximum satisfying a condition</p></li><li><p>peak finding problems</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/2dd9cf0e-1565-4394-9d5a-55dab2f47286.png" data-width="100%" data-align="center"><p></p>
12
New cards

binary tree traversal

  • visits all notes in a specific order. preorder (root-left-right), inorder (left-root-right) and postorder (left-right-root)

  • when to use

    • processing tree nodes in a specific order

    • building trees from traversals

    • bst operations (inorder gives sorted order)

    • tree serialization/deserialization)

<ul><li><p>visits all notes in a specific order. preorder (root-left-right), inorder (left-root-right) and postorder (left-right-root)</p></li><li><p>when to use</p><ul><li><p>processing tree nodes in a specific order</p></li><li><p>building trees from traversals</p></li><li><p>bst operations (inorder gives sorted order)</p></li><li><p>tree serialization/deserialization)</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/b5bf3fb6-aaba-4b01-bfbf-27ee678eac26.png" data-width="100%" data-align="center"><p></p>
13
New cards

depth-first search (DFS)

  • explores as deep as possible along each branch before backtracking. uses a stack (or recursion) to remember which nodes to visit next)

  • when to use

    • exploring all paths in a tree.graph

    • finding connected components

    • detecting cycles

    • topological sorting

    • path finding when all paths matter

<ul><li><p>explores as deep as possible along each branch before backtracking. uses a stack (or recursion) to remember which nodes to visit next)</p></li><li><p>when to use</p><ul><li><p>exploring all paths in a tree.graph</p></li><li><p>finding connected components</p></li><li><p>detecting cycles</p></li><li><p>topological sorting</p></li><li><p>path finding when all paths matter</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/9a71812b-7d49-467d-b20b-ab41e2aac7c6.png" data-width="100%" data-align="center"><p></p>
14
New cards

breadth-first search (BFS)

  • explores nodes level-by-level, visiting all neighbors before moving deeper. uses a queuue and guarantees the shortest path in unweighted graphs

  • when to use

    • finding shortest path (unweighted)

    • level-order traversal

    • finding all notes at distance k

    • speaking problems (rotting oranges, walls, and gates)

<ul><li><p>explores nodes level-by-level, visiting all neighbors before moving deeper. uses a queuue and guarantees the shortest path in unweighted graphs</p></li><li><p>when to use</p><ul><li><p>finding shortest path (unweighted)</p></li><li><p>level-order traversal</p></li><li><p>finding all notes at distance k</p></li><li><p>speaking problems (rotting oranges, walls, and gates)</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/be0ea69a-844f-44f0-810e-c10a31799102.png" data-width="100%" data-align="center"><p></p>
15
New cards

shortest path

  • minimam distance between nodes; dijstra’s for weighted graphs with non-negative weights, bellman-ford handles negative weights

  • when to use

    • finding minimum cost/distance paths

    • network routing problems

    • weighted graph traversal

    • problems with varying edge costs

<ul><li><p>minimam distance between nodes; dijstra’s for weighted graphs with non-negative weights, bellman-ford handles negative weights</p></li><li><p>when to use</p><ul><li><p>finding minimum cost/distance paths</p></li><li><p>network routing problems</p></li><li><p>weighted graph traversal</p></li><li><p>problems with varying edge costs</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/a0ef2585-a85b-4d8b-9392-e36496ed12c6.png" data-width="100%" data-align="center"><p></p>
16
New cards

matrix traversal

  • uses DFS or BFS to explore 2D grids. the key is handling 4-directional or 8-directional movement and boundary checks

  • when to use

    • grid based problems (island, regions)

    • flood fill algorithms

    • finding connected components in 2D

    • path finding in mazes

<ul><li><p>uses DFS or BFS to explore 2D grids. the key is handling 4-directional or 8-directional movement and boundary checks</p></li><li><p>when to use</p><ul><li><p>grid based problems (island, regions)</p></li><li><p>flood fill algorithms</p></li><li><p>finding connected components in 2D</p></li><li><p>path finding in mazes</p></li></ul></li></ul><p></p>
17
New cards

backtracking

  • explores all possible solutions by making choices and undoes (backtracks) when a path leads to an invalid solution

  • when to use

    • generating all permutations/combinations.subsets

    • solving constraint satisfaction problems (N-queens, Sudoku)

    • finding all paths meeting certain criteries

    • string partitioning problems

<ul><li><p>explores all possible solutions by making choices and undoes (backtracks) when a path leads to an invalid solution</p></li><li><p>when to use</p><ul><li><p>generating all permutations/combinations.subsets</p></li><li><p>solving constraint satisfaction problems (N-queens, Sudoku)</p></li><li><p>finding all paths meeting certain criteries</p></li><li><p>string partitioning problems</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/c4c8cf4d-6900-416f-b364-a578510ad354.png" data-width="100%" data-align="center"><p></p>
18
New cards

prefix search (trie)

  • stores strings character by character, allowing efficient prefix lookups. each node represents a character, and paths from root to nodes represent prefixes

  • when to use

    • autocomplete and search suggestions

    • spell checking

    • IP routing (longes prefix match)

<ul><li><p>stores strings character by character, allowing efficient prefix lookups. each node represents a character, and paths from root to nodes represent prefixes</p></li><li><p>when to use</p><ul><li><p>autocomplete and search suggestions</p></li><li><p>spell checking</p></li><li><p>IP routing (longes prefix match)</p></li></ul></li></ul><img src="https://assets.knowt.com/user-attachments/c4903776-9d7e-4ac3-84be-5b09195b87e3.png" data-width="100%" data-align="center"><p></p>
19
New cards

greedy

  • locally optimal choices at each step, hoping to find a global optimum. work when optimal choices lead to global optimal solutions

  • when to use

    • optimization problems with greedy choice propery

    • interval scheduling

    • huffman coding

    • activity selection

    • when proof by exchange argument works

<ul><li><p>locally optimal choices at each step, hoping to find a global optimum. work when optimal choices lead to global optimal solutions</p></li><li><p>when to use</p><ul><li><p>optimization problems with greedy choice propery</p></li><li><p>interval scheduling</p></li><li><p>huffman coding</p></li><li><p>activity selection</p></li><li><p>when proof by exchange argument works</p></li></ul></li></ul><p></p>
20
New cards

dynamic programing patterns

  • solves problems by breaking them into overlapping subproblems and stores results to avoid recomputation. works when problems have optimal substructure

  • when to use

    • problems with overlapping subproblems

    • optimization (min/max) problems

    • counting problems (number of ways)

    • decision problems (can we achieve X?)

  • common DP patterns

    • fibonacci

    • 0/1 knapsack

    • longest common subsequence

    • longest increasing subsequence