Intro
As someone preparing for interviews daily, I thought a cheat sheet focused on common patterns I might be asked about would be beneficial. Here, you’ll find the most common patterns, along with explanations, code templates I use to solve these questions, and an example question that I found both interesting and helpful in understanding each pattern better. I use Python for my interviews, so if you do too—or want to start using it—I recommend checking out my Python for Interviews Cheatsheet.
Arrays & Hashing
Prefix Sum
Idea
Prefix Sum is a technique used to store cumulative sums of a sequence of numbers, allowing for efficient range sum calculations. By precomputing the sum of elements up to each index, you can quickly calculate the sum of any subarray.
Template
Example Question: 238. Product of Array Except Self
Given an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Explanation: For each index, the product of all elements except the current one results in the array [24,12,8,6].
Solution:
Two Pointers
Idea
The Two Pointers technique uses two pointers to traverse a data structure, typically one starting from the beginning and the other from the end.
Template
Example Question: 15. 3Sum
Given an integer array nums
, return all the unique triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Example:
Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Explanation: The unique triplets that sum to zero are [-1, -1, 2] and [-1, 0, 1].
Solution:
Sliding Window
Idea
The Sliding Window technique is used to traverse subsets of a data structure, often an array or string, by maintaining a “window” of elements and sliding it across the structure. This approach is effective for finding subarrays or substrings that meet a specific condition.
Template (fixed length window)
Template (dynamic length window)
Example Question: 424. Longest Repeating Character Replacement
Given a string s
and an integer k
, you can choose any character in the string and change it to any other uppercase character at most k
times. Return the length of the longest substring containing the same letter you can get after performing the above operations.
Example:
Input: s = “AABABBA”, k = 1
Output: 4
Explanation: Replace the one ‘B’ in “AABABB” to get “AAAA” with a length of 4.
Solution:
Intervals
Idea
Interval problems involve processing a set of intervals, typically with operations like merging, finding overlaps, or checking if intervals are covered. Sorting intervals and using a greedy approach or maintaining a count of overlapping intervals is common in these problems.
Example Question: 56. Merge Intervals
Given an array of intervals where intervals[i] = [start, end]
, merge all overlapping intervals, and return an array of the non-overlapping intervals.
Example:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Solution:
Hashmaps
Idea
Hashmaps, or dictionaries, are collections that map keys to values, allowing for efficient O(1) average-time complexity for lookups, insertions, and deletions. They are especially useful for problems that require fast access to values associated with unique keys.
Example Question: 49. Group Anagrams
Given an array of strings strs
, group the anagrams together.
Example:
Input: strs = [“eat”,“tea”,“tan”,“ate”,“nat”,“bat”]
Output: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
Solution:
Sets
Idea
Sets are unordered collections of unique elements, providing efficient O(1) average-time complexity for element lookups, insertions, and deletions. For problems involving unique elements or distinct sequences, sets can simplify solutions.
Example Question: 128. Longest Consecutive Sequence
Given an unsorted array of integers nums
, find the length of the longest consecutive elements sequence.
Example:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is[1, 2, 3, 4]
.
Solution:
Stack
Idea
A stack is a data structure that follows the Last In, First Out (LIFO) principle. It’s useful for scenarios that involve reversing elements, tracking function calls, or balancing symbols (e.g., parentheses). Common operations include pushing elements onto the stack, popping elements off, and checking the top element.
Example Question: 739. Daily Temperatures
Given a list of daily temperatures temperatures
, return a list such that, for each day in the input, it tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0
instead.
Example:
Input: temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]
Explanation: For each day, you wait until a warmer temperature appears.
Solution:
Binary Search
Idea
Binary Search is an efficient algorithm for finding a target value in a sorted array by repeatedly dividing the search interval in half. It eliminates half of the remaining elements each step, making it ideal for large datasets. This technique requires the data to be sorted beforehand.
Template
Example Question: 74. Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n
matrix. Integers in each row are sorted from left to right, and the first integer of each row is greater than the last integer of the previous row.
Example:
Input: matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 3
Output: true
Solution:
This solution uses binary search by treating the 2D matrix as a 1D array, enabling efficient searching in O(log(m * n)) time.
Example Question: 153. Find Minimum in Rotated Sorted Array
Given a rotated sorted array nums
of unique elements, find the minimum element.
Example:
Input: nums = [3,4,5,1,2]
Output: 1
Solution:
Linked List
Idea
A linked list is a data structure made up of nodes, where each node contains a value and a reference (or pointer) to the next node. Linked lists are ideal for dynamic data structures where elements are frequently inserted or deleted, as they allow for efficient O(1) insertion and deletion.
Template
Example Question: 206. Reverse Linked List
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Solution:
Tree
A tree is a hierarchical data structure made up of nodes, where each node has a value and references to its child nodes. Traversal methods (in-order, pre-order, post-order) are used to visit nodes in a specific order.
Binary Tree
Idea
A binary tree has nodes with up to two children: left and right. Common types include full (0 or 2 children per node), complete (all levels filled except possibly the last), perfect (all interior nodes have two children and all leaves have the same depth)
Template
Example Question: 101. Symmetric Tree
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example:
Input: root = [1,2,2,3,4,4,3]
Output: true
Solution:
Example Question: 112. Path Sum
Given the root
of a binary tree and an integer targetSum
, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum
.
Example:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Solution:
Example Question: 102. Binary Tree Level Order Traversal
Given the root
of a binary tree, return the level order traversal of its nodes’ values (i.e., from left to right, level by level).
Example:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Solution:
Binary Search Tree
Idea
A Binary Search Tree (BST) is a tree where each node has at most two children. For each node, the left subtree contains only nodes with values less than the node’s value, and the right subtree contains only nodes with values greater than the node’s value. In-order traversal gives the values sorted in BST.
Template
Example Question: 235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes p
and q
.
Example:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The lowest common ancestor of nodes 2 and 8 is 6.
Solution:
Example Question: 230. Kth Smallest Element in a BST
Given the root of a binary search tree and an integer k
, return the k
th smallest element in the BST.
Example:
Input: root = [3,1,4,null,2], k = 1
Output: 1
Solution:
Heap / Priority Queue
Idea
A heap is a specialized binary tree that satisfies the heap property, where the parent node is either greater than (max-heap) or less than (min-heap) its children. Heaps are often used to implement priority queues, where elements are removed based on their priority. Heaps are efficient for operations that need the maximum or minimum element frequently.
Template
Example Question: 215. Kth Largest Element in an Array
Given an integer array nums
and an integer k
, return the k
th largest element in the array.
Example:
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Solution:
Backtracking
Idea
Backtracking builds solutions step-by-step, exploring each option. If a choice doesn’t work, it “backtracks” by undoing it and trying the next option. This approach is ideal for exploring combinations, permutations, and puzzle solutions.
Template
Example Question: 22. Generate Parentheses
Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: [”((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
Example 2:
Input: n = 1
Output: [”()”]
Solution:
Graph and Dynamic Programming
I wanted to review Graphs and Dynamic Programming more comprehensively since they are combinations of many topics we’ve discussed. So you can check them out from their posts.