Dynamic Programming (Multi-dimension)
Minimum Path Sum public int minPathSum(int[][] grid) { int m = grid.length, n = grid[0].length; int[][] dp = new int[m][n]; dp[m - 1][n - 1] = grid[m - 1][n - 1]; for (int j = n ...
Minimum Path Sum public int minPathSum(int[][] grid) { int m = grid.length, n = grid[0].length; int[][] dp = new int[m][n]; dp[m - 1][n - 1] = grid[m - 1][n - 1]; for (int j = n ...
Best Time to Buy and Sell Stock IV int maxProfit(int k, vector<int>& prices) { int n = prices.size(); // We can make maximum number of transactions if (k >= n / 2) { ...
K-SUM 2 Sum Two Sum One pass, Set (Map): O(n) Two Sum II - Input array is sorted Two pointers: O(n) Two Sum Less Than K Binary Search Count the Number of Fair Pairs public long countFairPa...
Best Time to Buy and Sell Stock II int maxProfit(vector<int>& prices) { int profit = 0; for (int i = 1; i < prices.size(); i++) { // Buys a stock at a valley and sells...
Kadane’s algorithm Maximum subarray problem Maximum Subarray public int maxSubArray(int[] nums) { int max = nums[0], currSum = nums[0]; for (int i = 1; i < nums.length; i++) { ...
String public boolean matches(String regex) Validate IP Address public String validIPAddress(String IP) { if (IP.matches("^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?...
Elastic-size Window The constraint can be expressed as: [f(v) \ge 0] where \(v\) is called contraint variable. Constraint variable is determined by the position and size of the sliding window: ...
Merge K Sorted Lists public ListNode mergeKLists(ListNode[] lists) { int k = lists.length; if (k == 0) { return null; } int interval = 1; while (interval < k) { ...
A spanning tree T of an undirected graph G is a subgraph that is a tree which includes all of the vertices of G. A minimum spanning tree (MST) or minimum weight spanning tree is a spanning tree wh...
Fundamentals Level traversal. The most common data structure used is Queue. Two rolling Lists or Sets (de-dupe) can also be used, but less common. Smallest Greater Multiple Made of Two Digits Im...