├── 0-1 Knapsack ├── 1 Two Sum ├── 10 Regular Expression Matching ├── 100 Same Tree ├── 101 Symmetric Tree ├── 1024 Video Stitching ├── 1046 Last Stone Weight ├── 1047 Remove All Adjacent Duplicates In String ├── 1143 Longest Common Subsequence ├── 118 Pascal's Triangle ├── 119 Pascal's Triangle II ├── 1190 Reverse Substrings Between Each Pair of Parentheses ├── 1209 Remove All Adjacent Duplicates in String II ├── 121 Best Time to Buy and Sell Stock ├── 122 Best Time to Buy and Sell Stock II ├── 123 Best Time to Buy and Sell Stock III ├── 1249 Minimum Remove to Make Valid Parentheses ├── 125 Valid Palindrome ├── 1277 Count Square Submatrices with All Ones ├── 1306 Jump Game III ├── 131 Palindrome Partitioning ├── 1312 Minimum Insertion Steps to Make a String Palindrome ├── 1326 Minimum Number of Taps to Open to Water a Garden ├── 1345 Jump Game IV ├── 136 Single Number ├── 1461 Check If a String Contains All Binary Codes of Size K ├── 1486 XOR Operation in an Array ├── 15 3Sum ├── 1553 Minimum Number of Days to Eat N Oranges ├── 162 Find Peak Element ├── 164 Maximum Gap ├── 167 Two Sum II - Input array is sorted ├── 17 Letter Combinations of a Phone Number ├── 172 Factorial Trailing Zeroes ├── 188 Best Time to Buy and Sell Stock IV ├── 20 Valid Parentheses ├── 200 Number of Islands ├── 216 Combination Sum III ├── 22 Generate Parentheses ├── 231 Power of Two ├── 235 Lowest Common Ancestor of a Binary Search Tree ├── 252 Meeting Rooms ├── 253 Meeting Rooms II ├── 268 Missing Number ├── 287 Find the Duplicate Number ├── 3 Longest Substring Without Repeating Characters ├── 30 Substring with Concatenation of All Words ├── 31 Next Permutation ├── 319 Bulb Switcher ├── 32 Longest Valid Parentheses ├── 329 Longest Increasing Path in a Matrix ├── 336 Palindrome Pairs ├── 34 Find First and Last Position of Element in Sorted Array ├── 347 Top K Frequent Elements ├── 36 Valid Sudoku ├── 39 Combination Sum ├── 40 Combination Sum II ├── 416 Partition Equal Subset Sum ├── 417 Pacific Atlantic Water Flow ├── 42 Trapping Rain Water ├── 438 Find All Anagrams in a String ├── 44 Wildcard Matching ├── 45 Jump Game II ├── 451 Sort Characters By Frequency ├── 46 Permutations ├── 48 Rotate Image ├── 484 Find Permutation ├── 49 Group Anagrams ├── 516 Longest Palindromic Subsequence ├── 53 Maximum Subarray ├── 54 Spiral Matrix ├── 55 Jump Game ├── 56 Merge Intervals ├── 581 Shortest Unsorted Continuous Subarray ├── 59 Spiral Matrix II ├── 62 Unique Paths ├── 63 Unique Paths II ├── 639 Decode Ways II ├── 64 Minimum Path Sum ├── 654 Maximum Binary Tree ├── 680 Valid Palindrome II ├── 682 Baseball Game ├── 7 Reverse Integer ├── 74 Search a 2D Matrix ├── 76 Minimum Window Substring ├── 77 Combinations ├── 78 Subsets ├── 84 Largest Rectangle in Histogram ├── 85 Maximal Rectangle ├── 856 Score of Parentheses ├── 9 Palindrome Number ├── 90 Subsets II ├── 91 Decode Ways ├── 980 Unique Paths III ├── Best Time to Buy and Sell Stock (Part1+Part2+Part3+Part4) - DP Version ├── Increasing Path in Matrix ├── Largest area of rectangle with permutations ├── Maximum Size Square Sub-matrix ├── Maximum Sum Square SubMatrix ├── Min Steps in Infinite Grid ├── Subset Sum Problem! └── WoodCutting Made Easy! /0-1 Knapsack: -------------------------------------------------------------------------------- 1 | Problem Description 2 | 3 | Given two integer arrays A and B of size N each which represent values and weights associated with N items respectively. 4 | 5 | Also given an integer C which represents knapsack capacity. 6 | 7 | Find out the maximum value subset of A such that sum of the weights of this subset is smaller than or equal to C. 8 | 9 | NOTE: 10 | 11 | You cannot break an item, either pick the complete item, or don’t pick it (0-1 property). 12 | 13 | public int solve(int[] A, int[] B, int C) { 14 | int[][] dp = new int[B.length+1][C+1]; 15 | 16 | for(int i=1;ij){ 19 | dp[i][i] = dp[i-1][j]; 20 | }else{ 21 | dp[i][i] = Math.max(dp[i-1][j],A[i-1]+dp[i-1][j-B[i-1]]); 22 | } 23 | } 24 | } 25 | 26 | return dp[B.length][C]; 27 | 28 | } 29 | -------------------------------------------------------------------------------- /1 Two Sum: -------------------------------------------------------------------------------- 1 | 1. Two Sum 2 | 3 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 4 | 5 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 6 | 7 | You can return the answer in any order. 8 | 9 | //Optimal solution using HashMap 10 | 11 | public int[] twoSum(int[] nums, int target) { 12 | 13 | HashMap map = new HashMap(); 14 | 15 | //Fill HM 16 | for(int i=0;imax){ 32 | max = r; 33 | } 34 | } 35 | if(min==max) return -1; 36 | min = max; 37 | total++; 38 | } 39 | 40 | return total; 41 | } 42 | -------------------------------------------------------------------------------- /1046 Last Stone Weight: -------------------------------------------------------------------------------- 1 | We have a collection of stones, each stone has a positive integer weight. 2 | 3 | Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: 4 | 5 | If x == y, both stones are totally destroyed; 6 | If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. 7 | At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: [2,7,4,1,8,1] 14 | Output: 1 15 | Explanation: 16 | We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, 17 | we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, 18 | we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, 19 | we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. 20 | 21 | public int lastStoneWeight(int[] stones) { 22 | PriorityQueue maxHeap = new PriorityQueue(Collections.reverseOrder()); 23 | 24 | for(int i=0;i1){ 29 | 30 | int last = maxHeap.poll(); 31 | int last2 = maxHeap.poll(); 32 | if(last!=last2){ 33 | int newStone = last-last2; 34 | maxHeap.add(newStone); 35 | } 36 | } 37 | 38 | if(maxHeap.isEmpty())return 0; 39 | else return maxHeap.poll(); 40 | } 41 | -------------------------------------------------------------------------------- /1047 Remove All Adjacent Duplicates In String: -------------------------------------------------------------------------------- 1 | 1047. Remove All Adjacent Duplicates In String 2 | Easy 3 | 4 | 734 5 | 6 | 60 7 | 8 | Add to List 9 | 10 | Share 11 | Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. 12 | 13 | We repeatedly make duplicate removals on S until we no longer can. 14 | 15 | Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. 16 | 17 | 18 | 19 | Example 1: 20 | 21 | Input: "abbaca" 22 | Output: "ca" 23 | Explanation: 24 | For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". 25 | 26 | public String removeDuplicates(String S) { 27 | 28 | Stack stack = new Stack(); 29 | StringBuilder b = new StringBuilder(); 30 | for(int i=0;i> generate(int numRows) { 5 | 6 | if(numRows==0) return new ArrayList(); 7 | 8 | List> result = new ArrayList(); 9 | 10 | for(int i=1;i<=numRows;i++){ 11 | 12 | List row = new ArrayList(); 13 | for(int j=0;j getRow(int rowIndex) { 10 | 11 | Integer[] result = new Integer[rowIndex+1]; 12 | int prev = 0; 13 | 14 | 15 | for(int i=1;i<=rowIndex+1;i++){ 16 | 17 | for(int j=0;j stack = new Stack(); 24 | Deque d = new ArrayDeque(); 25 | for(int i=0;iprices[i-1]){ 19 | p = p+ prices[i]-prices[i-1]; 20 | } 21 | } 22 | return p; 23 | } 24 | -------------------------------------------------------------------------------- /123 Best Time to Buy and Sell Stock III: -------------------------------------------------------------------------------- 1 | Say you have an array for which the ith element is the price of a given stock on day i. 2 | 3 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 4 | 5 | Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 6 | 7 | Example 1: 8 | 9 | Input: [3,3,5,0,0,3,1,4] 10 | Output: 6 11 | Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. 12 | Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. 13 | 14 | public int maxProfit(int[] prices) { 15 | int b1 = Integer.MAX_VALUE; 16 | int b2 = Integer.MAX_VALUE; 17 | int p1 = 0 , p2 = 0; 18 | for(int i=0;i ct = new Stack(); 19 | Stack index = new Stack(); 20 | 21 | for(int i=0;i index 4 -> index 1 -> index 3 14 | index 5 -> index 6 -> index 4 -> index 1 -> index 3 15 | 16 | 17 | public boolean canReach(int[] arr, int start) { 18 | 19 | Stack s = new Stack(); 20 | int[] seen = new int[arr.length]; 21 | s.add(start); 22 | 23 | 24 | while(!s.isEmpty()){ 25 | 26 | int m = s.pop(); //5 27 | int l = m-arr[m]; //4 28 | int r = m+arr[m]; //6 29 | 30 | 31 | if(l>=0 && l=0 && r> partition(String s) { 17 | List> result = new ArrayList(); 18 | findAll(s,result,new ArrayList()); 19 | return result; 20 | } 21 | 22 | void findAll(String s,List> result,List temp){ 23 | 24 | if(s.length()==0){ 25 | result.add(new ArrayList(temp)); 26 | } 27 | for(int i=0;i=j) return 0; 31 | 32 | if(dp[i][j]!=-1){ 33 | return dp[i][j]; 34 | } 35 | if(s.charAt(i)==s.charAt(j)){ 36 | dp[i][j] = minInsert(s,i+1,j-1,dp); 37 | return dp[i][j]; 38 | }else{ 39 | int dec1 = 1+minInsert(s,i+1,j,dp); 40 | int dec2 = 1+minInsert(s,i,j-1,dp); 41 | dp[i][j] = Math.min(dec1,dec2); 42 | return dp[i][j]; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /1326 Minimum Number of Taps to Open to Water a Garden: -------------------------------------------------------------------------------- 1 | There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). 2 | 3 | There are n + 1 taps located at points [0, 1, ..., n] in the garden. 4 | 5 | Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. 6 | 7 | Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1. 8 | 9 | 10 | public int minTaps(int n, int[] ranges) { 11 | 12 | int min = 0; 13 | int max = 0; 14 | int open = 0; 15 | int index = 0; 16 | while(maxmax){ 20 | max = i+ranges[i]; 21 | index = i; 22 | } 23 | } 24 | if(min==max)return -1; 25 | open++; 26 | min = max; 27 | } 28 | 29 | return open; 30 | } 31 | -------------------------------------------------------------------------------- /1345 Jump Game IV: -------------------------------------------------------------------------------- 1 | Given an array of integers arr, you are initially positioned at the first index of the array. 2 | 3 | In one step you can jump from index i to index: 4 | 5 | i + 1 where: i + 1 < arr.length. 6 | i - 1 where: i - 1 >= 0. 7 | j where: arr[i] == arr[j] and i != j. 8 | Return the minimum number of steps to reach the last index of the array. 9 | 10 | Notice that you can not jump outside of the array at any time. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: arr = [100,-23,-23,404,100,23,23,23,3,404] 17 | Output: 3 18 | Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array. 19 | 20 | 21 | public int minJumps(int[] arr) { 22 | 23 | if(arr.length==1)return 0; 24 | int jump = 0; 25 | int[] visited = new int[arr.length]; 26 | 27 | HashMap> map = new HashMap(); 28 | 29 | for(int i=0;i q = new ArrayDeque(); 39 | q.add(0); 40 | visited[0]=1; 41 | 42 | while(!q.isEmpty()){ 43 | 44 | int n = q.size(); 45 | for(int i=0;i=0 && index-1=0 && index+1 seen = new HashSet<>(); 16 | 17 | for (int i=0;i> res = new ArrayList(); 20 | public List> threeSum(int[] nums) { 21 | Arrays.sort(nums); 22 | for(int i=0;itarget){ 35 | j--; 36 | }else if(nums[i]+nums[j] list = new ArrayList(); 40 | list.add(a1);list.add(nums[i]);list.add(nums[j]); 41 | 42 | res.add(list); 43 | 44 | 45 | 46 | //duplicate b 47 | while(inums[1])return 0; 10 | if(i==nums.length-1 && nums[i]>nums[i-1])return nums.length-1; 11 | 12 | if(nums[i]>nums[i+1] && nums[i]>nums[i-1])return i; 13 | } 14 | 15 | return -1; 16 | } 17 | 18 | // OPTIMIZE CODE 19 | 20 | 21 | public int findPeakElement(int[] nums) { 22 | 23 | if(nums.length==1)return 0; 24 | 25 | int low = 0 , high = nums.length-1; 26 | while(lownums[mid-1]) && (mid==nums.length-1 || nums[mid]>nums[mid+1]))return mid; 29 | 30 | if(nums[mid]>nums[mid+1]){ 31 | high = mid; 32 | }else{ 33 | low = mid+1; 34 | } 35 | } 36 | 37 | return high; 38 | } 39 | -------------------------------------------------------------------------------- /164 Maximum Gap: -------------------------------------------------------------------------------- 1 | Given an unsorted array, find the maximum difference between the successive elements in its sorted form. 2 | 3 | Return 0 if the array contains less than 2 elements. 4 | 5 | Example 1: 6 | 7 | Input: [3,6,9,1] 8 | Output: 3 9 | Explanation: The sorted form of the array is [1,3,6,9], either 10 | (3,6) or (6,9) has the maximum difference 3. 11 | 12 | 13 | 14 | 15 | public int maximumGap(int[] nums) { 16 | 17 | if(nums.length<2)return 0; 18 | int min = nums[0] , max = 0; 19 | 20 | for(int num : nums){ 21 | min = Math.min(min,num); 22 | max = Math.max(max,num); 23 | } 24 | 25 | int interval = (int)Math.ceil((max-min+0.0)/(nums.length-1)); 26 | 27 | int[] bucketMin = new int[nums.length-1]; 28 | int[] bucketMax = new int[nums.length-1]; 29 | 30 | Arrays.fill(bucketMin,Integer.MAX_VALUE); 31 | Arrays.fill(bucketMax,-1); 32 | 33 | for(int i=0;itarget){ 28 | end--; 29 | }else if(numbers[start]+numbers[end] letterCombinations(String digits) { 14 | 15 | List result = new ArrayList(); 16 | if(digits.length()==0)return result; 17 | 18 | HashMap map = new HashMap(); 19 | map.put("2","abc"); map.put("3","def"); map.put("4","ghi"); 20 | map.put("5","jkl"); map.put("6","mno"); map.put("7","pqrs"); 21 | map.put("8","tuv"); map.put("9","wxyz"); 22 | 23 | Deque deque = new ArrayDeque(); 24 | deque.add(""); 25 | 26 | for(int i=0;i0){ 14 | count += n/5; 15 | n = n/5; 16 | } 17 | return count; 18 | } 19 | -------------------------------------------------------------------------------- /188 Best Time to Buy and Sell Stock IV: -------------------------------------------------------------------------------- 1 | Say you have an array for which the i-th element is the price of a given stock on day i. 2 | 3 | Design an algorithm to find the maximum profit. You may complete at most k transactions. 4 | 5 | Note: 6 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 7 | 8 | Example 1: 9 | 10 | Input: [2,4,1], k = 2 11 | Output: 2 12 | Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. 13 | 14 | 15 | 16 | 17 | public int maxProfit(int k, int[] prices) { 18 | if(k==0 || prices.length==0)return 0; 19 | int[] profit = new int[prices.length]; 20 | if(k>=prices.length/2){ 21 | int p = 0; 22 | for(int i=1;iprices[i-1]){ 24 | p = p+ prices[i]-prices[i-1]; 25 | } 26 | } 27 | return p; 28 | } 29 | 30 | //1 trans 31 | int min = prices[0] , p = 0; 32 | for(int i =0;i stack = new Stack(); //O(n) 22 | for(char c : s.toCharArray()){ //O(n) 23 | if(c=='(' || c=='[' || c=='{'){ 24 | stack.add(c); 25 | }else{ 26 | if(stack.isEmpty())return false; 27 | if(c==']' && stack.peek()!='[')return false; 28 | if(c==')' && stack.peek()!='(')return false; 29 | if(c=='}' && stack.peek()!='{')return false; 30 | stack.pop(); 31 | } 32 | } 33 | 34 | return stack.isEmpty(); 35 | } 36 | -------------------------------------------------------------------------------- /200 Number of Islands: -------------------------------------------------------------------------------- 1 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: grid = [ 8 | ["1","1","1","1","0"], 9 | ["1","1","0","1","0"], 10 | ["1","1","0","0","0"], 11 | ["0","0","0","0","0"] 12 | ] 13 | Output: 1 14 | 15 | 16 | public int numIslands(char[][] grid) { 17 | if(grid.length==0)return 0; 18 | int islands = 0; 19 | 20 | for(int i=0;igrid.length-1 || j>grid[0].length-1)return; 34 | 35 | if(grid[i][j]=='0')return; 36 | 37 | grid[i][j] = '0'; 38 | dfs(grid,i+1,j); 39 | dfs(grid,i-1,j); 40 | dfs(grid,i,j-1); 41 | dfs(grid,i,j+1); 42 | 43 | } 44 | -------------------------------------------------------------------------------- /216 Combination Sum III: -------------------------------------------------------------------------------- 1 | Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. 2 | 3 | Note: 4 | 5 | All numbers will be positive integers. 6 | The solution set must not contain duplicate combinations. 7 | Example 1: 8 | 9 | Input: k = 3, n = 7 10 | Output: [[1,2,4]] 11 | Example 2: 12 | 13 | Input: k = 3, n = 9 14 | Output: [[1,2,6], [1,3,5], [2,3,4]] 15 | 16 | 17 | 18 | public List> combinationSum3(int k, int n) { 19 | List> subset = new ArrayList(); 20 | dfs(subset,1,new ArrayList(),k,n); 21 | return subset; 22 | } 23 | 24 | void dfs(List> subset , int index ,List current,int k,int target){ 25 | 26 | if(current.size()==k){ 27 | if(target==0){ 28 | subset.add(new ArrayList(current)); 29 | } 30 | return; 31 | } 32 | 33 | 34 | 35 | for(int i = index;i<=9;i++){//1------9 36 | current.add(i); 37 | dfs(subset,i+1,current,k,target-i); 38 | current.remove(current.size()-1); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /22 Generate Parentheses: -------------------------------------------------------------------------------- 1 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 2 | 3 | For example, given n = 3, a solution set is: 4 | 5 | [ 6 | "((()))", 7 | "(()())", 8 | "(())()", 9 | "()(())", 10 | "()()()" 11 | ] 12 | 13 | 14 | public List generateParenthesis(int n) { 15 | List result = new ArrayList(); 16 | findAll("(",1,0,result,n); 17 | return result; 18 | } 19 | 20 | void findAll(String current,int o,int c, List result,int n){ 21 | 22 | if(current.length()==2*n){ 23 | result.add(current); 24 | return; 25 | } 26 | 27 | if(o>i)&1; 23 | } 24 | return cnt==1; 25 | } 26 | -------------------------------------------------------------------------------- /235 Lowest Common Ancestor of a Binary Search Tree: -------------------------------------------------------------------------------- 1 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 2 | 3 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” 4 | 5 | Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5] 6 | 7 | 8 | 9 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 10 | 11 | if(p.valroot.val && q.val>root.val){ 14 | return lowestCommonAncestor(root.right,p,q); 15 | }else{ 16 | return root; 17 | } 18 | } 19 | 20 | 21 | 22 | 8 23 | / \ 24 | 6 11 25 | /\ /\ 26 | 4 7 9 12 27 | 28 | //p = 4 , q = 7 ans = 6 29 | //p = 4 , q = 6 ans = 6 30 | //p = 4 , q = 12 ans = 8 31 | //p = 4 , q = 11 ans = 8 32 | -------------------------------------------------------------------------------- /252 Meeting Rooms: -------------------------------------------------------------------------------- 1 | Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings. 2 | 3 | Example 1: 4 | 5 | Input: intervals = [[0,30],[5,10],[15,20]] 6 | Output: false 7 | Example 2: 8 | 9 | Input: intervals = [[7,10],[2,4]] 10 | Output: true 11 | 12 | public boolean canAttendMeetings(int[][] intervals) { 13 | if(intervals.length==0)return true; 14 | Arrays.sort(intervals , (a,b)->Integer.compare(a[0],b[0])); //O(nlogn) 15 | Stack stack = new Stack(); //O(n) 16 | stack.add(intervals[0]); 17 | 18 | for(int i=1;istartpoint2){ 28 | return false; 29 | } 30 | 31 | stack.add(intervals[i]); 32 | } 33 | 34 | return true; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /253 Meeting Rooms II: -------------------------------------------------------------------------------- 1 | Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required. 2 | 3 | 4 | Example 1: 5 | 6 | Input: intervals = [[0,30],[5,10],[15,20]] 7 | Output: 2 8 | Example 2: 9 | 10 | Input: intervals = [[7,10],[2,4]] 11 | Output: 1 12 | 13 | public int minMeetingRooms(int[][] intervals) { 14 | 15 | Arrays.sort(intervals,(a,b)->Integer.compare(a[0],b[0])); 16 | PriorityQueue p = new PriorityQueue();//O(n) 17 | 18 | for(int[] interval : intervals){ 19 | 20 | if(p.isEmpty()){ 21 | p.add(interval[1]); 22 | continue; 23 | } 24 | 25 | if(p.peek()<=interval[0]){//same room 26 | p.remove(); 27 | } 28 | 29 | p.add(interval[1]); //O(nlogn) 30 | } 31 | 32 | return p.size(); 33 | 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /268 Missing Number: -------------------------------------------------------------------------------- 1 | Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. 2 | 3 | Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? 4 | 5 | Example 1: 6 | 7 | Input: nums = [3,0,1] 8 | Output: 2 9 | Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. 10 | Example 2: 11 | 12 | Input: nums = [0,1] 13 | Output: 2 14 | Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums. 15 | 16 | JAVA CODE 17 | class Solution { 18 | public int missingNumber(int[] nums) { 19 | 20 | int n = nums.length;//10 21 | int expectedTotal = (n*(n+1))/2; //55 22 | 23 | int total = 0; 24 | for(int num:nums){ 25 | total += num; 26 | } 27 | 28 | return expectedTotal-total; 29 | 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /287 Find the Duplicate Number: -------------------------------------------------------------------------------- 1 | Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 2 | 3 | Example 1: 4 | 5 | Input: [1,3,4,2,2] 6 | Output: 2 7 | Example 2: 8 | 9 | Input: [3,1,3,4,2] 10 | Output: 3 11 | Note: 12 | 13 | You must not modify the array (assume the array is read only). 14 | You must use only constant, O(1) extra space. 15 | Your runtime complexity should be less than O(n2). 16 | There is only one duplicate number in the array, but it could be repeated more than once. 17 | 18 | public int findDuplicate(int[] nums) { 19 | 20 | for(int i=0;i seen = new HashSet(); 29 | int max = 0; 30 | 31 | while(right findSubstring(String s, String[] words) { 16 | List result = new ArrayList(); 17 | if(s.length()==0 || words.length==0)return result; 18 | 19 | HashMap map1 = new HashMap(); 20 | 21 | for(int i=0;i map2 = new HashMap(); 34 | int k = 0; 35 | int n = 0; 36 | while(k map1 (step1) 53 | 54 | //foo 1 55 | //bar 1 56 | 57 | //barfoothefoobarman (step 2) 58 | 59 | //bar foo map2 bar foo (step3) == map1 (0) (step4) 60 | //arf oot map2 arf oot (step3) == map1 61 | //rfo oth 62 | //... 63 | //.. 64 | //bar man map2 bar foo (step3) == map1 65 | -------------------------------------------------------------------------------- /31 Next Permutation: -------------------------------------------------------------------------------- 1 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 2 | 3 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 4 | 5 | The replacement must be in-place and use only constant extra memory. 6 | 7 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 8 | 9 | 1,2,3 → 1,3,2 10 | 3,2,1 → 1,2,3 11 | 1,1,5 → 1,5,1 12 | 13 | public void nextPermutation(int[] nums) { 14 | 15 | int k = nums.length-2; 16 | 17 | while(k>=0 && nums[k]>=nums[k+1])k--; 18 | 19 | //CASE 1 20 | if(k==-1){ 21 | reverseArray(0,nums.length-1,nums); 22 | return; 23 | } 24 | 25 | //CASE 2 26 | for(int i = nums.length-1;i>k;i--){ 27 | if(nums[i]>nums[k]){//2 28 | int temp = nums[i]; 29 | nums[i] = nums[k]; 30 | nums[k] = temp; 31 | break; 32 | } 33 | } 34 | reverseArray(k+1,nums.length-1,nums); 35 | 36 | 37 | } 38 | 39 | void reverseArray(int i,int j,int[] nums){ 40 | while(i ct = new Stack(); 18 | Stack index = new Stack(); 19 | index.add(-1); 20 | int max = 0; 21 | 22 | for(int i=0;imatrix.length-1 || j>matrix[0].length-1)return 0; 34 | else if(pre>=matrix[i][j])return 0; 35 | 36 | 37 | 38 | int path1 = dfs(matrix,i-1,j,matrix[i][j]); 39 | int path2 = dfs(matrix,i+1,j,matrix[i][j]); 40 | int path3 = dfs(matrix,i,j-1,matrix[i][j]); 41 | int path4 = dfs(matrix,i,j+1,matrix[i][j]); 42 | 43 | 44 | int max1 = Math.max(path1,path2); 45 | int max2 = Math.max(path3,path4); 46 | 47 | int count = 1+Math.max(max1,max2); 48 | 49 | 50 | return count; 51 | } 52 | 53 | -------------------------------------------------------------------------------- /336 Palindrome Pairs: -------------------------------------------------------------------------------- 1 | Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. 2 | 3 | Example 1: 4 | 5 | Input: ["abcd","dcba","lls","s","sssll"] 6 | Output: [[0,1],[1,0],[3,2],[2,4]] 7 | Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"] 8 | 9 | 10 | public List> palindromePairs(String[] words) { 11 | List> result = new ArrayList(); 12 | int n = words.length; 13 | 14 | for(int i=0;itarget){ 19 | end = mid-1; 20 | }else if (nums[mid] map = new HashMap(); //step1 16 | 17 | int ans[] = new int[k]; 18 | 19 | for(int i=0;i pq = new PriorityQueue<>((a,b)->map.get(b)-map.get(a)); 25 | 26 | for(Map.Entry entry : map.entrySet()){ 27 | pq.add(entry.getKey()); 28 | } 29 | 30 | 31 | int index = 0; 32 | while(k>0){ 33 | ans[index] = pq.poll(); 34 | index++; 35 | k--; 36 | } 37 | 38 | return ans; 39 | } 40 | 41 | 42 | 43 | //Approach 44 | 45 | //nums = [1,1,1,2,2,3], k = 2 46 | 47 | //Step1 HashMap map 48 | 49 | //key count 50 | //1 --- 3 51 | //2-----2 52 | //3-----1 53 | //5-----6 54 | 55 | //Step 2 PriorityQueue [5,1,2,3] 56 | 57 | //Step 3 ans[2] = 5 , 1 58 | -------------------------------------------------------------------------------- /36 Valid Sudoku: -------------------------------------------------------------------------------- 1 | Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: 2 | 3 | Each row must contain the digits 1-9 without repetition. 4 | Each column must contain the digits 1-9 without repetition. 5 | Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. 6 | 7 | 8 | 9 | Leetcode suggestion code 10 | 11 | public boolean isValidSudoku(char[][] board) { 12 | // init data 13 | HashMap [] rows = new HashMap[9]; 14 | HashMap [] columns = new HashMap[9]; 15 | HashMap [] boxes = new HashMap[9]; 16 | for (int i = 0; i < 9; i++) { 17 | rows[i] = new HashMap(); 18 | columns[i] = new HashMap(); 19 | boxes[i] = new HashMap(); 20 | } 21 | 22 | // validate a board 23 | for (int i = 0; i < 9; i++) { 24 | for (int j = 0; j < 9; j++) { 25 | char num = board[i][j]; 26 | if (num != '.') { 27 | int n = (int)num; 28 | int box_index = (i / 3 ) * 3 + j / 3; 29 | 30 | // keep the current cell value 31 | rows[i].put(n, rows[i].getOrDefault(n, 0) + 1); 32 | columns[j].put(n, columns[j].getOrDefault(n, 0) + 1); 33 | boxes[box_index].put(n, boxes[box_index].getOrDefault(n, 0) + 1); 34 | 35 | // check if this value has been already seen before 36 | if (rows[i].get(n) > 1 || columns[j].get(n) > 1 || boxes[box_index].get(n) > 1) 37 | return false; 38 | } 39 | } 40 | } 41 | 42 | return true; 43 | } 44 | 45 | 46 | Video Code 47 | public boolean isValidSudoku(char[][] board) { 48 | 49 | HashSet seen = new HashSet(); 50 | for(int i=0;i<9;i++){ 51 | for(int j=0;j<9;j++){ 52 | if(board[i][j]!='.'){ 53 | if(!seen.add("row"+i+board[i][j]) || !seen.add("column"+j+board[i][j]) ){ 54 | return false; 55 | } 56 | if(!seen.add("box"+(i/3)*3+j/3+board[i][j])){ 57 | return false; 58 | } 59 | } 60 | } 61 | } 62 | return true; 63 | } 64 | -------------------------------------------------------------------------------- /39 Combination Sum: -------------------------------------------------------------------------------- 1 | Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. 2 | 3 | The same repeated number may be chosen from candidates unlimited number of times. 4 | 5 | Note: 6 | 7 | All numbers (including target) will be positive integers. 8 | The solution set must not contain duplicate combinations. 9 | Example 1: 10 | 11 | Input: candidates = [2,3,6,7], target = 7, 12 | A solution set is: 13 | [ 14 | [7], 15 | [2,2,3] 16 | ] 17 | 18 | 19 | public List> combinationSum(int[] candidates, int target) { 20 | List> subset = new ArrayList(); 21 | dfs(subset,0,candidates,new ArrayList(),target); 22 | return subset; 23 | } 24 | 25 | void dfs( List> subset,int index,int[] candidates,List current,int target){ 26 | 27 | if(target<0)return; 28 | if(target==0){ 29 | subset.add(new ArrayList(current)); 30 | return; 31 | } 32 | 33 | for(int i=index;i> combinationSum2(int[] candidates, int target) { 21 | Arrays.sort(candidates); 22 | List> subset = new ArrayList(); 23 | dfs(subset,0,candidates,new ArrayList(),target); 24 | return subset; 25 | } 26 | 27 | void dfs( List> subset,int index,int[] candidates,List current, int target){ 28 | 29 | if(target<0)return; 30 | if(target==0){ 31 | subset.add(new ArrayList(current)); 32 | return; 33 | } 34 | 35 | for(int i=index;iindex && candidates[i]==candidates[i-1])continue; 37 | current.add(candidates[i]); 38 | dfs(subset,i+1,candidates, current,target-candidates[i]); 39 | current.remove(current.size()-1); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /416 Partition Equal Subset Sum: -------------------------------------------------------------------------------- 1 | 2 | Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. 3 | 4 | Note: 5 | 6 | Each of the array element will not exceed 100. 7 | The array size will not exceed 200. 8 | 9 | 10 | Example 1: 11 | 12 | Input: [1, 5, 11, 5] 13 | 14 | Output: true 15 | 16 | Explanation: The array can be partitioned as [1, 5, 5] and [11]. 17 | 18 | 19 | class Solution { 20 | public boolean canPartition(int[] nums) { 21 | int sum = 0; 22 | for(int i=0;i> pacificAtlantic(int[][] matrix) { 16 | List> cord = new ArrayList(); 17 | if(matrix.length==0)return cord; 18 | 19 | int row = matrix.length; 20 | int col = matrix[0].length; 21 | 22 | int[][] paci = new int[row][col]; 23 | int[][] alt = new int[row][col]; 24 | 25 | 26 | //first row (pacific) 27 | for(int i=0;i c = new ArrayList(); 47 | c.add(i);c.add(j); 48 | cord.add(c); 49 | } 50 | } 51 | } 52 | 53 | return cord; 54 | } 55 | 56 | void dfs(int[][] matrix , int row , int col , int[][] temp,int pre){ 57 | 58 | if(row<0 || col<0 || row>matrix.length-1 || col>matrix[0].length-1)return; 59 | else if(pre>matrix[row][col])return; 60 | else if(temp[row][col]==1)return; 61 | 62 | temp[row][col] = 1; 63 | 64 | dfs(matrix,row+1,col,temp,matrix[row][col]); 65 | dfs(matrix,row-1,col,temp,matrix[row][col]); 66 | dfs(matrix,row,col-1,temp,matrix[row][col]); 67 | dfs(matrix,row,col+1,temp,matrix[row][col]); 68 | } 69 | -------------------------------------------------------------------------------- /42 Trapping Rain Water: -------------------------------------------------------------------------------- 1 | Brute Force 2 | 3 | public int trap(int[] height) { 4 | 5 | int n = height.length; 6 | int[] leftMax = new int[n]; 7 | int[] rightMax = new int[n]; 8 | int max = 0; 9 | int totalwater = 0; 10 | 11 | 12 | for(int i=0;i=0;i--){ 20 | max = Math.max(max,height[i]); 21 | rightMax[i] = max; 22 | } 23 | 24 | for(int i=n-1;i>=0;i--){ 25 | int water = Math.min(leftMax[i],rightMax[i])-height[i]; 26 | totalwater += water; 27 | } 28 | return totalwater; 29 | } 30 | 31 | ---------************** Optimal Code **************-------------- 32 | 33 | public int trap(int[] height) { 34 | 35 | int n = height.length; 36 | int totalwater = 0; 37 | int max = 0; 38 | int maxIndex = 0; 39 | 40 | for(int i=0;imax){ 42 | max = height[i]; //rmax 43 | maxIndex = i; 44 | } 45 | } 46 | 47 | int leftMax = 0; 48 | //part1 49 | for(int i=0;imaxIndex;i--){ 58 | leftMax = Math.max(leftMax,height[i]); 59 | int water = Math.min(leftMax,max)-height[i]; 60 | totalwater += water; 61 | } 62 | 63 | 64 | return totalwater; 65 | } 66 | -------------------------------------------------------------------------------- /438 Find All Anagrams in a String: -------------------------------------------------------------------------------- 1 | Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. 2 | 3 | Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. 4 | 5 | The order of output does not matter. 6 | 7 | Example 1: 8 | 9 | Input: 10 | s: "cbaebabacd" p: "abc" 11 | 12 | Output: 13 | [0, 6] 14 | 15 | Explanation: 16 | The substring with start index = 0 is "cba", which is an anagram of "abc". 17 | The substring with start index = 6 is "bac", which is an anagram of "abc". 18 | 19 | 20 | ********* Optimal Solution *************** 21 | 22 | 23 | public List findAnagrams(String s, String p) { 24 | 25 | int[] pCount = new int[256]; 26 | List res = new ArrayList(); 27 | 28 | for(char c :p.toCharArray()){ 29 | pCount[c]++; 30 | } 31 | 32 | int count = 0; 33 | int left = 0; 34 | 35 | for(int right=0;right0){ 39 | count++; 40 | } 41 | 42 | while(count==p.length()){ 43 | 44 | if(right-left+1==p.length()){ 45 | res.add(left); 46 | } 47 | 48 | char temp = s.charAt(left); 49 | pCount[temp]++; 50 | if(pCount[temp]-1>=0){ 51 | count--; 52 | } 53 | left++; 54 | } 55 | } 56 | return res; 57 | } 58 | 59 | 60 | //Video solution (hindi) in my youtube channel 61 | -------------------------------------------------------------------------------- /44 Wildcard Matching: -------------------------------------------------------------------------------- 1 | Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. 2 | 3 | '?' Matches any single character. 4 | '*' Matches any sequence of characters (including the empty sequence). 5 | The matching should cover the entire input string (not partial). 6 | 7 | Note: 8 | 9 | s could be empty and contains only lowercase letters a-z. 10 | p could be empty and contains only lowercase letters a-z, and characters like ? or *. 11 | Example 1: 12 | 13 | Input: 14 | s = "aa" 15 | p = "a" 16 | Output: false 17 | Explanation: "a" does not match the entire string "aa". 18 | 19 | 20 | class Solution { 21 | public boolean isMatch(String s, String p) { 22 | 23 | boolean[][] dp = new boolean[s.length()+1][p.length()+1]; 24 | dp[0][0] = true; 25 | 26 | char[] string = new char[s.length()+1]; 27 | char[] pattern = new char[p.length()+1]; 28 | 29 | string[0] = (char)0; 30 | pattern[0] = (char)0; 31 | 32 | for(int i=0;i pq = new PriorityQueue<>((a, b) -> count[b] - count[a]); 25 | 26 | //e t r 27 | 28 | for(int i=0;i> permute(int[] nums) { 18 | List> subset = new ArrayList(); 19 | boolean[] used = new boolean[nums.length]; 20 | dfs(subset,nums,new ArrayList(),used); 21 | return subset; 22 | } 23 | 24 | void dfs( List> subset,int[] nums,List current, boolean[] used){ 25 | if(current.size()==nums.length){ 26 | subset.add(new ArrayList(current)); 27 | return; 28 | } 29 | 30 | for(int i=0;i stack = new Stack(); 15 | int index = 0; 16 | 17 | for(int i=0;i> groupAnagrams(String[] strs) { 15 | 16 | List> result = new ArrayList(); 17 | HashMap> map = new HashMap(); 18 | //["eat", "tea", "tan", "ate", "nat", "bat"] 19 | for(int i=0;i> 36 | 37 | //aet , List 38 | //ant , List 39 | //abt , List 40 | 41 | -------------------------------------------------------------------------------- /516 Longest Palindromic Subsequence: -------------------------------------------------------------------------------- 1 | Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. 2 | 3 | Example 1: 4 | Input: 5 | 6 | "bbbab" 7 | Output: 8 | 4 9 | 10 | 11 | public int longestPalindromeSubseq(String s) { 12 | 13 | String text1 = s; 14 | String text2 = new StringBuilder(s).reverse().toString(); 15 | 16 | 17 | int[][] dp = new int[text1.length()+1][text2.length()+1]; 18 | 19 | for(int i=1;i spiralOrder(int[][] matrix) { 14 | 15 | List list = new ArrayList(); 16 | 17 | int row = matrix.length; 18 | if(row ==0 )return list; 19 | int col = matrix[0].length; 20 | 21 | 22 | 23 | 24 | int l = 0 , r = col-1 , t = 0 , b = row-1 , d = 0; 25 | 26 | while(l<=r && t<=b){ 27 | if(d==0){ 28 | for(int i=l;i<=r;i++){ 29 | list.add(matrix[t][i]); 30 | } 31 | d=1;t++; 32 | }else if(d==1){ 33 | for(int i=t;i<=b;i++){ 34 | list.add(matrix[i][r]); 35 | } 36 | d=2;r--; 37 | }else if (d==2){ 38 | for(int i =r;i>=l;i--){ 39 | list.add(matrix[b][i]); 40 | } 41 | d=3;b--; 42 | }else if (d==3){ 43 | for(int i = b;i>=t;i--){ 44 | list.add(matrix[i][l]); 45 | } 46 | d=0;l++; 47 | } 48 | } 49 | return list; 50 | 51 | } 52 | -------------------------------------------------------------------------------- /55 Jump Game: -------------------------------------------------------------------------------- 1 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 2 | 3 | Each element in the array represents your maximum jump length at that position. 4 | 5 | Determine if you are able to reach the last index. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: nums = [2,3,1,1,4] 12 | Output: true 13 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 14 | Example 2: 15 | 16 | Input: nums = [3,2,1,0,4] 17 | Output: false 18 | Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 19 | 20 | 21 | public boolean canJump(int[] nums) { 22 | 23 | int pos = 0; 24 | int des = 0; 25 | 26 | for(int i=0;i Integer.compare(a[0],b[0])); //O(nlogn) 19 | Stack stack = new Stack(); //O(n) 20 | stack.add(intervals[0]); 21 | 22 | 23 | for(int i=1;i=startpoint2){ 36 | int[] merge = new int[]{startpoint1,endmax}; 37 | stack.add(merge); 38 | }else{ 39 | stack.add(poparray); 40 | stack.add(intervals[i]); 41 | } 42 | 43 | } 44 | 45 | int[][] output = new int[stack.size()][2]; 46 | 47 | for(int i=output.length-1;i>=0;i--){ 48 | int[] poparray = stack.pop(); 49 | output[i][0] = poparray[0]; 50 | output[i][1] = poparray[1]; 51 | } 52 | return output; 53 | } 54 | -------------------------------------------------------------------------------- /581 Shortest Unsorted Continuous Subarray: -------------------------------------------------------------------------------- 1 | Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. 2 | 3 | You need to find the shortest such subarray and output its length. 4 | 5 | Example 1: 6 | Input: [2, 6, 4, 8, 10, 9, 15] 7 | Output: 5 8 | Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. 9 | 10 | 11 | public int findUnsortedSubarray(int[] nums) { 12 | 13 | int[] clone = nums.clone(); 14 | Arrays.sort(clone); 15 | 16 | if(Arrays.equals(clone,nums))return 0; 17 | 18 | int start = 0, end = 0; 19 | 20 | for(int i=0;i=0;i--){ 27 | if(nums[i]!=clone[i]){ 28 | end = i; break; 29 | } 30 | } 31 | 32 | 33 | return end-start+1; 34 | 35 | } 36 | 37 | 38 | //Approach 39 | 40 | //[2, 6, 4, 8, 10, 9, 15] //nums 41 | //[2, 4, 6, 8, 9, 10, 15] //clone - sorted 42 | 43 | //start = 1 44 | //end = 5 45 | 46 | //ans = end-start+1; 47 | -------------------------------------------------------------------------------- /59 Spiral Matrix II: -------------------------------------------------------------------------------- 1 | Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 2 | 3 | Example: 4 | 5 | Input: 3 6 | Output: 7 | [ 8 | [ 1, 2, 3 ], 9 | [ 8, 9, 4 ], 10 | [ 7, 6, 5 ] 11 | ] 12 | 13 | public int[][] generateMatrix(int n) { 14 | 15 | int t = 0 , b = n-1 , l = 0 , r = n-1 , d = 0; 16 | int[][] matrix = new int[n][n]; 17 | int num = 1; 18 | 19 | 20 | while(l<=r && t<=b){ 21 | 22 | if(d==0){ 23 | for(int i=l;i<=r;i++){ 24 | matrix[t][i] = num; num++; 25 | } 26 | d=1;t++; 27 | }else if(d==1){ 28 | for(int i=t;i<=b;i++){ 29 | matrix[i][r] = num; num++; 30 | } 31 | d=2;r--; 32 | }else if(d==2){ 33 | for(int i=r;i>=l;i--){ 34 | matrix[b][i] = num; num++; 35 | } 36 | d=3;b--; 37 | }else if(d==3){ 38 | for(int i=b;i>=t;i--){ 39 | matrix[i][l] = num; num++; 40 | } 41 | d=0;l++; 42 | } 43 | } 44 | return matrix; 45 | } 46 | -------------------------------------------------------------------------------- /62 Unique Paths: -------------------------------------------------------------------------------- 1 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 2 | 3 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 4 | 5 | How many possible unique paths are there? 6 | 7 | 8 | public int uniquePaths(int m, int n) { 9 | int[][] dp = new int[m][n]; 10 | 11 | for(int i=0;i 1 4 | 'B' -> 2 5 | ... 6 | 'Z' -> 26 7 | Beyond that, now the encoded string can also contain the character '*', which can be treated as one of the numbers from 1 to 9. 8 | 9 | Given the encoded message containing digits and the character '*', return the total number of ways to decode it. 10 | 11 | Also, since the answer may be very large, you should return the output mod 109 + 7. 12 | 13 | Example 1: 14 | Input: "*" 15 | Output: 9 16 | Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I". 17 | 18 | 19 | 20 | 21 | public int numDecodings(String s) { 22 | long[] dp = new long[s.length()+1]; 23 | dp[0] = 1; 24 | 25 | if(s.charAt(0)=='0')return 0; 26 | if(s.charAt(0)!='0'){ 27 | dp[1] = 1; 28 | } 29 | if(s.charAt(0)=='*'){ 30 | dp[1] = 9; 31 | } 32 | 33 | for(int i=2;i<=s.length();i++){ 34 | int first = s.charAt(i-2); 35 | int second = s.charAt(i-1); 36 | 37 | 38 | 39 | if(second>'0'){ 40 | dp[i] += dp[i-1]; 41 | }else if(second=='*'){ 42 | dp[i] += 9*dp[i-1]; 43 | } 44 | 45 | 46 | if(first=='*'){ 47 | if(second=='*'){ 48 | dp[i] += 15*dp[i-2]; 49 | }else if(second<='6'){ 50 | dp[i] += 2*dp[i-2]; 51 | }else{ 52 | dp[i] += dp[i-2]; 53 | } 54 | }else if(first=='1' || first=='2'){ 55 | if(second=='*'){ 56 | if(first=='1'){ 57 | dp[i] += 9*dp[i-2]; 58 | }else{ 59 | dp[i] += 6*dp[i-2]; 60 | } 61 | } 62 | else if( ((first-'0')*10+(second-'0')) <= 26){ 63 | dp[i] += dp[i-2]; 64 | } 65 | } 66 | 67 | dp[i] %= 1000000007; 68 | } 69 | 70 | return (int)dp[s.length()]; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /64 Minimum Path Sum: -------------------------------------------------------------------------------- 1 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 2 | 3 | Note: You can only move either down or right at any point in time. 4 | 5 | Example: 6 | 7 | Input: 8 | [ 9 | [1,3,1], 10 | [1,5,1], 11 | [4,2,1] 12 | ] 13 | Output: 7 14 | Explanation: Because the path 1→3→1→1→1 minimizes the sum. 15 | 16 | 17 | public int minPathSum(int[][] grid) { 18 | 19 | if(grid.length==0)return 0; 20 | 21 | //first row 22 | for(int i=1;ir){ 27 | return null; 28 | } 29 | int max = nums[l]; int index = l; 30 | for(int i=l;i<=r;i++){ 31 | if(nums[i]>max){ 32 | max = nums[i]; 33 | index = i; 34 | } 35 | } 36 | 37 | TreeNode root = new TreeNode(nums[index]); 38 | root.left = buildTree(l,index-1,nums); 39 | root.right = buildTree(index+1,r,nums); 40 | 41 | return root; 42 | 43 | } 44 | -------------------------------------------------------------------------------- /680 Valid Palindrome II: -------------------------------------------------------------------------------- 1 | Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. 2 | 3 | Example 1: 4 | Input: "aba" 5 | Output: True 6 | 7 | 8 | public boolean validPalindrome(String s) { 9 | 10 | int start= 0 , end = s.length()-1; 11 | int count1 = 0 , count2 = 0; 12 | 13 | while(start s = new Stack(); 30 | int score = 0; 31 | 32 | for(int i=0;iInteger.MAX_VALUE || num=0){ 23 | 24 | if(matrix[i][j]>target){ //7>4 25 | j--; 26 | }else if (matrix[i][j] map = new HashMap(); 17 | 18 | for(char c : t.toCharArray()){ 19 | if(map.containsKey(c)){ 20 | map.put(c,map.get(c)+1); 21 | }else{ 22 | map.put(c,1); 23 | } 24 | } 25 | 26 | int count = 0; 27 | int start = 0; 28 | int minlength = Integer.MAX_VALUE; 29 | int minleft = 0; 30 | 31 | for(int i=0;i=0){ 35 | count++; 36 | } 37 | } 38 | 39 | 40 | while(count==t.length()){//eliglble window 41 | 42 | //length save 43 | if(minlength>i-start+1){ 44 | minlength = i-start+1; //6 45 | minleft = start; 46 | } 47 | //remove 48 | if(map.containsKey(s.charAt(start))){ 49 | map.put(s.charAt(start),map.get(s.charAt(start))+1); 50 | if(map.get(s.charAt(start))>0){count--;} 51 | } 52 | start++; 53 | } 54 | } 55 | if(minlength>s.length())return ""; 56 | return s.substring(minleft,minleft+minlength); 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /77 Combinations: -------------------------------------------------------------------------------- 1 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 2 | 3 | Example: 4 | 5 | Input: n = 4, k = 2 6 | Output: 7 | [ 8 | [2,4], 9 | [3,4], 10 | [2,3], 11 | [1,2], 12 | [1,3], 13 | [1,4], 14 | ] 15 | 16 | 17 | public List> combine(int n, int k) {//n==3 18 | 19 | List> subset = new ArrayList(); 20 | dfs(subset,1,new ArrayList(),n,k); 21 | return subset; 22 | 23 | } 24 | 25 | void dfs( List> subset,int index,List current,int n,int k){ 26 | 27 | if(current.size()==k){ 28 | subset.add(new ArrayList(current)); 29 | return; 30 | } 31 | 32 | 33 | for(int i=index;i<=n;i++){ 34 | current.add(i); 35 | dfs(subset,i+1,current,n,k); 36 | current.remove(current.size()-1); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /78 Subsets: -------------------------------------------------------------------------------- 1 | 2 | Given a set of distinct integers, nums, return all possible subsets (the power set). 3 | 4 | Note: The solution set must not contain duplicate subsets. 5 | 6 | Example: 7 | 8 | Input: nums = [1,2,3] 9 | Output: 10 | [ 11 | [3], 12 | [1], 13 | [2], 14 | [1,2,3], 15 | [1,3], 16 | [2,3], 17 | [1,2], 18 | [] 19 | ] 20 | 21 | 22 | 23 | 24 | public List> subsets(int[] nums) { 25 | List> subset = new ArrayList(); 26 | dfs(subset,0,nums,new ArrayList()); 27 | return subset; 28 | } 29 | 30 | void dfs( List> subset,int index,int[] nums,List current){ 31 | subset.add(new ArrayList(current)); 32 | for(int i=index;i stack = new Stack(); 14 | 15 | 16 | //width --- left 17 | for(int i=0;i=0;i--){ 34 | 35 | while(!stack.isEmpty() && heights[i]<=heights[stack.peek()]){ 36 | stack.pop(); 37 | } 38 | 39 | if(stack.isEmpty()){ 40 | right[i] = heights.length; 41 | }else{ 42 | right[i] = stack.peek(); 43 | } 44 | 45 | stack.add(i); 46 | } 47 | 48 | int area = 0; 49 | 50 | for(int i=0;i stack = new Stack(); 42 | 43 | for(int i=0;i=0;i--){ 54 | while(!stack.isEmpty() && heights[i]<=heights[stack.peek()]){ 55 | stack.pop(); 56 | } 57 | if(stack.isEmpty())right[i] = heights.length; 58 | else right[i] = stack.peek(); 59 | stack.add(i); 60 | } 61 | int area = 0; 62 | 63 | for(int i=0;i0 && x%10==0)return false; 14 | 15 | int num = 0; 16 | 17 | while(x>num){ 18 | num = num*10+x%10; 19 | x = x/10; 20 | } 21 | 22 | if(x==num || num/10==x)return true; 23 | 24 | 25 | return false; 26 | } 27 | -------------------------------------------------------------------------------- /90 Subsets II: -------------------------------------------------------------------------------- 1 | Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). 2 | 3 | Note: The solution set must not contain duplicate subsets. 4 | 5 | Example: 6 | 7 | Input: [1,2,2] 8 | Output: 9 | [ 10 | [2], 11 | [1], 12 | [1,2,2], 13 | [2,2], 14 | [1,2], 15 | [] 16 | ] 17 | 18 | 19 | 20 | public List> subsetsWithDup(int[] nums) { 21 | Arrays.sort(nums); 22 | List> subset = new ArrayList(); 23 | dfs(subset,0,nums,new ArrayList()); 24 | return subset; 25 | } 26 | 27 | void dfs( List> subset,int index,int[] nums,List current){ 28 | subset.add(new ArrayList(current)); 29 | for(int i=index;iindex && nums[i]==nums[i-1])continue; 31 | current.add(nums[i]); 32 | dfs(subset,i+1,nums, current); 33 | current.remove(current.size()-1); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /91 Decode Ways: -------------------------------------------------------------------------------- 1 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 2 | 3 | 'A' -> 1 4 | 'B' -> 2 5 | ... 6 | 'Z' -> 26 7 | Given a non-empty string containing only digits, determine the total number of ways to decode it. 8 | 9 | Example 1: 10 | 11 | Input: "12" 12 | Output: 2 13 | Explanation: It could be decoded as "AB" (1 2) or "L" (12). 14 | 15 | 16 | public int numDecodings(String s) { 17 | int[] dp = new int[s.length()+1]; //4 18 | dp[0] = 1; 19 | if(s.charAt(0)!='0'){ 20 | dp[1] = 1; 21 | } 22 | 23 | //"1234" 24 | for(int i=2;i<=s.length();i++){ 25 | int firstcut = Integer.valueOf(s.substring(i-1,i)); 26 | int secondcut = Integer.valueOf(s.substring(i-2,i)); 27 | 28 | if(firstcut>0){ 29 | dp[i] = dp[i-1]; 30 | } 31 | 32 | if(secondcut>=10 && secondcut<=26){ 33 | dp[i] = dp[i] + dp[i-2]; 34 | } 35 | } 36 | 37 | return dp[s.length()]; 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /980 Unique Paths III: -------------------------------------------------------------------------------- 1 | 980. Unique Paths III 2 | Hard 3 | 4 | 613 5 | 6 | 62 7 | 8 | Add to List 9 | 10 | Share 11 | On a 2-dimensional grid, there are 4 types of squares: 12 | 13 | 1 represents the starting square. There is exactly one starting square. 14 | 2 represents the ending square. There is exactly one ending square. 15 | 0 represents empty squares we can walk over. 16 | -1 represents obstacles that we cannot walk over. 17 | Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once. 18 | 19 | 20 | 21 | Example 1: 22 | 23 | Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] 24 | Output: 2 25 | Explanation: We have the following two paths: 26 | 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 27 | 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) 28 | 29 | 30 | int Totalpath = 0; 31 | public int uniquePathsIII(int[][] grid) { 32 | int Totalzero = 0; 33 | 34 | for(int i=0;igrid.length-1 || j>grid[0].length-1 || grid[i][j]==-1 || 53 | (grid[i][j]==2 && Totalzero!=0) || grid[i][j]==99)return; 54 | 55 | if(grid[i][j]==2 && Totalzero==0)Totalpath++; 56 | if(grid[i][j]==0)Totalzero--; 57 | 58 | int temp = grid[i][j]; 59 | grid[i][j]=99; 60 | 61 | dfs(grid,i+1,j,Totalzero); 62 | dfs(grid,i-1,j,Totalzero); 63 | dfs(grid,i,j+1,Totalzero); 64 | dfs(grid,i,j-1,Totalzero); 65 | 66 | grid[i][j]=temp; 67 | 68 | } 69 | -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock (Part1+Part2+Part3+Part4) - DP Version: -------------------------------------------------------------------------------- 1 | //Design an algorithm to find the maximum profit. You may complete at most k transactions. 2 | 3 | //You may not engage in multiple transactions at the same time 4 | // (ie, you must sell the stock before you buy again). 5 | 6 | //BUY SELL STOCK PART1 1 TRANS 7 | //BUY SELL STOCK PART2 as many TRANS 8 | //BUY SELL STOCK PART3 2 TRANS 9 | //BUY SELL STOCK PART4 K TRANS 10 | 11 | 12 | static public int maxProfit(int k, int[] prices) { 13 | if(k==0 || prices.length<2)return 0; 14 | if(k>prices.length/2)k = prices.length/2;//4 15 | int[] dp = new int[prices.length]; 16 | 17 | int min = prices[0] , p = 0; 18 | for (int i=0;i A[i][j], or can move to A[i][j+1] if A[i][j+1] > A[i][j]. 6 | 7 | The task is to find and output the longest path length if we start from (0, 0). 8 | 9 | NOTE: 10 | 11 | If there doesn't exist a path return -1. 12 | 13 | public int solve(int[][] A) { 14 | 15 | int[][]dp = new int[A.length][A[0].length]; 16 | dp[0][0] = 1; 17 | 18 | for(int i=1;iA[0][i-1]){ 20 | dp[0][i] = dp[0][i-1]+1; 21 | }else{ 22 | break; 23 | } 24 | } 25 | for(int i=1;iA[i-1][0]){ 27 | dp[i][0] = dp[i-1][0]+1; 28 | }else{ 29 | break; 30 | } 31 | } 32 | 33 | for(int i=1;iA[i-1][j] && dp[i-1][j]!=0){ 36 | 37 | dp[i][j] = dp[i-1][j]+1; 38 | } 39 | 40 | if(A[i][j]>A[i][j-1] && dp[i][j-1]!=0){ 41 | dp[i][j] = Math.max(dp[i][j-1]+1,dp[i][j]); 42 | 43 | } 44 | } 45 | } 46 | 47 | int n = A.length-1; 48 | int m = A[0].length-1; 49 | 50 | if(dp[n][m]==0)return -1; 51 | else return dp[n][m]; 52 | 53 | 54 | } 55 | 56 | -------------------------------------------------------------------------------- /Largest area of rectangle with permutations: -------------------------------------------------------------------------------- 1 | 2 | Given a binary grid A of size N x M consisting of 0's and 1's, find the area of the largest rectangle inside the grid such that all the cells inside the chosen rectangle should have 1 in them. 3 | 4 | You are allowed to permutate the columns matrix i.e. you can arrange each of the column in any order in the final grid. 5 | 6 | Please follow the sample input and explanation for more clarity. 7 | 8 | 9 | public class Solution { 10 | public int solve(int[][] A) { 11 | 12 | //add column height 13 | for(int i=0;i=0;j--){ 32 | area = A[i][j]*width; width++; 33 | maxArea = Math.max(maxArea,area); 34 | } 35 | } 36 | 37 | return maxArea; 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Maximum Size Square Sub-matrix: -------------------------------------------------------------------------------- 1 | Given a 2D binary matrix A of size N x M find the area of maximum size square sub-matrix with all 1's. 2 | 3 | public int solve(int[][] A) { 4 | int ans = 0; 5 | 6 | for(int i=0;i= 1, such that sum of all the elements in submatrix is maximum. 2 | 3 | 4 | ----------------------xxxxxx BRUTE FORCE SOLUTION xxxxxxx------------------------- 5 | 6 | 7 | public int solve(int[][] A, int B) { 8 | 9 | int row = A.length; 10 | int col = A[0].length; 11 | int maxsum = Integer.MIN_VALUE; 12 | int[][] dp = new int[row+1][col+1]; 13 | 14 | 15 | for(int i=1;i=0 && j-B>=0){ 28 | sum = dp[i][j]-dp[i-B][j]-dp[i][j-B]+dp[i-B][j-B]; 29 | maxsum = Math.max(sum,maxsum); 30 | } 31 | } 32 | } 33 | 34 | return maxsum; 35 | } 36 | 37 | 38 | 39 | ----------------------xxxxxx DP SOLUTION xxxxxxx------------------------- 40 | 41 | 42 | public int solve(int[][] A, int B) { 43 | 44 | int row = A.length; 45 | int col = A[0].length; 46 | int maxsum = Integer.MIN_VALUE; 47 | int[][] dp = new int[row+1][col+1]; 48 | 49 | 50 | for(int i=1;i=0 && j-B>=0){ 61 | sum = dp[i][j] - dp[i-B][j]-dp[i][j-B]+ dp[i-B][j-B]; 62 | maxsum = Math.max(sum,maxsum); 63 | } 64 | } 65 | } 66 | return maxsum; 67 | } 68 | -------------------------------------------------------------------------------- /Min Steps in Infinite Grid: -------------------------------------------------------------------------------- 1 | You are given a sequence of points and the order in which you need to cover the points.. Give the minimum number of steps in which you can achieve it. You start from the first point. 2 | 3 | public int coverPoints(int[] A, int[] B) { 4 | 5 | int total = 0; 6 | for(int i=1;i0){ 18 | wood = wood+A[j]-mid; 19 | } 20 | } 21 | if(wood>=(long)B){ 22 | min = mid+1; 23 | //0 5 10 15 24 | ans = Math.max(ans,mid);//15 25 | }else{ 26 | max = mid-1; 27 | } 28 | } 29 | return ans; 30 | } 31 | } 32 | --------------------------------------------------------------------------------