Brief of Data-Structure & Algorithm coding interview questions
Some concepts, topics, and examples for Leetcode coding interview
Practice platforms
More of my implementations can be found here: Github: QuanHNguyen232/LeetCode
Prefix sum
Practice problems
- https://leetcode.com/problems/range-sum-query-2d-immutable
- https://leetcode.com/problems/widest-pair-of-indices-with-equal-range-sum/
- https://leetcode.com/problems/split-array-with-equal-sum/
- https://leetcode.com/problems/binary-subarrays-with-sum
- https://leetcode.com/problems/subarray-sums-divisible-by-k/
- https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/
- https://leetcode.com/problems/make-sum-divisible-by-p
Map/Set
Practice problems
- https://leetcode.com/problems/number-of-good-pairs/
- https://leetcode.com/problems/number-of-arithmetic-triplets/submissions/
- https://leetcode.com/problems/two-sum/
- https://leetcode.com/problems/decode-the-message/
- https://leetcode.com/problems/count-the-number-of-consistent-strings/
- https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/
- https://leetcode.com/problems/contains-duplicate-ii/
- https://leetcode.com/problems/check-if-the-sentence-is-pangram/
- https://leetcode.com/problems/count-largest-group/
- https://leetcode.com/problems/unique-email-addresses/
- https://leetcode.com/problems/destination-city/
- https://leetcode.com/problems/valid-sudoku/
- https://leetcode.com/problems/repeated-dna-sequences
- https://leetcode.com/problems/unique-morse-code-words/
- https://leetcode.com/problems/rank-teams-by-votes/
- https://leetcode.com/problems/find-all-anagrams-in-a-string
Big num
Practice problems
- https://leetcode.com/problems/plus-one/
- https://leetcode.com/problems/add-binary/
- https://leetcode.com/problems/add-strings/
- https://leetcode.com/problems/multiply-strings/
2D array
Practice problems
- https://leetcode.com/problems/transpose-matrix/
- https://leetcode.com/problems/rotate-image/
- https://leetcode.com/problems/diagonal-traverse/description/
- https://leetcode.com/problems/spiral-matrix/description/
- https://leetcode.com/problems/richest-customer-wealth/description/
- https://leetcode.com/problems/matrix-diagonal-sum
Sliding window
Patterns for Sliding Window
- ?
Notes:
- Sliding windows with 2 pointers works when the problem has monotonic properties - meaning that expanding the window consistently moves us in one direction regarding our constraint, and shrinking consistently moves us in the opposite direction.
- Key Criteria for Two Pointers/Sliding Window (Both should be True) (sliding window vs DP):
- Rule 1 (Validity of Wider Scope): If a larger window (wider scope) is valid, all smaller sub-windows within it must also be valid.
- Rule 2 (Invalidity of Narrower Scope): If a smaller window (narrower scope) is invalid, all larger windows containing it must also be invalid.
Sources:
- https://leetcode.com/discuss/post/6900561/ultimate-sliding-window-guide-patterns-a-28e9/
- https://adamowada.github.io/leetcode-study/sliding-window/study-guide.html
- https://github.com/0xjaydeep/leetcode-patterns/blob/main/patterns/sliding_window/README.md
Practice problems
- https://leetcode.com/problems/fruit-into-baskets
- https://leetcode.com/problems/max-consecutive-ones-iii/
- https://leetcode.com/problems/find-all-anagrams-in-a-string/
- https://leetcode.com/problems/permutation-in-string/description/
- https://leetcode.com/problems/minimum-window-substring/description/
- https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/
- https://leetcode.com/problems/maximum-average-subarray-i/
- https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/
- https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/
- https://leetcode.com/problems/number-of-substrings-containing-all-three-characters
- https://leetcode.com/problems/trapping-rain-water
- https://leetcode.com/problems/count-subarrays-with-fixed-bounds/
- https://leetcode.com/problems/subarrays-with-k-different-integers/
- https://leetcode.com/problems/minimum-size-subarray-sum/
- https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/
- https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/
- https://leetcode.com/problems/count-subarrays-with-score-less-than-k/
- https://leetcode.com/problems/find-the-longest-equal-subarray/
- https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/description/
Binary search
Reference:
- https://medium.com/swlh/binary-search-find-upper-and-lower-bound-3f07867d81fb
- https://leetcode.com/explore/learn/card/binary-search/136/template-analysis/935/
Templates
Choosing Mid, Left, Right
-
Assign L and R when asked for the lower bound. 1 2 3 4 5 6 7 8
def binary_search_lower(nums, target, expect): while left < right: mid = left + (right - left) // 2 # lower bound, since mid=l+(r-l)/2, we must avoid l = mid (infinite loop, e.g. arr=[0,1] with target=0) if condition(mid): # if mid works right = mid else: left = mid + 1 # otherwise causes infinite loop return left # find left most index (left == right)
-
Assign L and R when asked for the upper bound. 1 2 3 4 5 6 7 8
def binary_search_upper(nums, target, expect): while left < right: mid = right - (right - left) // 2 if condition(mid): # if mid works right = mid - 1 else: left = mid return left
Modified
Practice problems
N/A
Adhoc binary search
Practice problems
N/A
Matrix
Practice problems
N/A
Hard
Practice problems
N/A
Tree
Reference:
- https://leetcode.com/discuss/post/3743769/crack-easily-any-interview-tree-data-str-nxr9/
- https://cp-algorithms.com/
Traversal
Inorder Traversal
Practice problems
N/A
Preorder Traversal
Practice problems
N/A
Postorder Traversal
Practice problems
N/A
Level-order Traversal
Practice problems
N/A
Ancestor problems
Common ancestor (e.g: Lowest common ancestor)
Root to leaf path problems
Depth problem
Travel child to parent problems
Tree construction
Practice problems
N/A
Serialize and Deserialize tree
Practice problems
N/A
Distance between two Nodes
Practice problems
N/A
Binary Search Tree
Practice problems
N/A
Disjoint Set Union (DSU)/Union Find
https://cp-algorithms.com/data_structures/disjoint_set_union.html
Fenwick Tree
https://cp-algorithms.com/data_structures/fenwick.html
Segment Tree
https://cp-algorithms.com/data_structures/segment_tree.html
Trie
Reference:
- https://leetcode.com/problems/implement-trie-prefix-tree/
Implementation template:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class TrieNode:
def __init__(self):
self.children = {}
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
self.root.isEndOfWord = False
def insert(self, word: str) -> None:
current = self.root
for c in word:
if c not in current.children:
current.children[c] = TrieNode()
current = current.children[c]
current.isEndOfWord = True
def search(self, word: str) -> bool:
current = self.root
for c in word:
nextNode = current.children.get(c, None)
if not nextNode: return False
current = nextNode
return current.isEndOfWord
def startsWith(self, prefix: str) -> bool:
current = self.root
for c in prefix:
nextNode = current.children.get(c, None)
if not nextNode: return False
current = nextNode
return True
def lcs(self):
ans = []
current = self.root
while current:
if len(current.children) > 1 or current.isEndOfWord:
break
else:
key = list(current.children.keys())
ans.append(key[0])
current = current.children.get(key[0])
return ''.join(ans)
def canBeBuiltByOtherWords(self, word):
current = self.root
for c in word:
current = current.children[c]
if not current.isEndOfWord: return False
return True
Practice problems
N/A
Graph
References:
- https://leetcode.com/discuss/post/3900838/mastering-graph-algorithms-a-comprehensi-xyws/
- https://blog.algomaster.io/p/master-graph-algorithms-for-coding
BFS
DFS
Topological Sort
Practice problems
N/A
Union Find
Practice problems
N/A
Cycles
Cycle Detection
Practice problems
N/A
DFS for Undirected/Directed Graphs
Union-Find for Undirected Graphs
Eulerian path
Connected Components
Practice problems
N/A
Strongly Connected Components in Directed Graphs
Kosaraju’s
Tarjan’s
Bipartite Graphs
Practice problems
N/A
Flood Fill
Practice problems
N/A
Minimum Spanning Tree (MST)
Practice problems
N/A
Kruskal’s
Prim’s
Shortest Path
Practice problems
N/A
Dijkstra’s
Bellman-Ford
Floyd-Warshall
BFS
A*
Backtracking
Reference:
- https://leetcode.com/discuss/post/1405817/backtracking-algorithm-problems-to-pract-lujf/
Patterns for Backtracking:
- Permutation
- Combination
- Subset
-
Key idea:
- Order matters
- Each element can be used once per permutation
- Need a visited array (or swap)
procedure BACKTRACK(path) if length(path) = n then add path to result return end if for i ← 0 to n - 1 do if visited[i] then continue end if visited[i] ← true path.append(nums[i]) BACKTRACK(path) path.pop() visited[i] ← false end for -
Key idea:
- Order does NOT matter
- Use start index to prevent duplicates
- Each element used once
procedure BACKTRACK(start, path) if valid_solution then add path to result return end if for i ← start to n - 1 do path.append(nums[i]) BACKTRACK(i + 1, path) path.pop() end for -
Key idea:
- Every element has two choices: include/exclude
procedure BACKTRACK(start, path) add path to result for i ← start to n - 1 do path.append(nums[i]) BACKTRACK(i + 1, path) path.pop() end for
Bit manipulation
Some common functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Checking if a number is odd or even:
def is_odd(n):
return n & 1
def is_even(n):
return not n & 1
# Getting the i-th bit:
def get_bit(n, i):
return (n >> i) & 1
# Setting the i-th bit:
def set_bit(n, i):
return n | (1 << i)
# Clearing the i-th bit:
def clear_bit(n, i):
return n & ~(1 << i)
# Updating the i-th bit to a given value:
def update_bit(n, i, v):
mask = ~(1 << i)
return (n & mask) | (v << i)
# Counting the number of 1s in the binary representation (Hamming weight):
def hamming_weight(n):
count = 0
while n:
n &= (n - 1)
count += 1
return count
# Reversing the bits of a number:
def reverse_bits(n):
result = 0
for i in range(32): # Assuming 32-bit integer
result = (result << 1) | (n & 1)
n >>= 1
return result
# Finding the most significant bit position (zero-based index):
def most_significant_bit(n):
msb = -1
while n > 0:
n >>= 1
msb += 1
return msb
# Checking if a number is a power of 2:
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
# Swapping odd and even bits:
def swap_odd_even_bits(n):
even_bits = n & 0xAAAAAAAA
odd_bits = n & 0x55555555
even_bits >>= 1
odd_bits <<= 1
return even_bits | odd_bits
def clear_rightmost_bit(n):
''' a & (a-1) clear bit 1 tận cùng bên phải của a (last bit-1 of a)
a = xxxxxxxx10101
a-1 = xxxxxxxx10100
a & (a-1) = xxxxxxxx10100
a = xxxxxxxx10000
a-1 = xxxxxxxx01111
a & (a-1) = xxxxxxxx00000
'''
return n & (n-1)
Practice problems
N/A
Dynamic Programming
Sources:
- https://blog.algomaster.io/p/20-patterns-to-master-dynamic-programming
Notes:
- DP vs Sliding Window: Count the Number of Good Subarrays Leetcode 2537 and https://leetcode.com/problems/longest-non-decreasing-subarray-after-replacing-at-most-one-element/solutions/7337072/why-not-sliding-window-answer-here-by-ka-d6a8: focus on valid/invalid rules for Window
Fibonacci Sequence (or linear sequence, linear time)
Practice problems
- https://leetcode.com/problems/climbing-stairs/description/
- https://leetcode.com/problems/min-cost-climbing-stairs/description/
Kadane’s Algorithm
Practice problems
- https://leetcode.com/problems/maximum-subarray/description/
- https://leetcode.com/problems/maximum-sum-circular-subarray/description/
- https://leetcode.com/problems/maximum-product-subarray/description/
0/1 Knapsack
Practice problems
- https://leetcode.com/problems/partition-equal-subset-sum/description/
- https://leetcode.com/problems/target-sum/description/
- https://leetcode.com/problems/last-stone-weight-ii/description/
Unbounded Knapsack
Practice problems
- https://leetcode.com/problems/coin-change/description/
- https://leetcode.com/problems/coin-change-ii/description/
- https://leetcode.com/problems/perfect-squares/description/
Longest Common Subsequence (LCS)
Practice problems
- https://leetcode.com/problems/longest-common-subsequence/description/
- https://leetcode.com/problems/delete-operation-for-two-strings/description/
- https://leetcode.com/problems/shortest-common-supersequence/description/
Longest Increasing Subsequence (LIS)
Practice problems
- https://leetcode.com/problems/longest-increasing-subsequence/description/
- https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/
- https://leetcode.com/problems/russian-doll-envelopes/description/
Palindromic Subsequence
Practice problems
- https://leetcode.com/problems/longest-palindromic-subsequence/description/
- https://leetcode.com/problems/palindromic-substrings/description/
- https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/description/
Edit Distance
Practice problems
- https://leetcode.com/problems/edit-distance/description/
- https://leetcode.com/problems/delete-operation-for-two-strings/description/
- https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/
Subset Sum
Practice problems
- https://leetcode.com/problems/partition-equal-subset-sum/description/
- https://leetcode.com/problems/target-sum/description/
- https://leetcode.com/problems/partition-to-k-equal-sum-subsets/
String Partition
Practice problems
- https://leetcode.com/problems/word-break/description/
- https://leetcode.com/problems/palindrome-partitioning-ii/description/
- https://leetcode.com/problems/concatenated-words/description/
Catalan Numbers
Practice problems
- https://leetcode.com/problems/unique-binary-search-trees/description/
- https://leetcode.com/problems/generate-parentheses/description/
Matrix Chain Multiplication
Count Distinct Ways
Practice problems
N/A
DP on Grids
DP on Trees
DP on Graphs
Digit DP
Bitmasking DP
Probability DP
State Machine DP
Practice problems
- https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/
- https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/
Enjoy Reading This Article?
Here are some more articles you might like to read next: