# Length computation
let mut node_ptr : &ListNode = head.as_ref().unwrap();
while let Some(ref next) = node_ptr.next {
node_ptr = next;
l+=1;
}
- 206 Reverse Linked List
- 21 Merge Two Sorted Lists
- By list heads
- 19 Remove Nth Node From End of List
- 92. Reverse Linked List II
- By mutable references
- 94. Binary Tree Inorder Traversal
- Preorder and In-order Traversal with Stack
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 108. Convert Sorted Array to Binary Search Tree
- 726. Number of Atoms During iteration, think when to update parameters, when to process these parameters and re-reinitialize them, and when to invoke recursively. Note to match parentheses when subtracting subparts for the recursive call.
Extremely powerful for leftmost/rightmost smaller/greater problems in an array.
- 84. Largest Rectangle in Histogram
- 907. Sum of Subarray Minimums Employ to compute a min lexicographically ordered string or numbers with fixed digits, with certain actions satisfied.
- 316. Remove Duplicate Letters
- 321. Create Maximum Number
Hint: provide a level parameter in each recursive call. Prefix let level_padding : String = (0..level).map(|_|{" "}).collect();
in each print message for a clear format.
A general backtrack template is provided in the template. This can help the following problems:
A general permutation template is provided in the template. This can help the following problems:
- 31. Next Permutation (Find the last increasing adjacent pair, the first of which is indexed with k. If k not exists, reverse the entire array. Otherwise, find the greatest l such that arr[l]>arr[k]. Swap l and k, and reverse arr[k+1..])
Can use DP only if the states are enumerable, e.g, the target sum is integer. Otherwise, must apply the recursion.
Elements can NOT be reused.
Elements can be reused.
// result[i][j] represent the result to reach state j only with the first i elements. i=0 implies no elements considered.
Init result[element_count+1][state_count]
for i = 1..=element_count:
for j = 0..=state_count:
// Bounded
this_element = element[i-1]
if j < this_element {
Derive result[i][j] from result[i-1][j]
} else if bounded {
Derive result[i][j] from result[i-1][j-this_element]
} else {
Derive result[i][j] from result[i][j-this_element]
}
result[element_count][state_count]
- 72. Edit Distance
- 718. Maximum Length of Repeated Subarray
- 1092. Shortest Common Supersequence
- 1143. Longest Common Subsequence
- Others
Refer to the template for the classic binary search problem, such as first greater element, and etc.
// Assume the target must exist
low = 0i32; // inclusive and can be negative
high = nums.len() as i32 - 1;// inclusive and can be negative
while low < high {
let mid = (low + high) / 2;
// three branches can be merged.
if nums[mid]==target{
// may additional test whether it is the first and the last to be true
// If meeting condition: return
// else shrink the range:
high = mid or mid-1
low = mid + 1; NEVER low = mid, otherwise the loop is infinite.
} else if nums[mid] < target {
// similar as above
} else {
// similar as above
}
}
low
// Assume the target may not exist
low = 0i32; // inclusive and can be negative
high = nums.len() as i32 - 1;// inclusive and can be negative
while low <= high {
let mid = (low + high) / 2;
// three branches can be merged.
if nums[mid]==target{
// may additional test whether it is the first and the last to be true
// If meeting condition: return
// else shrink the range:
high = mid - 1; or
low = mid + 1; NEVER high/low = mid, otherwise the loop is infinite.
} else if nums[mid] < target {
// similar as above
} else {
// similar as above
}
}
// A general approach
let left = 0;
let right = nums.len() - 1;
while low <= high {
// check mid_num
if left_num < mid_num {
// adjust the ranges given that [left, mid] is sorted.
// Assume [left, mid] is not sorted, then suppose nums[left=0]=0 nums[left+1=-1] a[mid=2]=1, this array can never be rotated to be sorted.
} else if left_num > mid_num {
// adjust the ranges given that [mid, right] is sorted.
} else {
// increment left given that left_num = mid_num
}
}
-1
- 33. Search in Rotated Sorted Array
- 153. Find Minimum in Rotated Sorted Array
- 81. Search in Rotated Sorted Array II
- 154. Find Minimum in Rotated Sorted Array II
Suitable for problems where solutions are within in a range and the tentative solution is easy to verify.
- 275. H-Index II (Find the smallest i such that citations[i] >= n-i, return n-i)
# Handy code to produce a mapped index, like [0,2,4,1,3,5] or [0,2,4,1,3]
(0..(n+1)/2).map(|x|{2*x}).collect(); // [0,2,4] when n=5 or 6.
(0..n/2).map(|x|{2*x}).collect(); // [1,3] when n=5, or [1,3,5] when n=6.
In [1,3,0,2,4] or [1,3,5,0,2,4], every consecutive 3 are not adjacent.
- 190. Reverse Bits (Repeatedly test and set)
- 191. Number of 1 Bits (Use x&=x-1 to repeatively unset the least significant 1-bit. )
- 693. Binary Number with Alternating Bits (Use x&(x+1)==0 to check whether x=(2^n-1))
- 137. Single Number II (Find the single unique elements that appear k times, while the rest with n times. )
- Implement a cyclic counter with period n for each bit when xoring elements
- Return i-th bit counter if the i-th bit is set in binary k.
- 260. Single Number III (Find the two unique elements, (x,y) that appear k (k is odd) times, while the rest with n times. )
- Implement a cyclic counter with period n for each bit when xoring elements
- Locate any i-th bit counter, which is none-zero.(x,y differs in i-th bit).
- Separate all elements into two groups by i-th bit and redo p137 to discovery x and y.
- 29. Divide Two Integers
- 371. Sum of Two Integers
- 201. Bitwise AND of Numbers Range
NOTE: DP recursion for palindrome
is_palindrome(i,j) |= is_palindrome(k,j-1) && s[k-1] == s[j] for any k
Key recursion:
// no_stock_balances[i][k] represents the max balance at the end of i-th day with at most k txns, conditioned on no stock hold
// with_stock_balances[i][k] represents the max balance at the end of i-th day with at most k txns, conditioned on stocks holded
no_stock_balances[i<=0][*]=0; // initial condition
no_stock_balances[*][k=0]=0; // initial condition
with_stock_balances[*][k=0]=MIN; // imply N.A. to work with the below max operation
// sell
no_stock_balances[i][k] = max(no_stock_balances[i-1][k], with_stock_balances[i-1][k] + prices[i])
// buy
with_stock_balances[i][k] = max(with_stock_balances[i-1][k], no_stock_balances[i-1][k-1] - prices[i])
- 121. Best Time to Buy and Sell Stock (k=1)
- Enumerate k dimension with named variables.
- Always replace no_stock_balances[i-1][k-1] with 0 as k=1
- 122. Best Time to Buy and Sell Stock II (k=inf)
- Due inf, no_stock_balances[*][k]=no_stock_balances[*][k-1], and similar to with_stock_balances. Hence, the dimension for k can be removed.
- 188. Best Time to Buy and Sell Stock IV (Arbitrary k)
- Minor Optimization: since a txn must span at least two days, one day to buy and one day to sell, when k >n/2, it is equivalent to k = inf.
- 714. Best Time to Buy and Sell Stock with Transaction Fee
- Similar to P122.
- Can pay the fee either during the buy or the sell.
- 309. Best Time to Buy and Sell Stock with Cooldown (cool down with inf k)
- with_stock_balances[i][k] = max(with_stock_balances[i-1][k], no_stock_balances[i-2][k-1] - prices[i])
- 229. Majority Element II
- (B-M Majority Vote)
- 238. Product of Array Except Self
- 240. Search a 2D Matrix II
- 241. Different Ways to Add Parentheses
- 264. Ugly Number II
- DP
- 279. Perfect Squares
- Knapsack DP
- 307. Range Sum Query - Mutable
- Binary Index Tree, detailed here
- Range sum query
- Binary Index Tree, detailed here
- 310. Minimum Height Trees
- BFS from leaves
- 334. Increasing Triplet Subsequence
- Smart math tricks.
- 341. Flatten Nested List Iterator
- Pre-order Traversal with Stack.
- 365. Water and Jug Problem
- Bézout's identity: if d is a multiple of gcd(x,y), then d can be represented by ax+by (a,b,x,y are integers.)
- 368. Largest Divisible Subset
- 2D DP on Array
- 372. Super Pow
- Rely on Eulers' Theorem to form a recursion.
- 376. Wiggle Subsequence
- 1D DP, greedy.
- 382. Linked List Random Node
- Reservoir Sampling
- Select k elements from an unbounded stream with uniform probability.
- Reservoir Sampling
- 384. Shuffle an Array
- FY Algorithm for random shuffling.
- 390. Elimination Game
- Focus on invariant head element.
- 395. Longest Substring with At Least K Repeating Characters
- Divide and Conquer (Not 2 Pointer). For each recursion, identify a char which can never be included in the substring, due to the insufficient frequency. Use this char as split points and continue on the substring.
- 4. Median of Two Sorted Arrays
- Off-one error
- 10. Regular Expression Matching
- 2D DP
- 23. Merge k Sorted Lists
- Divide and Conquer
- 25. Reverse Nodes in k-Group
- Recursion
- 30. Substring with Concatenation of All Words
- Iterative String comparison
- 37. Sudoku Solver
- Recursion
- 41. First Missing Positive
- Bitset to mark for int presence.
- 42. Trapping Rain Water
- Math Modeling
- 44 Wildcard Matching
- 2D DP
- 51. N-Queens
- 52. N-Queens II
- Recursion
- 60. Permutation Sequence
- Off-one error
- 65. Valid Number
- Engineeringly Complex
- 68. Text Justification
- Engineeringly Complex
- 72. Edit Distance
- 2D DP
- 76. Minimum Window Substring
- 2-Pointer Approach
- 84. Largest Rectangle in Histogram
- Monotonic Stack.
- 85. Maximal Rectangle
- Similar to 84. Largest Rectangle in Histogram, solved with monotonic stack.
- 87. Scramble String
- Bottom-up approach with the increment on the substring length
- Top-down with memoization
- 115. Distinct Subsequences
- 2D DP.
- 123. Best Time to Buy and Sell Stock III
- As above
- 124. Binary Tree Maximum Path Sum
- Bottom-up Recursion.
- 127. Word Ladder II
- TODO: timeout
- 127. Word Ladder
- BFS
- 132. Palindrome Partitioning II
- 2D DP on 1D array (0 <=i<j<len)
- 135. Candy
- Smart tricks
- 140. Word Break II
- Recursion
- 149. Max Points on a Line
- Smart tricks: for each point Pi, count other points which share the identical slope with respect to Pi.
- 154 Find Minimum in Rotated Sorted Array II
- As above.
- 164. Maximum Gap
- Bucket Sort
- 174. Dungeon Game
- Bottom-up 2D DP, similar to 62. Unique Paths
- 188. Best Time to Buy and Sell Stock IV
- As above
- 212. Word Search II
- Build and employ the trie during DFS traversal.
- 214. Shortest Palindrome
- Find the longest palindrome from the first char.
- 218. The Skyline Problem
- Collect critical points, which the top-left and top-right point of each rectangle.
- Sort the critical points based on point x-coordinate, left or right, and height. (Details commented in code. )
- Iterate the critical points:
- If top-left:
- Add the corresponding rectangle to active ones
- If it increases the max height of the active rectangle: update result
- IF top-right:
- Remove the corresponding rectangle in active ons
- If it reduces the max height, update the result (Active rectangles can be maintained as a max-heap. )
- If top-left:
- 224. Basic Calculator
- State machine with Recursion.
- 233. Number of Digit One
- Smart Tricks to count Digit One in each digit position.
- 239. Sliding Window Maximum
- Max-heap
- 273. Integer to English Words
- Engineeringly Complex
- 282. Expression Add Operators
- Leverage stacks to compute the expression with operation precedence, e.g, multiplication is over addition.
- Concatenation (no-op) treated as the top-prior.
- 295. Find Median from Data Stream
- Min-max heap.
- 297. Serialize and Deserialize Binary Tree
- Preorder Traversal with the null marker
- 301. Remove Invalid Parentheses
- Recursion with duplicates.
- For each collected results after one round of recursion, do another round of recursion.
- 312. Burst Balloons
- Top-down DP with tricks: start recursion from the last bursted balloon, so that the left and right balloon are known.
- Similar to 87. Scramble String
- 315. Count of Smaller Numbers After Self
- During the merge sort, count the surpassed right numbers for each left one.
- 321. Create Maximum Number
- Two tricky sub-problems:
- Given an array of digits, return k of them in order, to form the greatest number. Use stacks.
- Given two array of digits, merge them while keeping their relative order, to form the greatest number.
- Two tricky sub-problems:
- 327. Count of Range Sum
- Prepare a vector of prefix sum S
- For each i, count j > i s.t S[j]-S[i] within the range
- Leverage the MergeSort, similar to 315. Count of Smaller Numbers After Self.
- [329. Longest Increasing Path in a Matrix](src/problem/p0329_longest_increasing_path_in_a_matrix.rs
- 2D DP with Memoization.
- 330. Patching Array
- Smart Tricks by Recursion: Assume the previous i number can attain [0,next_miss]),
- If num[i] <= next_miss:the range can be augment to [0, next_miss+num[i]) by considering num[i].
- Else:pad the array with next_muss to augment into [0, next_miss*2)
- Smart Tricks by Recursion: Assume the previous i number can attain [0,next_miss]),
- 335. Self Crossing
- Assume edge i to be first crossed, enumerate three canonical scenarios, in which the edge is crossed by i+4,i+5,and i+6.
- Relate the scenario with the edge length conditions.
- 336. Palindrome Pairs
- Build a trie for the reversed strings
- 352. Data Stream as Disjoint Intervals
- Ordered BTree Map
- 354. Russian Doll Envelopes
- Longest Increasing Subsequence
- 363. Max Sum of Rectangle No Larger Than K
- Two related subproblems:
- Max Sum Submatrix (KaDane's Algorithm)
- Subarray with the sum no larger than k (Compute during the Merge Sort, similar to 327. Count of Range Sum)
- Two related subproblems:
- 381. Insert Delete GetRandom O(1)
- Trick: a helper
positions : HashMap<i32, HashSet<usize>>
to track the index positions of each value in the array. It facilitates the removal of value in the middle of the array: fill the removed position with the last value in the array and updatepositions
accordingly.
- Trick: a helper
- 391. Perfect Rectangle
- Classify each point to a subset of four categories, top-left, top-right, bottom-left and bottom-right. A point can belong to multiple distinct types, but not duplicated types.
- Iterate each point for the above classification, validation and identify points in th corner.
- Again iterate each point and validate: if on corner, conforms to corner pattern. If interior, conform to T-pattern or X-pattern.
- Trick: 4 digits to encode the point type and identify pattern.
- 403. Frog Jump
- Incremental approach
- 407. Trapping Rain Water II
- The trapped water volume of a unit is determined by the lowest among all the highest units in each path towards the boundary.
- Leverage a priority queue.
- 410. Split Array Largest Sum
- Binary Search with the countable result candidate and easy verification.
- 420. Strong Password Checker
- Mathematically tricky.
- 432. All O`one Data Structure
- Leverage two data structures:
frq_arrays
, which maps the frequency to the list of elements with the associated frequency.key2frq_array_pos
, which maps the element key to the frequency and the array position.
- Leverage two data structures:
- 440. K-th Smallest in Lexicographical Order
- Leverage a denary tree, as detailed in here
- Tricks to calculate the number of children nodes within a parent node, without expanding.
- 446. Arithmetic Slices II - Subsequence
- 2D DP, with a data structure counts[i][d]. It counts the arithmetic subsequence ending at nums[i] with difference d with length at least 2.
- 458. Poor Pigs
- Smart tricks explained here
- 460. LFU Cache
frq_lists
, which maps the frequency to the list of elements with the associated frequency.key2frq_node
, which maps the element key to the frequency and the list node
- 466. Count The Repetitions
- Two-pointer approach to check one string is a subsequence of the other
- Make the process cyclic to accommodate for repetition.
- 472. Concatenated Words
- 2D DP to test a word is concatenated by others in a dictionary.
- 479. Largest Palindrome Product
- Too mathematically hard to attempt
- 480. Sliding Window Median
- Small and big heap/BtreeMap.
- 483. Smallest Good Base
- Mathematical Tricks explained here
- 488. Zuma Game
- Backtrack for each combination of possible insertion position and chars.
- Cached to deduplicate.
- 493. Reverse Pairs
- Count during the merge sort
- 502. IPO
- Pick the capital-allowed with the highest profit
- Leverage min-max heap.
- 514. Freedom Trail
- 2D DP
- 517. Super Washing Machines
- Mathematical Tricks
- 546. Remove Boxes
- 3D DP (Smart Recursion Formulation!)
- 552. Student Attendance Record II
- 3D DP (Smart and Generic Recursion Formulation!)
- 1st dimension on n:# of days
- 2nd dimension on the # of current absent days.
- 3nd dimension on the # of trailing leave days
- Given the limited cardinality, the last two dimensions can be unrolled as named variables.
- 3D DP (Smart and Generic Recursion Formulation!)
- Data structure:
- BtreeMap
- BtreeSet
- HashMap
- HashSet
- Vector
- Iterator
- Heap
- Stack
- Queue
- Bit Operation
- Primitives
- Option
- Typed/Untyped structs
- User Input
- Algorithms
- Binary Search
- Union Find (Map-based & vector-based)
Promient Problems 713 Element count in window sliding. 399 str Union Find
Unsolved: 803. Bricks Falling When Hit 126. Word Ladder II
- LRU(146) and LFU(460) has to be implemented in PYTHON, as only possible to encode in unsafe rust.