├── 1014. Best Sightseeing Pair ├── 102. Binary Tree Level Order Traversal ├── 1048. Longest String Chain ├── 1071. Greatest Common Divisor of Strings ├── 1074. Number of Submatrices That Sum to Target ├── 1129. Shortest Path with Alternating Colors ├── 114. Flatten Binary Tree to Linked List ├── 1143. Longest Common Subsequence ├── 118. Pascal's Triangle ├── 1192. Critical Connections in a Network ├── 120. Triangle ├── 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 ├── 1235. Maximum Profit in Job Scheduling ├── 1293. Shortest Path in a Grid with Obstacles Elimination ├── 1302. Deepest Leaves Sum ├── 134. Gas Station ├── 1340. Jump Game V ├── 135. Candy ├── 1353. Maximum Number of Events That Can Be Attended ├── 1354. Construct Target Array With Multiple Sums ├── 1365. How Many Numbers Are Smaller Than the Current Number ├── 1383. Maximum Performance of a Team ├── 1423. Maximum Points You Can Obtain from Cards ├── 1480. Running Sum of 1d Array ├── 1498. Number of Subsequences That Satisfy the Given Sum Condition ├── 1510. Stone Game IV ├── 1523. Count Odd Numbers in an Interval Range ├── 1551. Minimum Operations to Make Array Equal ├── 1642. Furthest Building You Can Reach ├── 1696. Jump Game VI ├── 17. Letter Combinations of a Phone Number ├── 1704. Determine if String Halves Are Alike ├── 1751. Maximum Number of Events That Can Be Attended II ├── 1802. Maximum Value at a Given Index in a Bounded Array ├── 1834. Single-Threaded CPU ├── 1871. Jump Game VII ├── 188. Best Time to Buy and Sell Stock IV ├── 19. Remove Nth Node From End of List ├── 1920. Build Array from Permutation ├── 198. House Robber ├── 204. Count Primes ├── 206. Reverse Linked List ├── 209. Minimum Size Subarray Sum ├── 2116. Check if a Parentheses String Can Be Valid ├── 213. House Robber II ├── 2328. Number of Increasing Paths in a Grid ├── 234. Palindrome Linked List ├── 2375. Construct Smallest Number From DI String ├── 25. Reverse Nodes in k-Group ├── 2531. Make Number of Distinct Characters Equal ├── 2657. Find the Prefix Common Array of Two Arrays ├── 2958. Length Of Longest Subarray with at most K Frequency ├── 300. Longest Increasing Subsequence ├── 304. Range Sum Query 2D - Immutable ├── 309. Best Time to Buy and Sell Stock with Cooldown ├── 32. Longest Valid Parentheses ├── 3223. Minimum Length of String After Operations ├── 326. Power of Three ├── 329. Longest Increasing Path in a Matrix ├── 337. House Robber III ├── 34. Find First and Last Position of Element in Sorted Array ├── 341. Flatten Nested List Iterator ├── 377. Combination Sum IV ├── 403. Frog Jump ├── 45. Jump Game II ├── 462. Minimum Moves to Equal Array Elements II ├── 474. Ones and Zeroes ├── 48. Rotate Image ├── 509. Fibonacci Number ├── 51. N-Queens ├── 52. N-Queens II ├── 530. Minimum Absolute Difference in BST ├── 55. Jump Game ├── 554. Brick Wall ├── 583. Delete Operation for Two Strings ├── 589. N-ary Tree Preorder Traversal ├── 600. Non-negative Integers without Consecutive Ones ├── 609. Find Duplicate File in System ├── 617. Merge Two Binary Trees ├── 622. Design Circular Queue ├── 63. Unique Paths II ├── 630. Course Schedule III ├── 65. Valid Number ├── 665. Non-decreasing Array ├── 667. Beautiful Arrangement II ├── 684. Redundant Connection ├── 696. Count Binary Substrings ├── 714. Best Time to Buy and Sell Stock with Transaction Fee ├── 724. Find Pivot Index ├── 745. Prefix and Suffix Search ├── 775. Global and Local Inversions ├── 816. Ambiguous Coordinates ├── 84. Largest Rectangle in Histogram ├── 86. Partition List ├── 862. Shortest Subarray with Sum at Least K ├── 871. Minimum Number of Refueling Stops ├── 890. Find and Replace Pattern ├── 906. Super Palindromes ├── 927. Three Equal Parts ├── 953. Verifying an Alien Dictionary ├── 968. Binary Tree Cameras ├── 970. Powerful Integers └── README.md /1014. Best Sightseeing Pair: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxScoreSightseeingPair(int[] values) { 3 | int result =0; 4 | int max = values[0]; 5 | for(int i=1;i> levelOrder(TreeNode root) { 3 | List> result = new ArrayList<>(); 4 | if(root == null) return result; 5 | 6 | Queue q = new LinkedList<>(); 7 | q.offer(root); 8 | 9 | while(!q.isEmpty()) { 10 | int size = q.size(); 11 | List currLevel = new ArrayList<>(); 12 | while(size-- > 0) { 13 | TreeNode curr = q.poll(); 14 | currLevel.add(curr.val); 15 | if(curr.left != null) q.offer(curr.left); 16 | if(curr.right != null) q.offer(curr.right); 17 | } 18 | result.add(currLevel); 19 | } 20 | return result; 21 | } 22 | } 23 | 24 | class Solution { 25 | List> result; 26 | public List> levelOrder(TreeNode root) { 27 | result = new ArrayList<>(); 28 | if(root ==null) return result; 29 | traverse(root, 0); 30 | return result; 31 | } 32 | 33 | private void traverse(TreeNode node, int level) { 34 | if(node == null) return; 35 | if(result.size() == level){ 36 | result.add(new ArrayList<>()); 37 | } 38 | 39 | result.get(level).add(node.val); 40 | traverse(node.left, level+1); 41 | traverse(node.right, level+1); 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /1048. Longest String Chain: -------------------------------------------------------------------------------- 1 | 2 | //Time : NlogN + N * Length * Length 3 | //Space : O(N*Length) 4 | class Solution { 5 | public int longestStrChain(String[] words) { 6 | //Sort on length 7 | //Time : NlogN 8 | Arrays.sort(words, (a,b) -> a.length()-b.length()); 9 | int res = 0; 10 | Map memo = new HashMap<>(); 11 | 12 | //Iterate on the words 13 | //TIme : N * Length * Length 14 | for(String word : words) { 15 | //Put current word in map with default value. 16 | memo.put(word, 1); 17 | //Time : Length * Length 18 | for(int i = 0; i < word.length(); i++) { 19 | StringBuilder current = new StringBuilder(word); 20 | String next = current.deleteCharAt(i).toString(); //Time : Length 21 | //Check if the value for next is already calculated 22 | if(memo.containsKey(next)) { 23 | //Update the value in map with the maximum possible value 24 | memo.put(word, Math.max(memo.get(word), memo.get(next)+1)); 25 | } 26 | } 27 | 28 | res = Math.max(res, memo.get(word)); 29 | } 30 | 31 | return res; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /1071. Greatest Common Divisor of Strings: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String gcdOfStrings(String str1, String str2) { 3 | if(str2.length()>str1.length()){ 4 | return gcdOfStrings(str2,str1); 5 | } 6 | if(str2.equals(str1)){ 7 | return str1; 8 | } 9 | 10 | if(str1.startsWith(str2)){ 11 | return gcdOfStrings(str1.substring(str2.length()),str2); 12 | } 13 | 14 | return ""; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /1074. Number of Submatrices That Sum to Target: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numSubmatrixSumTarget(int[][] matrix, int target) { 3 | int m = matrix.length,n=matrix[0].length; 4 | 5 | for(int row =0;row map = new HashMap<>(); 17 | map.put(0,1); 18 | int sum=0; 19 | 20 | for(int row=0;row0 ? matrix[row][c1-1] : 0); 22 | count += map.getOrDefault(sum-target,0); 23 | map.put(sum,map.getOrDefault(sum,0)+1); 24 | } 25 | 26 | } 27 | } 28 | 29 | return count; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /1129. Shortest Path with Alternating Colors: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { 3 | List[] adj = new ArrayList[n]; 4 | for(int i=0;i(); 6 | } 7 | for(int[] red:redEdges){ 8 | adj[red[0]].add(new int[]{red[1],0}); 9 | } 10 | for(int[] blue:blueEdges){ 11 | adj[blue[0]].add(new int[]{blue[1],1}); 12 | } 13 | 14 | Queue queue = new LinkedList<>(); 15 | int[] res = new int[n]; 16 | Arrays.fill(res,-1); 17 | res[0]=0; 18 | boolean[][] v = new boolean[n][2]; 19 | 20 | queue.add(new int[]{0,0,-1}); //currentPos,distance,color 21 | 22 | while(queue.size()>0){ 23 | int[] prev = queue.remove(); 24 | List nodes = adj[prev[0]]; 25 | for(int[] next:nodes){ 26 | if(!v[next[0]][next[1]] && next[1]!=prev[2]){ 27 | if(res[next[0]]==-1){ 28 | res[next[0]]=prev[1] + 1; 29 | } 30 | v[next[0]][next[1]] = true; 31 | queue.add(new int[]{next[0],prev[1]+1,next[1]}); 32 | } 33 | } 34 | } 35 | return res; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /114. Flatten Binary Tree to Linked List: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void flatten(TreeNode root) { 3 | if(root == null) return; 4 | 5 | TreeNode tempLeft = root.left; 6 | TreeNode tempRight = root.right; 7 | 8 | root.left = null; 9 | 10 | flatten(tempLeft); 11 | flatten(tempRight); 12 | 13 | root.right = tempLeft; 14 | TreeNode current = root; 15 | while(current.right != null) current = current.right; 16 | current.right = tempRight; 17 | 18 | } 19 | } 20 | 21 | class Solution { 22 | public void flatten(TreeNode root) { 23 | if(root == null) return; 24 | while(root != null){ 25 | if(root.left != null) { 26 | TreeNode left = root.left; 27 | TreeNode current = left; 28 | while(current.right != null) current = current.right; 29 | current.right = root.right; // Morris Traversal main step 30 | root.left =null; 31 | root.right = left; 32 | } 33 | root = root.right; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /1143. Longest Common Subsequence: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestCommonSubsequence(String text1, String text2) { 3 | return helper(text1,text2,0,0); 4 | } 5 | 6 | int helper(String s1,String s2,int index1,int index2){ 7 | if(index1==s1.length() || index2== s2.length()){ 8 | return 0; 9 | } 10 | 11 | if(s1.charAt(index1) == s2.charAt(index2)){ 12 | return 1 + helper(s1,s2,index1+1,index2+1); 13 | } 14 | 15 | return Math.max(helper(s1,s2,index1+1,index2),helper(s1,s2,index1,index2+1)); 16 | } 17 | } 18 | 19 | class Solution { 20 | int[][] dp; 21 | public int longestCommonSubsequence(String text1, String text2) { 22 | dp = new int[text1.length()][text2.length()]; 23 | for(int i=0;i=0){ 37 | return dp[index1][index2]; 38 | } 39 | 40 | if(s1.charAt(index1) == s2.charAt(index2)){ 41 | dp[index1][index2]= 1 + helper(s1,s2,index1+1,index2+1); 42 | } 43 | else{ 44 | dp[index1][index2] = Math.max(helper(s1,s2,index1+1,index2),helper(s1,s2,index1,index2+1)); 45 | } 46 | 47 | return dp[index1][index2]; 48 | } 49 | } 50 | 51 | class Solution { 52 | int[][] dp; 53 | public int longestCommonSubsequence(String text1, String text2) { 54 | dp = new int[text1.length()+1][text2.length()+1]; 55 | for(int i=0;i<=text1.length();i++){ 56 | for(int j=0;j<=text2.length();j++){ 57 | if(i==0 || j==0){ 58 | continue; 59 | } 60 | 61 | if(text1.charAt(i-1)==text2.charAt(j-1)){ 62 | dp[i][j] = 1 + dp[i-1][j-1]; 63 | } 64 | else{ 65 | dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]); 66 | } 67 | } 68 | } 69 | return dp[text1.length()][text2.length()]; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /118. Pascal's Triangle: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> generate(int numRows) { 3 | List> result = new ArrayList<>(); 4 | if(numRows == 0) return result; 5 | 6 | List row = new ArrayList<>(); 7 | row.add(1); 8 | result.add(row); 9 | 10 | List prevRow = row; 11 | 12 | for(int i = 1; i < numRows; i++) { 13 | List currentRow = new ArrayList<>(); 14 | currentRow.add(1); 15 | for(int j = 1; j < i; j++) { 16 | currentRow.add(prevRow.get(j) + prevRow.get(j-1)); 17 | } 18 | currentRow.add(1); 19 | result.add(new ArrayList<>(currentRow)); 20 | prevRow = currentRow; 21 | } 22 | 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /1192. Critical Connections in a Network: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int time =0; 3 | List> result; 4 | public List> criticalConnections(int n, List> connections) { 5 | List[] adj = new ArrayList[n]; 6 | 7 | for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); 8 | 9 | for(List edge:connections){ 10 | int a = edge.get(0); 11 | int b = edge.get(1); 12 | 13 | adj[a].add(b); 14 | adj[b].add(a); 15 | } 16 | 17 | boolean[] visited = new boolean[n]; 18 | int[] timestamp = new int[n]; 19 | result = new ArrayList<>(); 20 | dfs(adj,visited,timestamp,0,-1); 21 | return result; 22 | } 23 | 24 | void dfs(List[] adj,boolean[] visited,int[] timestamp,int vertex, int prev){ 25 | visited[vertex]=true; 26 | timestamp[vertex] = time++; 27 | int currentTimeStamp = timestamp[vertex]; 28 | 29 | 30 | for(int v : adj[vertex]){ 31 | if(v == prev) continue; 32 | 33 | if(!visited[v]) dfs(adj,visited,timestamp,v,vertex); 34 | 35 | timestamp[vertex] = Math.min(timestamp[vertex],timestamp[v]); 36 | 37 | if(currentTimeStamp < timestamp[v]) result.add(Arrays.asList(vertex,v)); 38 | 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /120. Triangle: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumTotal(List> triangle) { 3 | for(int i = 1; i < triangle.size(); i++) { 4 | for(int j = 0; j < triangle.get(i).size(); j++){ 5 | int sum = 0; 6 | if(j == 0) { 7 | sum = triangle.get(i).get(j) + triangle.get(i-1).get(j); 8 | } 9 | else if(j == triangle.get(i).size()-1) { 10 | sum = triangle.get(i).get(j) + triangle.get(i-1).get(triangle.get(i-1).size()-1); 11 | } 12 | else { 13 | int min = Math.min(triangle.get(i-1).get(j), triangle.get(i-1).get(j-1)); 14 | sum = min+ triangle.get(i).get(j); 15 | } 16 | 17 | triangle.get(i).set(j, sum); 18 | } 19 | } 20 | return Collections.min(triangle.get(triangle.size()-1)); 21 | } 22 | } 23 | 24 | class Solution { 25 | public int minimumTotal(List> triangle) { 26 | for(int i = triangle.size()-2; i >= 0; i--) { 27 | for(int j = 0; j < triangle.get(i).size(); j++) { 28 | int min = Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1)); 29 | int sum = min + triangle.get(i).get(j); 30 | triangle.get(i).set(j, sum); 31 | } 32 | } 33 | return triangle.get(0).get(0); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /1209. Remove All Adjacent Duplicates in String II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String removeDuplicates(String s, int k) { 3 | Stack main = new Stack<>(); 4 | 5 | for(char c: s.toCharArray()){ 6 | Stack temp = new Stack<>(); 7 | temp.push(c); 8 | 9 | while(!main.isEmpty() && main.peek()==c){ 10 | temp.push(main.pop()); 11 | } 12 | 13 | if(temp.size()!=k){ 14 | while(!temp.isEmpty()){ 15 | main.push(temp.pop()); 16 | } 17 | } 18 | } 19 | 20 | StringBuilder sb= new StringBuilder(); 21 | 22 | while(!main.isEmpty()){ 23 | sb.append(main.pop()); 24 | } 25 | 26 | return sb.reverse().toString(); 27 | } 28 | } 29 | 30 | class Solution { 31 | public String removeDuplicates(String s, int k) { 32 | Stack main = new Stack<>(); 33 | 34 | for(char c: s.toCharArray()){ 35 | if(!main.isEmpty() && main.peek()[0] == c){ 36 | main.peek()[1]++; 37 | } 38 | else{ 39 | main.push(new int[]{c,1}); 40 | } 41 | 42 | if(main.peek()[1]==k){ 43 | main.pop(); 44 | } 45 | } 46 | 47 | StringBuilder sb= new StringBuilder(); 48 | 49 | while(!main.isEmpty()){ 50 | int[] top = main.pop(); 51 | 52 | while(top[1]-->0) 53 | sb.append((char) top[0]); 54 | } 55 | 56 | return sb.reverse().toString(); 57 | } 58 | } 59 | 60 | class Solution { 61 | public String removeDuplicates(String s, int k) { 62 | int count = 1; 63 | for(int i=1;i= 0; i--) { 11 | right[i] = Math.max(right[i+1], prices[i]); 12 | } 13 | int max = 0; 14 | for(int i = 0; i < prices.length; i++) { 15 | max = Math.max(max, right[i]-left[i]); 16 | } 17 | return max; 18 | } 19 | } 20 | 21 | class Solution { 22 | public int maxProfit(int[] prices) { 23 | 24 | int minPrice = Integer.MAX_VALUE; 25 | int maxProfit = 0; 26 | for(int i = 0; i < prices.length; i++) { 27 | if(prices[i] < minPrice) 28 | minPrice = prices[i]; 29 | maxProfit = Math.max(prices[i] - minPrice, maxProfit); 30 | } 31 | 32 | return maxProfit; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /122. Best Time to Buy and Sell Stock II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | int n = prices.length; 4 | int profit = 0; 5 | 6 | //Start with index 1 and compare the price 7 | //with previous day price to calculate profit if any 8 | 9 | for(int i = 1; i < n; i++) { 10 | if(prices[i] > prices[i-1]) 11 | profit += (prices[i] - prices[i-1]); 12 | } 13 | 14 | return profit; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /123. Best Time to Buy and Sell Stock III: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | 4 | int n = prices.length; 5 | 6 | if(n==0) return 0; 7 | 8 | int[] left = new int[n]; 9 | int[] right = new int[n]; 10 | 11 | //Bidirectional DP Logic 12 | //Left to right traversal 13 | int min = prices[0]; 14 | for(int i = 1; i < n; i++) { 15 | //1. Update Buy price 16 | if(prices[i] < min) min=prices[i]; 17 | //2. Calculate current profit 18 | int profit = prices[i]-min; 19 | //3. Fill left array (based on condition) 20 | left[i] = Math.max(left[i-1], profit); 21 | } 22 | 23 | 24 | //Right to left traversal 25 | int max = prices[n-1]; 26 | for(int i = n-2; i>=0; i--) { 27 | //1. Update Sell price 28 | if(prices[i] > max) max=prices[i]; 29 | //2. Calculate current profit 30 | int profit = max-prices[i]; 31 | //3. Update right array 32 | right[i] = Math.max(right[i+1], profit); 33 | } 34 | 35 | int maxProfit = 0; 36 | for(int i = 0; i a[1] - b[1]); 10 | 11 | TreeMap dp = new TreeMap<>(); 12 | dp.put(0,0); 13 | 14 | for(int[] job:jobs){ 15 | int val = job[2] + dp.floorEntry(job[0]).getValue(); 16 | if(val>dp.lastEntry().getValue()){ 17 | dp.put(job[1],val); 18 | } 19 | } 20 | 21 | return dp.lastEntry().getValue(); 22 | } 23 | } 24 | 25 | // Video Link: https://www.youtube.com/watch?v=3kU7VYcmffU&list=PLJtzaiEpVo2zkt8tV1eZlq8PFfrS4D3UE&index=1&pp=sAQB 26 | -------------------------------------------------------------------------------- /1293. Shortest Path in a Grid with Obstacles Elimination: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int shortestPath(int[][] grid, int k) { 3 | 4 | int m = grid.length, n = grid[0].length; 5 | int[][] DIR = {{0,1}, {1,0}, {0,-1}, {-1,0}}; 6 | boolean[][][] v = new boolean[m][n][k+1]; 7 | Queue q = new LinkedList<>(); 8 | int steps = 0; 9 | q.offer(new int[]{0,0,k}); 10 | 11 | while(!q.isEmpty()) { 12 | int size = q.size(); 13 | 14 | while(size-- > 0) { 15 | int[] curr = q.poll(); 16 | //If curr is the destination; return steps 17 | if(curr[0] == m-1 && curr[1] == n-1) return steps; 18 | //Else go in all valid directions 19 | for(int[] d : DIR) { 20 | int i = curr[0]+d[0]; 21 | int j = curr[1]+d[1]; 22 | int obs = curr[2]; 23 | 24 | //Traverse through the valid cells 25 | if(i >= 0 && i < m && j >= 0 && j < n) { 26 | //If cell is empty visit the cell and add in queue 27 | if(grid[i][j] == 0 && !v[i][j][obs]) { 28 | q.offer(new int[]{i,j,obs}); 29 | v[i][j][obs] = true; 30 | } 31 | else if(grid[i][j] == 1 && obs > 0 && !v[i][j][obs-1]) { 32 | q.offer(new int[]{i,j,obs-1}); 33 | v[i][j][obs-1] = true; 34 | } 35 | } 36 | } 37 | } 38 | ++steps; 39 | } 40 | return -1; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /1302. Deepest Leaves Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int sum = 0; 3 | public int deepestLeavesSum(TreeNode root) { 4 | int maxDepth = maxDepth(root); 5 | findSum(root, 1, maxDepth); 6 | return sum; 7 | } 8 | 9 | public int maxDepth(TreeNode node) { 10 | if(node == null) return 0; 11 | return 1 + Math.max(maxDepth(node.left), maxDepth(node.right)); 12 | } 13 | 14 | public void findSum(TreeNode node, int curr, int depth) { 15 | if(node != null) { 16 | if(curr == depth) { 17 | sum+=node.val; 18 | } 19 | findSum(node.left, curr+1, depth); 20 | findSum(node.right, curr+1, depth); 21 | } 22 | } 23 | } 24 | 25 | 26 | class Solution { 27 | int sum = 0; 28 | int maxDepth = 0; 29 | public int deepestLeavesSum(TreeNode root) { 30 | findSum(root, 1); 31 | return sum; 32 | } 33 | 34 | 35 | public void findSum(TreeNode node, int curr) { 36 | if(node != null) { 37 | if(curr > maxDepth) { 38 | sum = 0; 39 | maxDepth = curr; 40 | } 41 | if(curr == maxDepth) { 42 | sum+=node.val; 43 | } 44 | findSum(node.left, curr+1); 45 | findSum(node.right, curr+1); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /134. Gas Station: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int canCompleteCircuit(int[] gas, int[] cost) { 3 | int position =0 , sum =0 , total =0; 4 | 5 | for(int index=0;index=0?position:-1; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /1340. Jump Game V: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | int[] dp; 4 | public int maxJumps(int[] arr, int d) { 5 | int max = 0; 6 | dp = new int[arr.length]; 7 | for(int i = 0;i0){ 17 | return dp[index]; 18 | } 19 | 20 | int result = 1; 21 | //index - 1 ----- index - d 22 | for(int j = index - 1; j>= Math.max(index - d,0) && arr[index]>arr[j]; j--){ 23 | result = Math.max(result, 1 + helper(arr,d,j)); 24 | } 25 | 26 | //index + 1 ------- index + d 27 | for(int j = index + 1; j<= Math.min(index + d,arr.length-1) && arr[index]>arr[j] ; j++){ 28 | result = Math.max(result, 1 + helper(arr,d,j)); 29 | } 30 | 31 | dp[index] = result; 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /135. Candy: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int candy(int[] ratings) { 3 | int candies = 0, n = ratings.length; 4 | int[] left = new int[n]; 5 | int[] right = new int[n]; 6 | 7 | Arrays.fill(left, 1); 8 | Arrays.fill(right, 1); 9 | 10 | //Left relative array 11 | for(int i = 1; i < n; i++) { 12 | //If current index rating > previous ; give extra candies 13 | if(ratings[i] > ratings[i-1]) left[i] = left[i-1] + 1; 14 | } 15 | 16 | //Right relative array 17 | for(int i = n-2; i >= 0; i--) { 18 | if(ratings[i] > ratings[i+1]) right[i] = right[i+1] +1; 19 | } 20 | 21 | //Merge both the sides 22 | for(int i = 0; i < n; i++) { 23 | candies = candies + Math.max(left[i], right[i]); 24 | } 25 | 26 | return candies; 27 | } 28 | } 29 | 30 | 31 | class Solution { 32 | public int candy(int[] ratings) { 33 | int[] candies = new int[ratings.length]; 34 | Arrays.fill(candies, 1); 35 | 36 | for(int i = 1; i < ratings.length; i++) { 37 | if(ratings[i] > ratings[i - 1]) 38 | candies[i] = candies[i - 1] + 1; 39 | } 40 | for(int i = ratings.length - 2; i >= 0; i--) { 41 | if(ratings[i] > ratings[i + 1]) 42 | candies[i] = Math.max(candies[i], candies[i+1] +1); 43 | } 44 | int total = 0; 45 | for(int candy : candies) 46 | total+=candy; 47 | 48 | return total; 49 | } 50 | } 51 | 52 | class Solution { 53 | public int candy(int[] ratings) { 54 | if(ratings.length <= 1) return ratings.length; 55 | int candies = 0; 56 | int up = 0, down = 0; 57 | int prevSlope = 0; 58 | 59 | for(int i = 1; i < ratings.length; i++) { 60 | //If increasing then 1; if decreasing then -1; if equal then 0. 61 | int currSlope = (ratings[i] > ratings[i-1]) ? 1 62 | : (ratings[i] < ratings[i-1] ? -1 : 0); 63 | // _ 64 | //If mountain is changing. \_ || \/ || / 65 | if((prevSlope < 0 && currSlope >= 0) || (prevSlope > 0 && currSlope == 0)) { 66 | candies = candies + sum(up) + sum(down) + (Math.max(up, down)); 67 | System.out.println(up + " "+ down + " " +candies); 68 | up = 0; 69 | down = 0; 70 | } 71 | 72 | //Add in up/down if slope is increasing or decreasing respectively. 73 | //If it is a plain, add a candy as it is the base case. 74 | if(currSlope > 0) { 75 | up++; 76 | } 77 | else if(currSlope < 0) { 78 | down++; 79 | } 80 | else { 81 | candies++; 82 | } 83 | 84 | prevSlope = currSlope; 85 | } 86 | System.out.println(up + " "+ down + " "+ candies); 87 | candies = candies + sum(up) + sum(down) + (Math.max(up, down) + 1); 88 | return candies; 89 | } 90 | 91 | int sum(int n) { 92 | return (n * (n + 1)) / 2; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /1353. Maximum Number of Events That Can Be Attended: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxEvents(int[][] events) { 3 | Arrays.sort(events,(a,b)->a[0]-b[0]); 4 | 5 | int day=0,index=0,n=events.length,result=0; 6 | 7 | PriorityQueue pq = new PriorityQueue<>(); 8 | 9 | while(!pq.isEmpty() || indextarget[max] || diff == 0 || target[max]%diff==0) return false; 19 | 20 | target[max] %= diff; 21 | 22 | return isPossible(target); 23 | } 24 | } 25 | 26 | //TC O(n*logN) SC O(N) 27 | class Solution { 28 | public boolean isPossible(int[] target) { 29 | long sum =0; 30 | 31 | PriorityQueue pq=new PriorityQueue((a,b)->b-a); 32 | 33 | for(int i=0;ivalue || diff == 0 || value%diff==0) return false; 45 | 46 | value %= diff; 47 | sum = diff + value; 48 | pq.offer(value); 49 | } 50 | return true; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /1365. How Many Numbers Are Smaller Than the Current Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] smallerNumbersThanCurrent(int[] nums) { 3 | int[] result = nums.clone(); 4 | Arrays.sort(result); 5 | Map index = new HashMap<>(); 6 | for(int i=0;i b[0]-a[0]); 12 | 13 | PriorityQueue speed = new PriorityQueue<>(); 14 | 15 | long speedSum = 0, maxPerformance = 0; 16 | 17 | for(int[] p : pair) { 18 | speedSum+=p[1]; 19 | speed.offer(p[1]); 20 | if(speed.size() > k) { 21 | speedSum-=speed.poll(); 22 | } 23 | maxPerformance = Math.max(maxPerformance, speedSum*p[0]); 24 | } 25 | 26 | return (int)(maxPerformance%MOD); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /1423. Maximum Points You Can Obtain from Cards: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxScore(int[] cardPoints, int k) { 3 | int sum=0; 4 | for(int i:cardPoints){ 5 | sum+=i; 6 | } 7 | 8 | int ans =0, window =0; 9 | int n = cardPoints.length; 10 | 11 | if(n==k) return sum; 12 | 13 | for(int i=0;i=left){ 16 | result += power[right - left]; 17 | result %= mod; 18 | } 19 | } 20 | 21 | return result; 22 | } 23 | 24 | private int binarySearch(int[] nums, int value){ 25 | int low = 0, high = nums.length - 1; 26 | while(low<=high){ 27 | int mid = low + (high - low)/2; 28 | if(nums[mid]<=value){ 29 | low = mid + 1; 30 | } 31 | else{ 32 | high = mid - 1; 33 | } 34 | } 35 | return low; 36 | } 37 | } 38 | 39 | class Solution { 40 | public int numSubseq(int[] nums, int target) { 41 | Arrays.sort(nums); 42 | int mod = 1_000_000_007; 43 | int result =0; 44 | int n = nums.length; 45 | int[] power = new int[n]; 46 | power[0] = 1; 47 | for(int i=1;i pq = new PriorityQueue<>(); 4 | for(int i = 1; i < heights.length; i++) { 5 | int diff = heights[i] - heights[i-1]; 6 | if(diff > 0) { 7 | if(pq.size() < ladders) { 8 | pq.offer(diff); 9 | } 10 | else { 11 | int br = diff; 12 | //Optimize previous ladder use 13 | if(pq.size() > 0 && pq.peek() < diff) { 14 | br = pq.remove(); 15 | pq.offer(diff); 16 | } 17 | if(bricks-br >= 0) { 18 | bricks-=br; 19 | } 20 | else { 21 | return i-1; 22 | } 23 | } 24 | } 25 | } 26 | 27 | return heights.length-1; 28 | } 29 | } 30 | 31 | class Solution { 32 | public int furthestBuilding(int[] heights, int bricks, int ladders) { 33 | int n=heights.length; 34 | PriorityQueue q= new PriorityQueue<>(); 35 | int brickesUsed=0; 36 | for(int i=1;i0){ 39 | q.add(diff); 40 | if(q.size()>ladders){ 41 | brickesUsed+=q.remove(); 42 | } 43 | 44 | if(brickesUsed>bricks){ 45 | return i-1; 46 | } 47 | } 48 | } 49 | return n-1; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /1696. Jump Game VI: -------------------------------------------------------------------------------- 1 | TC: O(NLogK) 2 | SC: O(K) 3 | 4 | class Solution { 5 | public int maxResult(int[] nums, int k) { 6 | /** 7 | For every index starting from 1: --- n 8 | Find out the max sum from all { i -1 } to { i –k } index -- klogk 9 | sum[index] = value[index] + maxfound 10 | Result is sum[length -1] 11 | 12 | */ 13 | 14 | int n = nums.length; 15 | int max = nums[0]; 16 | 17 | // index --- maxSum 18 | PriorityQueue pq = new PriorityQueue<>((a,b) -> b[1]-a[1]); 19 | 20 | pq.offer(new int[]{0,nums[0]}); 21 | 22 | for(int i=1;ik){ 25 | pq.poll(); 26 | } 27 | 28 | int[] top = pq.peek(); 29 | 30 | max = nums[i] + top[1]; 31 | 32 | pq.offer(new int[]{i,max}); 33 | 34 | } 35 | 36 | return max; 37 | } 38 | } 39 | 40 | TC: O(N) 41 | SC: O(K) 42 | 43 | class Solution { 44 | public int maxResult(int[] nums, int k) { 45 | int n = nums.length; 46 | 47 | Deque dq = new ArrayDeque<>(); 48 | 49 | dq.offerLast(0); 50 | 51 | for(int i=1;i=nums[dq.peekLast()]){ 56 | dq.pollLast(); 57 | } 58 | 59 | dq.offerLast(i); 60 | 61 | if(i - dq.peekFirst() >=k){ 62 | dq.pollFirst(); 63 | } 64 | 65 | } 66 | return nums[n-1]; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /17. Letter Combinations of a Phone Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | List result=null; 3 | String[] mapping = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 4 | public List letterCombinations(String digits) { 5 | result = new ArrayList<>(); 6 | if(digits.length()==0) return result; 7 | dfs(0,digits,new StringBuilder()); 8 | return result; 9 | } 10 | 11 | void dfs(int length,String digits,StringBuilder temp){ 12 | if(length == digits.length()){ 13 | result.add(temp.toString()); 14 | return; 15 | } 16 | 17 | //loop digit present at length index of digits string; 18 | char ch= digits.charAt(length); 19 | String str = mapping[ch-'0']; 20 | for(char c:str.toCharArray()){ 21 | temp.append(c); 22 | dfs(length+1,digits,temp); 23 | temp.deleteCharAt(temp.length()-1); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /1704. Determine if String Halves Are Alike: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean halvesAreAlike(String s) { 3 | char[] ch = s.toCharArray(); 4 | int left=0,right=ch.length-1; 5 | 6 | int lcount=0,rcount=0; 7 | Set vowels=Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'); 8 | 9 | while(left a[0]==b[0]?a[1]-b[1]:a[0]-b[0]); 17 | 18 | return helper(events,0,k,n); //o(N*K) * O(logN) 19 | } 20 | 21 | int helper(int[][] events,int pos,int k,int n){ 22 | if(pos>=n || k==0){ 23 | return 0; 24 | } 25 | 26 | if(dp[pos][k]>-1){ 27 | return dp[pos][k]; 28 | } 29 | 30 | int nextPos = nextEvent(events,pos,n); // O(logN) 31 | int select = events[pos][2] + helper(events,nextPos,k-1,n); 32 | int reject = helper(events,pos+1,k,n); 33 | dp[pos][k]= Math.max(select,reject); 34 | return dp[pos][k]; 35 | } 36 | 37 | int nextEvent(int[][] events,int pos, int n){ 38 | int endDay = events[pos][1]; 39 | pos++; 40 | while(posendDay){ 43 | n =mid; 44 | } 45 | else{ 46 | pos = mid+1; 47 | } 48 | } 49 | return n; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /1802. Maximum Value at a Given Index in a Bounded Array: -------------------------------------------------------------------------------- 1 | //Bruteforce - O(Steps OR Result)/ O(1) 2 | class Solution { 3 | public int maxValue(int n, int index, int maxSum) { 4 | int res = 1; 5 | maxSum -= n; 6 | int left = 0, right = 0; 7 | int maxLeft = index, maxRight = n - index - 1; 8 | 9 | while(maxSum > 0) { 10 | res++; 11 | int leftVal = Math.min(left++, maxLeft); 12 | int rightVal = Math.min(right++, maxRight); 13 | maxSum -= (1 + leftVal + rightVal); 14 | } 15 | return (maxSum<0) ? res-1 : res; 16 | } 17 | } 18 | 19 | 20 | //Optimized - O(N)/O(1) 21 | class Solution { 22 | public int maxValue(int n, int index, int maxSum) { 23 | int res = 1; 24 | maxSum -= n; 25 | int left = 0, right = 0; 26 | int maxLeft = index, maxRight = n - index - 1; 27 | 28 | while(maxSum > 0) { 29 | res++; 30 | int leftVal = Math.min(left++, maxLeft); 31 | int rightVal = Math.min(right++, maxRight); 32 | maxSum -= (1 + leftVal + rightVal); 33 | 34 | if(leftVal == maxLeft && rightVal == maxRight) { 35 | break; 36 | } 37 | } 38 | 39 | if(maxSum > 0){ 40 | res = res + (maxSum/n); 41 | } 42 | 43 | return (maxSum<0) ? res-1 : res; 44 | } 45 | } 46 | 47 | //Binary Search 48 | 49 | class Solution { 50 | public int maxValue(int n, int index, int maxSum) { 51 | //Binary Search code 52 | if(n == 1) return maxSum; 53 | 54 | int left = 1, right = maxSum; 55 | while(left < right) { 56 | int mid = left + (right-left)/2; 57 | long sum = calculateSumOfArray(mid, index, n); 58 | 59 | if(sum <= maxSum) { 60 | left = mid+1; 61 | } 62 | else { 63 | right = mid; 64 | } 65 | } 66 | 67 | return left-1; 68 | } 69 | 70 | //Calculate the Sum of array 71 | private long calculateSumOfArray(int v, int i, int n){ 72 | long sum = 0; 73 | if(v <= i){ 74 | int a = i+1-v; 75 | sum+=summation(v-1) + a; 76 | } 77 | else { 78 | int x = v-i; 79 | sum+= summation(v-1) - summation(x-1); 80 | } 81 | 82 | 83 | if(v <= n-i){ 84 | int b = n-i-v; 85 | sum+=summation(v-1) + b; 86 | } 87 | else { 88 | int y = v-(n-i-1); 89 | sum+= summation(v-1) - summation(y-1); 90 | } 91 | 92 | return sum+v; 93 | 94 | } 95 | 96 | //Utility method to apply summation formula 97 | private long summation(int n) { 98 | return (long)(n+1)*n/2; 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /1834. Single-Threaded CPU: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] getOrder(int[][] tasks) { 3 | //How to store the tasks 4 | //Task(index, startTime, processingTime) 5 | //Sort : StartTime ==> processingTime 6 | 7 | int n = tasks.length; 8 | Task[] t = new Task[n]; 9 | for(int i = 0; i < n; i++) { 10 | t[i] = new Task(i, tasks[i][0], tasks[i][1]); 11 | } 12 | 13 | Arrays.sort(t, (a,b) -> a.startTime == b.startTime ? a.processingTime- b.processingTime : a.startTime - b.startTime); 14 | 15 | 16 | //How to pick the task 17 | //Priority Queue 18 | //Sorting => ProcessingTime (asc) ==> index (asc) 19 | 20 | PriorityQueue waitingTasks = new PriorityQueue<>((a,b) -> a.processingTime == b.processingTime ? a.index-b.index : a.processingTime - b.processingTime); 21 | 22 | int[] result = new int[n]; 23 | int index = 0, resIndex = 0; 24 | int endTime = 0; 25 | 26 | while(index < n) { 27 | if(waitingTasks.size() > 0) { 28 | //Calculate new EndTime and process one task 29 | //Pick the next Task, calculte the new endTime, Fill the waitingTasks Queue 30 | Task currentTask = waitingTasks.remove(); 31 | endTime = Math.max(currentTask.startTime, endTime) + currentTask.processingTime; 32 | result[resIndex++] = currentTask.index; 33 | 34 | while(index < n && endTime >= t[index].startTime) { 35 | waitingTasks.add(t[index++]); 36 | } 37 | } 38 | else { 39 | //Add a task in waitingTasks List 40 | waitingTasks.add(t[index++]); 41 | } 42 | } 43 | 44 | while(waitingTasks.size() > 0) { 45 | Task task = waitingTasks.remove(); 46 | result[resIndex++] = task.index; 47 | } 48 | 49 | return result; 50 | } 51 | 52 | class Task { 53 | int index; 54 | int startTime; 55 | int processingTime; 56 | 57 | Task(int index, int startTime, int processingTime) { 58 | this.index = index; 59 | this.startTime= startTime; 60 | this.processingTime = processingTime; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /1871. Jump Game VII: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canReach(String s, int minJump, int maxJump) { 3 | int n = s.length(); 4 | boolean[] dp = new boolean[n]; 5 | char[] ch = s.toCharArray(); 6 | 7 | dp[0] = ch[0]=='0'; 8 | 9 | int reachable = 0; 10 | 11 | for(int i = 1;i=minJump){ 14 | reachable += dp[i-minJump]? 1 : 0; 15 | } 16 | 17 | if(i>maxJump){ 18 | reachable -= dp[i-maxJump-1]? 1 : 0; 19 | } 20 | 21 | dp[i] = reachable>0 && ch[i] == '0'; 22 | } 23 | 24 | return dp[n-1]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /188. Best Time to Buy and Sell Stock IV: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int k, int[] prices) { 3 | 4 | int n = prices.length; 5 | int[][] dp = new int[k+1][n]; 6 | 7 | if(n < 2) return 0; 8 | 9 | for(int i = 1; i <= k; i++) { 10 | for(int j = 1; j < n; j++) { 11 | dp[i][j] = Math.max(dp[i][j-1], helper(i, j, prices, dp)); 12 | } 13 | } 14 | 15 | return dp[k][n-1]; 16 | 17 | } 18 | 19 | private int helper(int k, int x, int[] prices, int[][] dp){ 20 | int max = 0; 21 | for(int i = 0; i < x; i++) { 22 | //Sell on day_x, buy on day_i and add profit from (i-1) transsactions dp[k-1][i] 23 | max = Math.max(max, prices[x]-prices[i] + dp[k-1][i]); 24 | } 25 | return max; 26 | } 27 | } 28 | 29 | 30 | 31 | class Solution { 32 | public int maxProfit(int k, int[] prices) { 33 | 34 | int n = prices.length; 35 | int[][] dp = new int[k+1][n]; //Space : O(KN) 36 | 37 | if(n < 2) return 0; 38 | 39 | //Time O(K*N) 40 | for(int i = 1; i <= k; i++) { 41 | int effectiveBuyPrice = prices[0]; 42 | for(int j = 1; j < n; j++) { 43 | //Profit by selling on current price (j) 44 | // Profit = SP-EBP 45 | // SP => price[j] 46 | // BP => Effective Buy Price -> price[j] - previous profit (dp[k-1][j]) 47 | dp[i][j] = Math.max(dp[i][j-1], prices[j] - effectiveBuyPrice); 48 | effectiveBuyPrice = Math.min(effectiveBuyPrice, prices[j] - dp[i-1][j]); 49 | } 50 | } 51 | return dp[k][n-1]; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /19. Remove Nth Node From End of List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode removeNthFromEnd(ListNode head, int n) { 13 | ListNode dummy =new ListNode(0); 14 | dummy.next = head; 15 | ListNode current = dummy, nth = dummy; 16 | 17 | for(int i=1;i<=n+1;i++){ 18 | current = current.next; 19 | } 20 | 21 | while(current!=null){ 22 | current = current.next; 23 | nth = nth.next; 24 | } 25 | 26 | nth.next = nth.next.next; 27 | 28 | return dummy.next; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /1920. Build Array from Permutation: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] buildArray(int[] nums) { 3 | int CONST = 1001; 4 | 5 | for(int i = 0; i < nums.length; i++) { 6 | int a = nums[i]; 7 | int b = nums[a]%CONST; 8 | nums[i] = a + b*CONST; 9 | } 10 | 11 | for(int i = 0; i < nums.length; i++) { 12 | nums[i] /= CONST; 13 | } 14 | 15 | return nums; 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /198. House Robber: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rob(int[] nums) { 3 | int[] dp = new int[nums.length]; 4 | dp[0]=nums[0]; 5 | if(nums.length==1) return nums[0]; 6 | if(nums.length==2) return Math.max(nums[0],nums[1]); 7 | dp[1] = Math.max(nums[0],nums[1]); 8 | 9 | for(int index=2;index True represent composite and False represents primes 7 | for(int i = 2; i <= limit; i++){ 8 | if(composites[i] == false) { 9 | //Mark all the multiples of i as true. 10 | //The first index to be flipped to true, is i*i 11 | for(int j = i*i; j < n; j+=i){ 12 | composites[j] = true; 13 | } 14 | } 15 | } 16 | 17 | int count = 0; 18 | for(int i = 2; i < n; i++) { 19 | if(composites[i] == false) count++; 20 | } 21 | 22 | return count; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /206. Reverse Linked List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | 12 | class Solution { 13 | public ListNode reverseList(ListNode head) { 14 | if(head==null || head.next==null) return head; 15 | ListNode newHead = reverseList(head.next); 16 | head.next.next = head; 17 | head.next = null; 18 | return newHead; 19 | } 20 | } 21 | 22 | 23 | class Solution { 24 | public ListNode reverseList(ListNode head) { 25 | ListNode prev=null,curr=head; 26 | while(curr!=null){ 27 | ListNode next = curr.next; 28 | curr.next=prev; 29 | prev=curr; 30 | curr=next; 31 | } 32 | return prev; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /209. Minimum Size Subarray Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSubArrayLen(int target, int[] nums) { 3 | int currSum = 0, window = Integer.MAX_VALUE; 4 | int start = 0, end = 0; 5 | 6 | for(end = 0; end < nums.length; end++){ 7 | currSum += nums[end]; 8 | while(currSum >= target){ 9 | window = Math.min(window, end-start+1); 10 | currSum -= nums[start]; 11 | start++; 12 | } 13 | } 14 | 15 | return window == Integer.MAX_VALUE ? 0 : window; 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /2116. Check if a Parentheses String Can Be Valid: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canBeValid(String s, String locked) { 3 | if(s.length()%2!=0) return false; 4 | Stack unlocked = new Stack<>(); 5 | Stack open = new Stack<>(); 6 | char[] stArray = s.toCharArray(); 7 | char[] lArray = locked.toCharArray(); 8 | 9 | for(int i=0;i0){ 18 | open.pop(); 19 | } 20 | else if(unlocked.size()>0){ 21 | unlocked.pop(); 22 | } 23 | else{ 24 | return false; 25 | } 26 | } 27 | } 28 | 29 | while(open.size()>0 && unlocked.size()>0 && open.peek()=m || sj>=n || grid[si][sj]<=prev){ 21 | return 0; 22 | } 23 | if(dp[si][sj]>0) return dp[si][sj]; 24 | int path = 1; 25 | for(int[] d:dir){ 26 | path += dfs(grid,si+d[0],sj+d[1],grid[si][sj]); 27 | } 28 | 29 | path%=mod; 30 | dp[si][sj] = path; 31 | return path; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /234. Palindrome Linked List: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(ListNode head) { 3 | if(head == null || head.next == null) return true; 4 | List l = new ArrayList<>(); 5 | while(head != null){ 6 | l.add(head.val); 7 | head = head.next; 8 | } 9 | int start = 0, end = l.size()-1; 10 | while(start < end){ 11 | if(l.get(start) != l.get(end)) return false; 12 | start++;end--; 13 | } 14 | return true; 15 | } 16 | } 17 | 18 | class Solution { 19 | public boolean isPalindrome(ListNode head) { 20 | //Find Mid 21 | ListNode fast = head; 22 | ListNode slow = head; 23 | 24 | while(fast.next != null && fast.next.next != null) { 25 | slow = slow.next; 26 | fast = fast.next.next; 27 | } 28 | 29 | // 1, ||| 2. |||| 3 --> slow = 2, fast = 3 30 | if(fast != null) slow = slow.next; 31 | 32 | //Reverse the list start from slow. 33 | ListNode revHead = reverse(slow); 34 | 35 | while(revHead != null) { 36 | if(revHead.val != head.val) return false; 37 | else { 38 | revHead = revHead.next; 39 | head = head.next; 40 | } 41 | } 42 | return true; 43 | } 44 | 45 | public ListNode reverse(ListNode head) { 46 | ListNode prev = null; 47 | while(head != null) { 48 | ListNode next = head.next; 49 | head.next = prev; 50 | prev = head; 51 | head = next; 52 | } 53 | return prev; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /2375. Construct Smallest Number From DI String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String smallestNumber(String pattern) { 3 | int size = pattern.length(); 4 | int[] ans = new int[size+1]; 5 | for(int i=0;i 0){ 32 | ListNode next = second.next; 33 | second.next = first; 34 | first = second; 35 | second = next; 36 | } 37 | count-=k; 38 | temp.next = first; 39 | tempnext.next = second; 40 | temp = tempnext; 41 | 42 | } 43 | return dummy.next; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /2531. Make Number of Distinct Characters Equal: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isItPossible(String word1, String word2) { 3 | int[] occ1 = findOccurance(word1); 4 | int[] occ2 = findOccurance(word2); 5 | 6 | for(int i=0;i<26;i++){ 7 | if(occ1[i]>0){ 8 | for(int j=0;j<26;j++){ 9 | if(occ2[j]>0){ 10 | swap(occ1,occ2,i,j); 11 | if(areDistinctEqual(occ1,occ2)){ 12 | return true; 13 | } 14 | swap(occ1,occ2,j,i); 15 | } 16 | } 17 | } 18 | } 19 | return false; 20 | } 21 | 22 | private boolean areDistinctEqual(int[] occ1,int[] occ2){ 23 | int count=0; 24 | for(int i=0;i<26;i++){ 25 | if(occ1[i]>0) count++; 26 | if(occ2[i]>0) count--; 27 | } 28 | return count==0; 29 | } 30 | 31 | private void swap(int[] occ1,int[] occ2,int i,int j){ 32 | occ1[i]--; 33 | occ2[i]++; 34 | occ1[j]++; 35 | occ2[j]--; 36 | } 37 | 38 | private int[] findOccurance(String word){ 39 | int[] occurance = new int[26]; 40 | for(char c:word.toCharArray()){ 41 | occurance[c-'a']++; 42 | } 43 | return occurance; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /2657. Find the Prefix Common Array of Two Arrays: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findThePrefixCommonArray(int[] A, int[] B) { 3 | int[] c = new int[A.length]; 4 | for(int i=0;i=i){ 11 | c[j]++; 12 | } 13 | } 14 | } 15 | return c; 16 | } 17 | } 18 | 19 | 20 | class Solution { 21 | public int[] findThePrefixCommonArray(int[] A, int[] B) { 22 | int[] c = new int[A.length]; 23 | int[] freq = new int[A.length+1]; 24 | int count=0; 25 | for(int i=0;i freq = new HashMap<>(); 8 | 9 | while(end < nums.length) { 10 | int currentFreq = freq.getOrDefault(nums[end], 0); 11 | 12 | if(currentFreq < k) { 13 | freq.put(nums[end], currentFreq+1); 14 | } 15 | else { 16 | while(nums[start] != nums[end]) { 17 | freq.put(nums[start], freq.get(nums[start])-1); 18 | start++; 19 | } 20 | start++; 21 | } 22 | 23 | int newWindowLength = end-start+1; 24 | result = Math.max(result, newWindowLength); 25 | 26 | end++; 27 | 28 | } 29 | 30 | return result; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /300. Longest Increasing Subsequence: -------------------------------------------------------------------------------- 1 | //Recursion - Brute force (TLE) 2 | 3 | class Solution { 4 | public int lengthOfLIS(int[] nums) { 5 | if(nums.length <= 1) return nums.length; 6 | return lis(nums, 0, -1); 7 | } 8 | 9 | private int lis(int[] nums, int currentInd, int prevInd) { 10 | 11 | if(currentInd == nums.length) return 0; 12 | int skip = lis(nums, currentInd + 1, prevInd); 13 | int select = -1; 14 | if(prevInd == -1 || nums[currentInd] > nums[prevInd]) { 15 | select = 1 + lis(nums, currentInd+1, currentInd); 16 | } 17 | 18 | return Math.max(skip, select); 19 | } 20 | 21 | } 22 | 23 | //Recursion + Memoization 24 | 25 | class Solution { 26 | public int lengthOfLIS(int[] nums) { 27 | int n = nums.length; 28 | if(n <= 1) return n; 29 | 30 | int[][] dp = new int[n][n+1]; 31 | 32 | for(int[] rows : dp) { 33 | Arrays.fill(rows, -1); 34 | } 35 | 36 | return lis(nums, 0, -1, dp); 37 | } 38 | 39 | private int lis(int[] nums, int currentInd, int prevInd, int[][] dp) { 40 | 41 | if(currentInd == nums.length) return 0; 42 | 43 | if(dp[currentInd][prevInd+1] != -1) return dp[currentInd][prevInd+1]; 44 | 45 | int skip = lis(nums, currentInd + 1, prevInd, dp); 46 | int select = -1; 47 | if(prevInd == -1 || nums[currentInd] > nums[prevInd]) { 48 | select = 1 + lis(nums, currentInd+1, currentInd, dp); 49 | } 50 | 51 | dp[currentInd][prevInd+1] = Math.max(skip, select); 52 | 53 | return dp[currentInd][prevInd+1]; 54 | } 55 | 56 | } 57 | 58 | //DP 59 | 60 | class Solution { 61 | public int lengthOfLIS(int[] nums) { 62 | int n = nums.length; 63 | if(n <= 1) return n; 64 | 65 | int[] dp = new int[n]; 66 | 67 | Arrays.fill(dp, 1); 68 | 69 | int maxLength = 0; 70 | 71 | for(int i = 1; i < n; i++) { 72 | for(int j = 0; j < i; j++) { 73 | if(nums[i] > nums[j]) { 74 | dp[i] = Math.max(dp[i], 1+dp[j]); 75 | } 76 | } 77 | maxLength = Math.max(maxLength, dp[i]); 78 | } 79 | 80 | return maxLength; 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /304. Range Sum Query 2D - Immutable: -------------------------------------------------------------------------------- 1 | class NumMatrix { 2 | 3 | int[][] matrix; 4 | public NumMatrix(int[][] matrix) { 5 | for(int i=0;i O(1) 4 | int sold = Integer.MIN_VALUE; 5 | int held = Integer.MIN_VALUE; 6 | int reset = 0; 7 | 8 | //Time -> O(N) 9 | for(int p : prices) { 10 | int prevSold = sold; 11 | sold = held + p; 12 | held = Math.max(held, reset - p); 13 | reset = Math.max(reset, prevSold); 14 | } 15 | 16 | return Math.max(sold, reset); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /32. Longest Valid Parentheses: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestValidParentheses(String s) { 3 | Stack st=new Stack<>(); 4 | st.push(-1); 5 | int max=0; 6 | for(int i=0;i open ){ 49 | open = close = 0; 50 | } 51 | } 52 | 53 | open = close = 0; 54 | // n -- 0 55 | for(int i= s.length()-1; i>=0 ;i--){ 56 | char c = s.charAt(i); 57 | if(c == '('){ 58 | open++; 59 | } 60 | else{ 61 | close++; 62 | } 63 | 64 | if(open == close){ 65 | int len = open + close; 66 | max = Math.max(max,len); 67 | } 68 | else if(open > close ){ 69 | open = close = 0; 70 | } 71 | } 72 | 73 | return max; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /3223. Minimum Length of String After Operations: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumLength(String s) { 3 | char[] ch = s.toCharArray(); 4 | int[] count = new int[26]; 5 | for(char c:ch){ 6 | count[c-'a']++; 7 | } 8 | int result = 0; 9 | for(int ct: count){ 10 | if(ct>0) result+=(ct%2==0?2:1); 11 | } 12 | return result; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /326. Power of Three: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPowerOfThree(int n) { 3 | //27 27/3=9(0) --> 9/3=3(0) --> 3/3=1(0) --> n has reduced to 1 4 | //10 10/3=3(1) --> false (remainder != 0) 5 | 6 | while(n>=3) { 7 | if(n%3 != 0) return false; 8 | n=n/3; 9 | } 10 | return n==1; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /329. Longest Increasing Path in a Matrix: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[][] dir = {{1,0}, {-1,0}, {0,1}, {0,-1}}; 3 | public int longestIncreasingPath(int[][] matrix) { 4 | if(matrix == null || matrix.length == 0) return 0; 5 | int m = matrix.length, n = matrix[0].length; 6 | int[][] mem = new int[m][n]; 7 | int longestPath = 0; 8 | 9 | for(int i = 0; i < m; i++) { 10 | for(int j = 0; j < n; j++) { 11 | int path = dfs(matrix, m, n, i, j, mem); 12 | longestPath = Math.max(path, longestPath); 13 | } 14 | } 15 | 16 | return longestPath; 17 | } 18 | 19 | public int dfs(int[][] matrix, int m, int n, int i, int j, int[][] mem) { 20 | if(mem[i][j] > 0) return mem[i][j]; 21 | int max = 0; 22 | for(int[] d : dir) { 23 | int x = i+d[0], y = j+d[1]; 24 | if(x >= 0 && y >= 0 && x < m && y < n && matrix[x][y] > matrix[i][j]) { 25 | max = Math.max(max, dfs(matrix, m, n, x, y, mem)); 26 | } 27 | } 28 | mem[i][j] = max+1; 29 | return max+1; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /337. House Robber III: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | Map map=new HashMap<>(); 18 | public int rob(TreeNode root) { 19 | if(root==null){ 20 | return 0; 21 | } 22 | if(map.containsKey(root)){ 23 | return map.get(root); 24 | } 25 | 26 | int sum=root.val; 27 | 28 | if(root.left!=null){ 29 | sum+=rob(root.left.left); 30 | sum+=rob(root.left.right); 31 | } 32 | 33 | if(root.right!=null){ 34 | sum+=rob(root.right.left); 35 | sum+=rob(root.right.right); 36 | } 37 | 38 | int next_sum=rob(root.left)+rob(root.right); 39 | 40 | int res=Math.max(sum,next_sum); 41 | map.put(root,res); 42 | return res; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /34. Find First and Last Position of Element in Sorted Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] searchRange(int[] nums, int target) { 3 | int[] res=new int[]{-1,-1}; 4 | if(nums.length==0) return res; 5 | int start=0,end=nums.length-1; 6 | 7 | while(start=target){ 11 | end = mid; 12 | } 13 | else{ 14 | start = mid+1; 15 | } 16 | } 17 | 18 | if(nums[start] != target){ 19 | return res; 20 | } 21 | 22 | res[0] = start; 23 | 24 | end = nums.length; 25 | 26 | while(start target){ 30 | end=mid; 31 | } 32 | else{ 33 | start = mid +1; 34 | } 35 | } 36 | 37 | res[1] = start -1; 38 | 39 | return res; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /341. Flatten Nested List Iterator: -------------------------------------------------------------------------------- 1 | /** 2 | * // This is the interface that allows for creating nested lists. 3 | * // You should not implement it, or speculate about its implementation 4 | * public interface NestedInteger { 5 | * 6 | * // @return true if this NestedInteger holds a single integer, rather than a nested list. 7 | * public boolean isInteger(); 8 | * 9 | * // @return the single integer that this NestedInteger holds, if it holds a single integer 10 | * // Return null if this NestedInteger holds a nested list 11 | * public Integer getInteger(); 12 | * 13 | * // @return the nested list that this NestedInteger holds, if it holds a nested list 14 | * // Return empty list if this NestedInteger holds a single integer 15 | * public List getList(); 16 | * } 17 | */ 18 | public class NestedIterator implements Iterator { 19 | 20 | List flattenList = null; 21 | int current=0; 22 | public NestedIterator(List nestedList) { 23 | flattenList= new ArrayList<>(); 24 | for(NestedInteger integer:nestedList){ 25 | helper(integer); 26 | } 27 | } 28 | 29 | @Override 30 | public Integer next() { 31 | return flattenList.get(current++); 32 | } 33 | 34 | @Override 35 | public boolean hasNext() { 36 | return current-1){ 35 | return dp[target]; 36 | } 37 | int res = 0; 38 | for(int i:nums){ 39 | if(i<=target){ 40 | res+=helper(nums,target - i); 41 | } 42 | } 43 | dp[target]=res; 44 | return dp[target]; 45 | } 46 | } 47 | 48 | \\Bottom-up 49 | class Solution { 50 | 51 | int[] dp ; 52 | public int combinationSum4(int[] nums, int target) { 53 | 54 | dp=new int[target+1]; 55 | 56 | dp[0] =1; 57 | 58 | for(int i = 1 ; i<=target ;i++){ 59 | for(int n:nums){ 60 | if(i>=n){ 61 | dp[i] += dp[i-n]; 62 | } 63 | } 64 | } 65 | 66 | return dp[target]; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /403. Frog Jump: -------------------------------------------------------------------------------- 1 | class Solution { 2 | boolean[][] dp; 3 | public boolean canCross(int[] stones) { 4 | 5 | if(stones[1]!=1) return false; 6 | 7 | int n = stones.length; 8 | dp = new boolean[n][n]; 9 | return helper(stones,0,1); 10 | } 11 | 12 | boolean helper(int[] stones,int lastIndex,int currentIndex){ 13 | if(currentIndex == stones.length - 1){ 14 | return true; 15 | } 16 | 17 | if(dp[lastIndex][currentIndex]) return false; 18 | 19 | int lastJump = stones[currentIndex] - stones[lastIndex]; 20 | 21 | int nextIndex = currentIndex + 1; 22 | 23 | while(nextIndex=-1 && jump<=1){ 28 | if(helper(stones,currentIndex,nextIndex)){ 29 | return true; 30 | } 31 | } 32 | nextIndex++; 33 | } 34 | 35 | dp[lastIndex][currentIndex] = true; 36 | 37 | return false; 38 | } 39 | } 40 | 41 | 42 | class Solution { 43 | Map dp =null; 44 | public boolean canCross(int[] stones) { 45 | if(stones[1]!=1) return false; 46 | dp = new HashMap<>(); 47 | return helper(stones,1,1); 48 | } 49 | 50 | boolean helper(int[] stones, int index,int jump){ 51 | if(index == stones.length - 1){ 52 | return true; 53 | } 54 | if(dp.containsKey(index+"-"+jump)) return dp.get(index+"-"+jump); 55 | boolean ans = false; 56 | for(int j = Math.max(1,jump - 1); j<=jump+1;j++){ 57 | if(j==0) continue; 58 | int newStone = stones[index] + j; 59 | int indexNew = exists(stones,newStone); 60 | if(indexNew!=-1){ 61 | ans |= helper(stones,indexNew,j); 62 | } 63 | } 64 | 65 | dp.put(index+"-"+jump,ans); 66 | 67 | return ans; 68 | } 69 | 70 | int exists(int[] stone,int target){ 71 | int left=0,right = stone.length-1; 72 | while(left<=right){ 73 | int mid = left + (right - left)/2; 74 | if(stone[mid]==target) { 75 | return mid; 76 | } 77 | else if(stone[mid]>target) right = mid-1; 78 | else left = mid+1; 79 | } 80 | 81 | return -1; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /45. Jump Game II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int jump(int[] nums) { 3 | int n =nums.length; 4 | int[] dp = new int[n]; 5 | Arrays.fill(dp,Integer.MAX_VALUE); 6 | dp[n-1]=0; 7 | 8 | for(int i=n-2;i>=0;i--){ 9 | int min = Integer.MAX_VALUE; 10 | for(int j=i+1;j<=Math.min(n-1,i+nums[i]);j++){ 11 | min = Math.min(min,dp[j]); 12 | } 13 | 14 | if(min!=Integer.MAX_VALUE){ 15 | dp[i] = min + 1; 16 | } 17 | } 18 | 19 | return dp[0]; 20 | } 21 | } 22 | 23 | class Solution { 24 | public int jump(int[] nums) { 25 | int begin=0,end=0,farthest=0; 26 | int jump=0; 27 | 28 | for(int i=0;i0){ 15 | return dp[zero][one][index]; 16 | } 17 | 18 | int[] count = count(strs[index]); 19 | 20 | //consider changes the zero ad one 21 | int consider=0; 22 | 23 | if(zero >=count[0] && one>=count[1]){ 24 | consider = 1 + helper(strs,zero-count[0],one-count[1],index+1); 25 | } 26 | 27 | int skip = helper(strs,zero,one,index+1); 28 | 29 | //skip 30 | dp[zero][one][index]=Math.max(consider,skip);; 31 | return dp[zero][one][index]; 32 | 33 | } 34 | 35 | int[] count(String s){ 36 | int[] count=new int[2]; 37 | for(char c: s.toCharArray()){ 38 | count[c-'0']++; 39 | } 40 | return count; 41 | } 42 | } 43 | 44 | class Solution { 45 | 46 | int[][] dp; 47 | public int findMaxForm(String[] strs, int m, int n) { 48 | dp= new int[m+1][n+1]; 49 | 50 | for(String s:strs){ 51 | int[] count = count(s); 52 | //zero m-count[0] ---- 0 53 | //one n - count[1] ---- 0 54 | for(int zero=m;zero>=count[0];zero--){ 55 | for(int one=n; one>=count[1]; one--){ 56 | dp[zero][one] = Math.max(dp[zero-count[0]][one-count[1]] +1 , dp[zero][one]); 57 | } 58 | } 59 | } 60 | 61 | 62 | return dp[m][n]; 63 | } 64 | 65 | int[] count(String s){ 66 | int[] count=new int[2]; 67 | for(char c: s.toCharArray()){ 68 | count[c-'0']++; 69 | } 70 | return count; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /48. Rotate Image: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | int n = matrix.length; 4 | //Transpose 5 | for(int i = 0; i < n; i++) { 6 | for(int j = i; j < n; j++) { 7 | //Swap matrix[i][j] with matrix[j][i] 8 | int temp = matrix[i][j]; 9 | matrix[i][j] = matrix[j][i]; 10 | matrix[j][i] = temp; 11 | } 12 | } 13 | 14 | //Reverse of rows 15 | for(int i = 0; i < n; i++) { 16 | for(int j = 0; j < n/2; j++) { 17 | //Swap matrix[i][j] with matrix[i][n-j-1] 18 | int temp = matrix[i][j]; 19 | matrix[i][j] = matrix[i][n-j-1]; 20 | matrix[i][n-j-1] = temp; 21 | } 22 | } 23 | 24 | } 25 | } 26 | 27 | class Solution { 28 | public void rotate(int[][] matrix) { 29 | 30 | int n = matrix.length; 31 | int layers = n/2; 32 | 33 | for(int layer = 0; layer < layers; layer++) { 34 | int start = layer; 35 | int end = n-1-layer; 36 | 37 | for(int i = start; i < end; i++) { 38 | 39 | //top in temp 40 | int temp = matrix[start][i]; 41 | //left in top 42 | matrix[start][i] = matrix[n-1-i][start]; 43 | //bottom in left 44 | matrix[n-1-i][start] = matrix[end][n-1-i]; 45 | //right in bottom 46 | matrix[end][n-1-i] = matrix[i][end]; 47 | //top in right 48 | matrix[i][end] = temp; 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /509. Fibonacci Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] dp = new int[31]; 3 | 4 | public int fib(int n) { 5 | if(n<=1) return n; 6 | 7 | if(dp[n]>0){ 8 | return dp[n]; 9 | } 10 | 11 | dp[n] = fib(n-1) + fib(n-2); 12 | return dp[n]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /51. N-Queens: -------------------------------------------------------------------------------- 1 | class Solution { 2 | List> result; 3 | public List> solveNQueens(int n) { 4 | result = new ArrayList<>(); 5 | char[][] board = new char[n][n]; 6 | 7 | //Filled it as empty cells 8 | for(int i = 0; i < n; i++){ 9 | for(int j = 0; j < n; j++) { 10 | board[i][j] = '.'; 11 | } 12 | } 13 | 14 | List queens = new ArrayList<>(); 15 | dfs(board, 0, queens); 16 | return result; 17 | } 18 | 19 | private void dfs(char[][] board, int r, List queens) { 20 | //Check if all queens are placed 21 | if(queens.size() == board.length) { 22 | //Construct output 23 | List rows = new ArrayList<>(); 24 | for(char[] row : board) { 25 | rows.add(new String(row)); 26 | } 27 | result.add(rows); 28 | } 29 | 30 | //Try adding the queen 31 | for(int c = 0; c < board.length; c++) { 32 | if(canAddQueen(r,c,queens)) { 33 | board[r][c] = 'Q'; 34 | queens.add(new int[]{r,c}); 35 | dfs(board, r+1, queens); 36 | board[r][c] = '.'; 37 | queens.remove(queens.size()-1); 38 | } 39 | } 40 | } 41 | 42 | private boolean canAddQueen(int r, int c, List queens) { 43 | for(int[] q : queens) { 44 | int dx = Math.abs(r-q[0]); 45 | int dy = Math.abs(c-q[1]); 46 | if(dx==0 || dy==0 || dx==dy) return false; 47 | } 48 | return true; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /52. N-Queens II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int count; 3 | public int totalNQueens(int n) { 4 | count = 0; 5 | List queens = new ArrayList<>(); 6 | dfs(n, 0, queens); 7 | return count; 8 | } 9 | 10 | private void dfs(int n, int row, List queens) { 11 | if(queens.size() == n) { 12 | count++; 13 | return; 14 | } 15 | for(int col = 0; col < n; col++) { 16 | if(canPlaceQueen(row, col, queens)) { 17 | queens.add(new int[]{row, col}); 18 | dfs(n, row+1, queens); 19 | queens.remove(queens.size()-1); 20 | } 21 | } 22 | } 23 | 24 | private boolean canPlaceQueen(int row, int col, List queens) { 25 | for(int[] q : queens) { 26 | int dx = Math.abs(q[0] - row); 27 | int dy = Math.abs(q[1] - col); 28 | if(dx == 0 || dy == 0 || dx == dy) return false; 29 | } 30 | return true; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /530. Minimum Absolute Difference in BST: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | int minDifference = Integer.MAX_VALUE; 18 | Integer prev = null; 19 | public int getMinimumDifference(TreeNode root) { 20 | 21 | //Exit Condition 22 | if(root == null) return minDifference; 23 | 24 | getMinimumDifference(root.left); 25 | 26 | //Process Root 27 | if(prev != null){ 28 | minDifference = Math.min(minDifference, root.val-prev); 29 | } 30 | 31 | if(root != null){ 32 | prev = root.val; 33 | } 34 | 35 | getMinimumDifference(root.right); 36 | 37 | return minDifference; 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /55. Jump Game: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canJump(int[] nums) { 3 | int n = nums.length; 4 | 5 | if(n==1) return true; 6 | 7 | int max = 0; 8 | 9 | for(int index=0;index=index;index++){ 10 | if(max=n-1){ 15 | return true; 16 | } 17 | } 18 | 19 | return false; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /554. Brick Wall: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int leastBricks(List> wall) { 3 | int untouched =0; 4 | Map map =new HashMap<>(); 5 | 6 | for(List row : wall){ 7 | 8 | int end=0; 9 | for(int brick=0 ; brick < row.size() - 1 ; brick++){ 10 | end += row.get(brick); 11 | map.put(end, map.getOrDefault(end,0) + 1); 12 | untouched = Math.max(untouched,map.get(end)); 13 | } 14 | } 15 | 16 | return wall.size() - untouched; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /583. Delete Operation for Two Strings: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDistance(String word1, String word2) { 3 | int length = helper(word1,word2); 4 | return word1.length() + word2.length() - 2 * length ; 5 | } 6 | 7 | public int lcs(String text1, String text2) { 8 | int[][] dp = new int[text1.length()+1][text2.length()+1]; 9 | for(int i=0;i<=text1.length();i++){ 10 | for(int j=0;j<=text2.length();j++){ 11 | if(i==0 || j==0){ 12 | continue; 13 | } 14 | 15 | if(text1.charAt(i-1)==text2.charAt(j-1)){ 16 | dp[i][j] = 1 + dp[i-1][j-1]; 17 | } 18 | else{ 19 | dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]); 20 | } 21 | } 22 | } 23 | return dp[text1.length()][text2.length()]; 24 | } 25 | } 26 | 27 | class Solution { 28 | public int minDistance(String text1, String text2) { 29 | int[][] dp = new int[text1.length()+1][text2.length()+1]; 30 | for(int i=0;i<=text1.length();i++){ 31 | for(int j=0;j<=text2.length();j++){ 32 | if(i==0 || j==0){ 33 | dp[i][j] = i+j; 34 | } 35 | 36 | else if(text1.charAt(i-1)==text2.charAt(j-1)){ 37 | dp[i][j] = dp[i-1][j-1]; 38 | } 39 | else{ 40 | dp[i][j] = 1 + Math.min(dp[i-1][j],dp[i][j-1]); 41 | } 42 | } 43 | } 44 | return dp[text1.length()][text2.length()]; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /589. N-ary Tree Preorder Traversal: -------------------------------------------------------------------------------- 1 | class Solution { 2 | List result = new ArrayList<>(); 3 | public List preorder(Node root) { 4 | if(root == null) return result; 5 | preorderHelper(root); 6 | return result; 7 | } 8 | 9 | public void preorderHelper(Node node) { 10 | if(node.children == null) return; 11 | result.add(node.val); 12 | for(Node child : node.children) { 13 | preorderHelper(child); 14 | } 15 | } 16 | } 17 | 18 | class Solution { 19 | List result = new ArrayList<>(); 20 | public List preorder(Node root) { 21 | if(root == null) return result; 22 | 23 | Stack stack = new Stack<>(); 24 | stack.push(root); 25 | 26 | while(!stack.isEmpty()) { 27 | Node curr = stack.pop(); 28 | result.add(curr.val); 29 | //Pushing in children in reverse order 30 | for(int i = curr.children.size()-1; i >= 0; i--) { 31 | stack.push(curr.children.get(i)); 32 | } 33 | } 34 | 35 | return result; 36 | } 37 | 38 | }} 39 | -------------------------------------------------------------------------------- /600. Non-negative Integers without Consecutive Ones: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int[] dp; 3 | public int findIntegers(int n) { 4 | int ones = helper(n); 5 | return n - ones + 1; 6 | } 7 | 8 | int helper(int n){ 9 | double pow = Math.log(n)/Math.log(2); 10 | if(pow == (int)pow) return dp[(int)pow]; 11 | pow = Math.floor(pow); 12 | int ans = dp[(int) pow]; 13 | 14 | int lowestNumber = 1<<(int)pow; 15 | 16 | int left = n - lowestNumber; 17 | 18 | if(left>=lowestNumber/2) ans+= dp[(int)pow - 1] + (left - lowestNumber/2 + 1); 19 | else ans+=helper(left); 20 | return ans; 21 | } 22 | 23 | static{ 24 | dp = new int[33]; 25 | dp[0] = 0; 26 | dp[1] = 0; 27 | int val = 1; 28 | for(int i=2;i<33;i++){ 29 | dp[i] = dp[i-1] + dp[i-2] + val; 30 | val=val<<1; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /609. Find Duplicate File in System: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> findDuplicate(String[] paths) { 3 | Map> store = new HashMap<>(); 4 | 5 | for(String path:paths){ 6 | String[] arr = path.split(" "); 7 | String directory = arr[0]; 8 | 9 | for(int i=1;i filepaths = store.getOrDefault(content,new ArrayList<>()); 14 | filepaths.add(directory +"/"+fileName); 15 | store.put(content,filepaths); 16 | } 17 | } 18 | 19 | store.entrySet().removeIf(entry -> entry.getValue().size()<2); 20 | 21 | return new ArrayList<>(store.values()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /617. Merge Two Binary Trees: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 3 | //If t1 == NULL -> t2 4 | //If t2 == NULL -> t2 5 | // Sum (t1,t2) 6 | 7 | //Preorder Traversal (P -> L -> R) 8 | if(t1 == null) return t2; 9 | if(t2 == null) return t1; 10 | t1.val+=t2.val; 11 | t1.left = mergeTrees(t1.left, t2.left); 12 | t1.right = mergeTrees(t1.right, t2.right); 13 | return t1; 14 | } 15 | } 16 | 17 | 18 | 19 | class Solution { 20 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 21 | //If t1 == NULL -> t2 22 | //If t2 == NULL -> t2 23 | // Sum (t1,t2) 24 | 25 | if(t1 == null) return t2; 26 | if(t2 == null) return t1; 27 | 28 | Stack st = new Stack<>(); 29 | st.push(new TreeNode[]{t1,t2}); 30 | 31 | //While is not empty process the nodes 32 | while(!st.isEmpty()) { 33 | TreeNode[] curr = st.pop(); 34 | 35 | //Process the node 36 | curr[0].val+=curr[1].val; 37 | 38 | //1. curr[0] = null, curr[1] != null -> curr[1] 39 | //2. curr[1] = null, curr[0] != null -> curr[0] 40 | //3. both not null, add it stack 41 | 42 | //Left Tree 43 | if(curr[0].left == null) { 44 | curr[0].left = curr[1].left; 45 | } 46 | else if(curr[1].left != null) { 47 | st.push(new TreeNode[]{curr[0].left, curr[1].left}); 48 | } 49 | 50 | //Right Tree 51 | if(curr[0].right == null) { 52 | curr[0].right = curr[1].right; 53 | } 54 | else if(curr[1].right != null) { 55 | st.push(new TreeNode[]{curr[0].right, curr[1].right}); 56 | } 57 | } 58 | return t1; 59 | } 60 | } 61 | 62 | 63 | class Solution { 64 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 65 | //If t1 == NULL -> t2 66 | //If t2 == NULL -> t2 67 | // Sum (t1,t2) 68 | 69 | if(t1 == null) return t2; 70 | if(t2 == null) return t1; 71 | 72 | Queue q = new LinkedList<>(); 73 | q.add(new TreeNode[]{t1,t2}); 74 | 75 | //While is not empty process the nodes 76 | while(!q.isEmpty()) { 77 | TreeNode[] curr = q.remove(); 78 | if(curr[1] != null) { 79 | curr[0].val+=curr[1].val; 80 | 81 | //1. curr[0] = null -> curr[1] 82 | //2. curr[0] = null ->, add it queue 83 | 84 | //Left Tree 85 | if(curr[0].left == null) { 86 | curr[0].left = curr[1].left; 87 | } 88 | else { 89 | q.add(new TreeNode[]{curr[0].left, curr[1].left}); 90 | } 91 | 92 | //Right Tree 93 | if(curr[0].right == null) { 94 | curr[0].right = curr[1].right; 95 | } 96 | else { 97 | q.add(new TreeNode[]{curr[0].right, curr[1].right}); 98 | } 99 | } 100 | } 101 | return t1; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /622. Design Circular Queue: -------------------------------------------------------------------------------- 1 | class MyCircularQueue { 2 | 3 | int[] q; 4 | int front=0,rear=0,size=0; 5 | 6 | public MyCircularQueue(int k) { 7 | q=new int[k]; 8 | Arrays.fill(q,-1); 9 | } 10 | 11 | public boolean enQueue(int value) { 12 | if(isFull()){ 13 | return false; 14 | } 15 | if(isEmpty()){ 16 | front=rear=0; 17 | q[rear]=value; 18 | size++; 19 | return true; 20 | } 21 | 22 | rear++; 23 | size++; 24 | rear = rear %q.length; 25 | q[rear]=value; 26 | return true; 27 | } 28 | 29 | public boolean deQueue() { 30 | if(isEmpty()){ 31 | return false; 32 | } 33 | q[front]=-1; 34 | size--; 35 | front++; 36 | front = front % q.length; 37 | return true; 38 | } 39 | 40 | public int Front() { 41 | return q[front]; 42 | } 43 | 44 | public int Rear() { 45 | return q[rear]; 46 | } 47 | 48 | public boolean isEmpty() { 49 | return size==0; 50 | } 51 | 52 | public boolean isFull() { 53 | return size==q.length; 54 | } 55 | } 56 | 57 | /** 58 | * Your MyCircularQueue object will be instantiated and called as such: 59 | * MyCircularQueue obj = new MyCircularQueue(k); 60 | * boolean param_1 = obj.enQueue(value); 61 | * boolean param_2 = obj.deQueue(); 62 | * int param_3 = obj.Front(); 63 | * int param_4 = obj.Rear(); 64 | * boolean param_5 = obj.isEmpty(); 65 | * boolean param_6 = obj.isFull(); 66 | */ 67 | -------------------------------------------------------------------------------- /63. Unique Paths II: -------------------------------------------------------------------------------- 1 | //Basic DFS : TLE as time complexity goes O(2^(M*N)) 2 | 3 | class Solution { 4 | int un=0; 5 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 6 | dfs(obstacleGrid,0,0); 7 | return un; 8 | } 9 | void dfs(int[][] obstacleGrid,int row,int col){ 10 | if(row==obstacleGrid.length-1 && col==obstacleGrid[0].length-1 && obstacleGrid[row][col]==0){ 11 | un++; 12 | return; 13 | } 14 | if(row<0 || col<0 || row==obstacleGrid.length || col==obstacleGrid[0].length || obstacleGrid[row][col]==1){ 15 | return; 16 | } 17 | 18 | dfs(obstacleGrid,row,col+1); 19 | dfs(obstacleGrid,row+1,col); 20 | } 21 | } 22 | 23 | 24 | //Adding Memoization for above code 25 | class Solution { 26 | int[][] dp; 27 | public int uniquePathsWithObstacles(int[][] grid) { 28 | dp = new int[grid.length][grid[0].length]; 29 | for(int[] d : dp) { 30 | Arrays.fill(d, -1); 31 | } 32 | return dfs(grid, 0, 0); 33 | } 34 | 35 | int dfs(int[][] grid, int row, int col) { 36 | //Exit condition 37 | if(row < 0 || col < 0 || row == grid.length || col == grid[0].length || grid[row][col] == 1) 38 | return 0; 39 | if(row == grid.length-1 && col == grid[0].length-1){ 40 | return 1; 41 | } 42 | if(dp[row][col] > -1) return dp[row][col]; 43 | dp[row][col] = dfs(grid, row, col+1) +dfs(grid, row+1, col); 44 | return dp[row][col]; 45 | } 46 | } 47 | 48 | //Top Down Approach 49 | class Solution { 50 | public int uniquePathsWithObstacles(int[][] grid) { 51 | int m = grid.length, n = grid[0].length; 52 | if(grid[0][0] == 1) return 0; 53 | for(int i = 0; i < m; i++) { 54 | for(int j = 0; j < n; j++) { 55 | //First row && first column 56 | if(i == 0 || j ==0) { 57 | //its prev cell was obstacle or if current cell is obstacle 58 | if(grid[i][j] == 1 || (i!=0 && grid[i-1][0] == 0) || (j!=0 && grid[i][j-1] == 0)) { 59 | grid[i][j] = 0; 60 | } 61 | else { 62 | grid[i][j] = 1; 63 | } 64 | } 65 | //All the other cells 66 | else { 67 | if(grid[i][j] == 1) { 68 | grid[i][j] = 0; 69 | } 70 | else { 71 | grid[i][j] = grid[i-1][j] + grid[i][j-1]; 72 | } 73 | } 74 | } 75 | } 76 | return grid[m-1][n-1]; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /630. Course Schedule III: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int scheduleCourse(int[][] courses) { 3 | Arrays.sort(courses, (a,b)-> a[1]==b[1] ? a[0]-b[0] : a[1]-b[1]); 4 | PriorityQueue pq = new PriorityQueue<>((a,b) -> b-a); 5 | int time = 0; 6 | 7 | for(int[] course : courses) { 8 | //Check if we consider current course : if duration <= lastday 9 | if(course[0] <= course[1]) { 10 | //current course can be completed with the lastday given 11 | if(course[0]+time <= course[1]) { 12 | pq.offer(course[0]); 13 | time+=course[0]; 14 | } 15 | else { 16 | //Check if we can swap 17 | if(pq.peek() > course[0]) { 18 | time-=pq.poll(); 19 | time+=course[0]; 20 | pq.offer(course[0]); 21 | } 22 | } 23 | } 24 | } 25 | return pq.size(); 26 | } 27 | } 28 | 29 | 30 | //Short version of the code 31 | public class Solution { 32 | public int scheduleCourse(int[][] courses) { 33 | Arrays.sort(courses, (a,b)-> a[1]==b[1] ? a[0]-b[0] : a[1]-b[1]); 34 | PriorityQueue pq=new PriorityQueue<>((a,b)->b-a); 35 | int time=0; 36 | for (int[] course : courses) 37 | { 38 | //Add current course to a priority queue 39 | time+=course[0]; 40 | pq.offer(course[0]); 41 | //If time exceeds, drop the previous course which costs the most time. 42 | if (time>course[1]) time-=pq.poll(); 43 | } 44 | return pq.size(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /65. Valid Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isNumber(String s) { 3 | boolean digitseen =false, eseen = false, dotseen=false; 4 | int countPlusMinus = 0; 5 | 6 | for(int i=0;i0 && (s.charAt(i-1) != 'e' && s.charAt(i-1) != 'E')){ 20 | return false; 21 | } 22 | 23 | if(i == s.length()-1){ 24 | return false; 25 | } 26 | 27 | countPlusMinus++; 28 | } 29 | //dot 30 | else if(ch == '.'){ 31 | if(eseen || dotseen){ 32 | return false; 33 | } 34 | 35 | if(i == s.length() -1 && !digitseen){ 36 | return false; 37 | } 38 | 39 | dotseen = true; 40 | } 41 | 42 | //e/E 43 | else if(ch == 'e' || ch == 'E'){ 44 | if(eseen || !digitseen || i == s.length()-1){ 45 | return false; 46 | } 47 | 48 | eseen = true; 49 | } 50 | else{ 51 | return false; 52 | } 53 | 54 | } 55 | 56 | return true; 57 | } 58 | } 59 | 60 | import java.util.regex.*; 61 | class Solution { 62 | public boolean isNumber(String s) { 63 | return Pattern.matches("^([+-]?(((\\d+\\.\\d*)|(\\.\\d+))|(\\d+))([eE][+-]?\\d+)?)$", s); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /665. Non-decreasing Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean checkPossibility(int[] nums) { 3 | int pos = -1; 4 | 5 | for(int i=0;inums[i+1]){ 7 | if(pos!=-1){ 8 | return false; 9 | } 10 | pos=i; 11 | } 12 | } 13 | 14 | return pos==-1 || pos==0 || pos == nums.length-2 || nums[pos-1]<=nums[pos+1] || nums[pos]<=nums[pos+2]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /667. Beautiful Arrangement II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] constructArray(int n, int k) { 3 | int[] result =new int[n]; 4 | 5 | int high = n , low = 1; 6 | int index = 0; 7 | 8 | result[index++] = low++; 9 | 10 | boolean isHigh = false; 11 | 12 | while(k>1){ 13 | result[index++] = high--; 14 | k--; 15 | isHigh = true; 16 | if(k>1){ 17 | result[index++] = low++; 18 | k--; 19 | isHigh = false; 20 | } 21 | } 22 | 23 | //increasing or decreasing 24 | while(index pList = prefix.startswith(pre); 23 | List sList = suffix.startswith(new StringBuilder(suff).reverse().toString()); 24 | 25 | int i = pList.size()-1, j = sList.size()-1; 26 | while(i >= 0 && j >= 0) { 27 | if(Objects.equals(pList.get(i), sList.get(j))) return pList.get(i); 28 | else if(pList.get(i) > sList.get(j)) i--; 29 | else j--; 30 | } 31 | 32 | return -1; 33 | } 34 | } 35 | 36 | class Trie { 37 | 38 | public Trie[] t; 39 | List index; 40 | 41 | Trie() { 42 | t = new Trie[26]; 43 | index = new ArrayList<>(); 44 | } 45 | 46 | //insert 47 | public void insert(String word, int i) { 48 | Trie root = this; 49 | for(char c: word.toCharArray()) { 50 | if(root.t[c-'a'] == null) { 51 | root.t[c-'a'] = new Trie(); 52 | } 53 | root = root.t[c-'a']; 54 | root.index.add(i); 55 | } 56 | } 57 | 58 | //startswith 59 | public List startswith(String word) { 60 | Trie root = this; 61 | for(char c : word.toCharArray()) { 62 | if(root.t[c-'a'] == null) { 63 | return new ArrayList<>(); 64 | } 65 | root = root.t[c-'a']; 66 | } 67 | return root.index; 68 | } 69 | } 70 | 71 | /** 72 | * Your WordFilter object will be instantiated and called as such: 73 | * WordFilter obj = new WordFilter(words); 74 | * int param_1 = obj.f(prefix,suffix); 75 | */ 76 | -------------------------------------------------------------------------------- /775. Global and Local Inversions: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isIdealPermutation(int[] A) { 3 | for(int i = 0; i < A.length; i++) { 4 | if(Math.abs(A[i]-i) > 1) return false; 5 | } 6 | return true; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /816. Ambiguous Coordinates: -------------------------------------------------------------------------------- 1 | class Solution { 2 | List result = new ArrayList<>(); 3 | public List ambiguousCoordinates(String s) { 4 | s=s.substring(1,s.length()-1); 5 | //Breaking String in x,y form (0123) -> (0,123) 6 | for(int i = 1; i < s.length(); i++) { 7 | helper(s.substring(0,i), s.substring(i)); 8 | } 9 | return result; 10 | } 11 | 12 | public void helper(String x, String y){ 13 | List dotx = putDot(x); 14 | List doty = putDot(y); 15 | 16 | for(String dx : dotx){ 17 | if(isValid(dx)) { 18 | for(String dy : doty){ 19 | if(isValid(dy)) { 20 | result.add("("+dx+", "+dy+")"); //(1, 23) 21 | } 22 | } 23 | } 24 | } 25 | } 26 | 27 | public List putDot(String s){ 28 | List res = new ArrayList<>(); 29 | res.add(s); 30 | for(int i = 1; i < s.length(); i++) { 31 | res.add(s.substring(0,i)+"."+s.substring(i)); 32 | } 33 | return res; 34 | } 35 | 36 | public boolean isValid(String s) { 37 | if(s.contains(".")) { 38 | String[] part = s.split("\\."); 39 | if(!part[0].equals("0") && part[0].startsWith("0")) return false; 40 | else return !part[1].endsWith("0"); 41 | } 42 | else { 43 | if(s.equals("0")) return true; 44 | else return !s.startsWith("0"); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /84. Largest Rectangle in Histogram: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int largestRectangleArea(int[] h) { 3 | //Check null condition 4 | if(h == null || h.length == 0) return 0; 5 | 6 | //Initialize variables left and right 7 | int n = h.length; 8 | int[] left = new int[n]; 9 | left[0] = -1; 10 | 11 | int[] right = new int[n]; 12 | right[n-1] = n; 13 | 14 | //Fill left array 15 | for(int i = 1; i < n; i++) { 16 | int prev = i-1; 17 | while(prev >= 0 && h[prev] >= h[i]){ 18 | prev = left[prev]; 19 | } 20 | left[i] = prev; 21 | } 22 | 23 | //Fill right array 24 | for(int i = n-2; i >= 0; i--){ 25 | int prev = i+1; 26 | while(prev < n && h[prev] >= h[i]){ 27 | prev = right[prev]; 28 | } 29 | right[i] = prev; 30 | } 31 | 32 | int maxArea = 0; 33 | for(int i = 0; i < n; i++) { 34 | maxArea = Math.max(maxArea, h[i] * (right[i]-left[i]-1)); 35 | } 36 | 37 | return maxArea; 38 | } 39 | } 40 | 41 | class Solution { 42 | public int largestRectangleArea(int[] h) { 43 | //Check null condition 44 | if(h == null || h.length == 0) return 0; 45 | 46 | //Initialize variables left and right 47 | int n = h.length; 48 | Stack stack = new Stack<>(); 49 | int maxArea = 0; 50 | 51 | for(int i = 0; i <= n; i++) { 52 | int ht = (i == n) ? 0 : h[i]; 53 | //If stack is empty of ht >= h[top] push in stack 54 | //Else process the elements and find area. 55 | 56 | if(stack.isEmpty() || ht >= h[stack.peek()]) { 57 | stack.push(i); 58 | } 59 | else { 60 | //Process elements and find the mexArea for popped index 61 | int top = stack.pop(); 62 | int width = (stack.isEmpty()) ? i : (i - stack.peek() - 1); 63 | int area = h[top] * width; 64 | maxArea = Math.max(maxArea, area); 65 | i--; 66 | } 67 | } 68 | return maxArea; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /86. Partition List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode partition(ListNode head, int x) { 13 | ListNode small = new ListNode(0); 14 | ListNode higher = new ListNode(0); 15 | 16 | ListNode smallHead=small, higherHead = higher; 17 | 18 | while(head!=null){ 19 | if(head.val map = new TreeMap<>(); 10 | 11 | for(int i=0;i=k) return 1; 13 | sum+=nums[i]; 14 | if(sum>=k){ 15 | res = Math.min(res,i + 1); 16 | } 17 | 18 | long remainingSum = sum - k; 19 | Map.Entry entry = map.floorEntry(remainingSum); 20 | while(entry!=null){ 21 | int index = entry.getValue(); 22 | res = Math.min(res,i - index); 23 | map.remove(entry.getKey()); 24 | entry = map.floorEntry(entry.getKey()-1); 25 | } 26 | map.put(sum,i); 27 | 28 | } 29 | 30 | return res==Integer.MAX_VALUE?-1:res; 31 | } 32 | } 33 | 34 | //TC: O(N) 35 | //SC: O(N) 36 | class Solution { 37 | public int shortestSubarray(int[] nums, int k) { 38 | int n = nums.length; 39 | long sum=0; 40 | int res = Integer.MAX_VALUE; 41 | 42 | long[] prefix = new long[n+1]; 43 | for(int i=0;i dq = new ArrayDeque<>(); 48 | for(int i=0;i =k we remove the start index at dq 50 | while(!dq.isEmpty() && (prefix[i] - prefix[dq.peekFirst()]) >=k){ 51 | res = Math.min(res,i-dq.pollFirst()); 52 | } 53 | 54 | //if sum at last in dq >= current sum, we remove the last values from dq 55 | while(!dq.isEmpty() && prefix[dq.peekLast()]>=prefix[i]){ 56 | dq.pollLast(); 57 | } 58 | dq.add(i); 59 | } 60 | 61 | return res==Integer.MAX_VALUE?-1:res; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /871. Minimum Number of Refueling Stops: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minRefuelStops(int target, int startFuel, int[][] stations) { 3 | int n=stations.length; 4 | long[] dp = new long[n+1]; 5 | dp[0]=startFuel; 6 | 7 | for(int i=0;i=0 && dp[refill]>=stations[i][0];refill--){ 9 | dp[refill+1] = Math.max(dp[refill+1],dp[refill] + stations[i][1]); 10 | } 11 | } 12 | 13 | for(int i=0;i<=n;i++){ 14 | if(dp[i]>=target){ 15 | return i; 16 | } 17 | } 18 | 19 | return -1; 20 | } 21 | } 22 | 23 | class Solution { 24 | public int minRefuelStops(int target, int startFuel, int[][] stations) { 25 | int n=stations.length; 26 | PriorityQueue pq= new PriorityQueue<>((a,b) -> b[1]-a[1]); 27 | 28 | int refill =0,i=0; 29 | int distance = startFuel; 30 | 31 | while(distance= stations[i][0]){ 33 | pq.offer(stations[i]); 34 | i++; 35 | } 36 | 37 | if(pq.isEmpty()) return -1; 38 | 39 | distance += pq.remove()[1]; 40 | refill++; 41 | } 42 | 43 | return refill; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /890. Find and Replace Pattern: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List findAndReplacePattern(String[] words, String pattern) { 3 | List result = new ArrayList<>(); 4 | 5 | for(String word:words){ 6 | if(matches(word,pattern)){ 7 | result.add(word); 8 | } 9 | } 10 | 11 | return result; 12 | } 13 | 14 | private boolean matches(String word,String pattern){ 15 | char[] patternToWord = new char[26]; 16 | char[] wordToPattern = new char[26]; 17 | 18 | for(int index = 0; index= 0; j--) { 13 | sb.append(sb.charAt(j)); 14 | } 15 | 16 | //Palindrome in sb 17 | long n = Long.valueOf(sb.toString()); 18 | n*=n; 19 | //Check if n is a super palindrome --> Find whether it is palindrome 20 | if(n > r) break; 21 | else if(n>=l && isPalindrome(n)) count++; 22 | } 23 | 24 | //Odd Palindromes 25 | for(int i = 1; i < 100000; i++) { 26 | StringBuilder sb = new StringBuilder(Integer.toString(i)); 27 | for(int j = sb.length()-2; j >= 0; j--) { 28 | sb.append(sb.charAt(j)); 29 | } 30 | 31 | //Palindrome in sb 32 | long n = Long.valueOf(sb.toString()); 33 | n*=n; 34 | //Check if n is a super palindrome --> Find whether it is palindrome 35 | if(n > r) break; 36 | else if(n>=l && isPalindrome(n)) count++; 37 | } 38 | 39 | return count; 40 | 41 | } 42 | 43 | public boolean isPalindrome(long n) { 44 | return n == reverse(n); 45 | } 46 | 47 | public long reverse(long n) { 48 | long rev = 0; 49 | while(n > 0) { 50 | rev = rev*10 + n%10; 51 | n/=10; 52 | } 53 | return rev; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /927. Three Equal Parts: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] threeEqualParts(int[] arr) { 3 | int n = arr.length; 4 | int oneCount = 0; 5 | 6 | //Counting total number of 1's 7 | for(int i : arr) if(i==1) oneCount++; 8 | 9 | //Base exit condition 10 | if(oneCount % 3 != 0) return new int[]{-1,-1}; 11 | 12 | //If oneCount ==0; return any partition 13 | if(oneCount == 0) return new int[]{0,n-1}; 14 | 15 | int k = oneCount/3; 16 | 17 | //Create Partition 18 | int i1 = -1, i2 = -1, i3 = -1, j1 = -1, j2 = -1,j3 = -1; 19 | int currCount = 0; 20 | 21 | for(int i = 0; i < n; i++) { 22 | if(arr[i] == 1) { 23 | currCount+=1; 24 | if(currCount == 1) i1 = i; 25 | if(currCount == (k+1)) i2 = i; 26 | if(currCount == (2*k+1)) i3 = i; 27 | 28 | if(currCount == k) j1 = i; 29 | if(currCount == 2*k) j2 = i; 30 | if(currCount == 3*k) j3 = i; 31 | } 32 | } 33 | 34 | //Compare 3 partitions 35 | 36 | /* 37 | //O(N) Space Solution 38 | int[] part1 = Arrays.copyOfRange(arr, i1, j1+1); 39 | int[] part2 = Arrays.copyOfRange(arr, i2, j2+1); 40 | int[] part3 = Arrays.copyOfRange(arr, i3, j3+1); 41 | 42 | if(!Arrays.equals(part1, part2) || !Arrays.equals(part1, part3)) 43 | return new int[]{-1,-1}; 44 | 45 | */ 46 | int start = i1, mid = i2,end = i3; 47 | while(k-- > 0 && arr[start] == arr[mid] && arr[mid] == arr[end]){ 48 | start++; 49 | mid++; 50 | end++; 51 | } 52 | 53 | if(k >= 0) return new int[]{-1,-1}; 54 | 55 | 56 | //Take care of the trailing zeros 57 | int first = 0, second = 0, third = 0; 58 | first = i2-j1-1; 59 | second = i3-j2-1; 60 | third = n-j3-1; 61 | 62 | if(third > Math.min(first, second)) return new int[]{-1,-1}; 63 | 64 | return new int[]{j1+third, j2+third+1}; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /953. Verifying an Alien Dictionary: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isAlienSorted(String[] words, String order) { 3 | int[] mapping = new int[26]; 4 | int seq=0; 5 | for(char ch:order.toCharArray()){ 6 | mapping[ch-'a'] = seq++; 7 | } 8 | 9 | for(int i=0;i mapping[next.charAt(l)-'a']){ 21 | return false; 22 | } 23 | 24 | if(mapping[curr.charAt(l)-'a'] < mapping[next.charAt(l)-'a']){ 25 | break; 26 | } 27 | 28 | } 29 | } 30 | 31 | return true; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /968. Binary Tree Cameras: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int cam; 3 | Set covered; 4 | public int minCameraCover(TreeNode root) { 5 | if(root == null) return 0; 6 | cam = 0; 7 | covered = new HashSet<>(); 8 | covered.add(null); // Skip the leaf nodes and start from one level above. 9 | dfs(root, null); 10 | return cam; 11 | } 12 | 13 | public void dfs(TreeNode node, TreeNode parent){ 14 | if(node != null) { 15 | dfs(node.left, node); 16 | dfs(node.right, node); 17 | 18 | //Check if i need to add camera at node. 19 | // Parent is null & node is uncovered 20 | // OR 21 | // if any of its left or right child are not covered 22 | 23 | if(parent == null && !covered.contains(node) 24 | || !covered.contains(node.left) || !covered.contains(node.right)) { 25 | cam++; 26 | covered.add(node); 27 | covered.add(parent); 28 | covered.add(node.left); 29 | covered.add(node.right); 30 | } 31 | 32 | } 33 | } 34 | } 35 | 36 | class Solution { 37 | int cam = 0; 38 | public int minCameraCover(TreeNode root) { 39 | // (0) -> cam + 1 ,(1,2) --> cam 40 | return dfs(root)==0 ? cam+1 : cam; 41 | } 42 | 43 | // 2 --> Has Camera 44 | // 1 -> Covered with the camera 45 | // 0 --> No camera is covering this node 46 | public int dfs(TreeNode node) { 47 | if(node == null) return 1; 48 | int left = dfs(node.left); 49 | int right = dfs(node.right); 50 | //Check if we need to add a camera 51 | if(left == 0 || right == 0) { 52 | cam++; 53 | return 2; 54 | } 55 | else if(left == 2 || right == 2) return 1; 56 | else return 0; 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /970. Powerful Integers: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List powerfulIntegers(int x, int y, int bound) { 3 | List px = new ArrayList<>(); 4 | List py = new ArrayList<>(); 5 | int powx = x, powy = y; 6 | px.add(1); 7 | py.add(1); 8 | //logx 9 | if(x != 1) { 10 | //Calculate powers of x until < bound 11 | while(powx < bound) { 12 | px.add(powx); 13 | powx = powx*x; 14 | } 15 | } 16 | //logy 17 | if(y != 1) { 18 | //Calculate powers of y until < bound 19 | while(powy < bound) { 20 | py.add(powy); 21 | powy = powy*y; 22 | } 23 | } 24 | 25 | Set result = new HashSet<>(); 26 | //logx * logy 27 | for(int i : px) { 28 | for(int j : py) { 29 | if((i+j) <= bound) result.add(i+j); 30 | } 31 | } 32 | 33 | return result.stream().collect(Collectors.toList()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode Problems 2 | 3 | Number | Name of Problem | Leetcode Link | Video Link | Code 4 | --- | :---: | --- | --- | --- 5 | 55 | Jump Game | https://leetcode.com/problems/jump-game/ | https://youtu.be/C6AZyfj-Kyw | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/55.%20Jump%20Game 6 | 118 | Pascal's Triangle | https://leetcode.com/problems/pascals-triangle/description/ | https://youtu.be/eeleEMOlRpA | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/118.%20Pascal's%20Triangle 7 | 121 | Best Time to Buy and Sell Stock | https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ | https://youtu.be/5skEWekmJ2w | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/121.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock 8 | 134 | Gas Station | https://leetcode.com/problems/gas-station/ | https://youtu.be/3wUa7Lf1Xjk | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/134.%20Gas%20Station 9 | 198 | House Robber | https://leetcode.com/problems/house-robber/ | https://youtu.be/YEEQRP2ZFxk | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/198.%20House%20Robber 10 | 206 | Reverse Linked List | https://leetcode.com/problems/reverse-linked-list/description/ | https://youtu.be/rzXJe1xMHLc | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/206.%20Reverse%20Linked%20List 11 | 213 | House Robber II | https://leetcode.com/problems/house-robber-ii/ | https://youtu.be/5bxF0MJ1oM0 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/213.%20House%20Robber%20II 12 | 300 | Longest Increasing Subsequence | https://leetcode.com/problems/longest-increasing-subsequence/description/ | https://youtu.be/iyd-8fpqEgU | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/300.%20Longest%20Increasing%20Subsequence 13 | 337 | House Robber III | https://leetcode.com/problems/house-robber-iii/ | https://youtu.be/FRP5l83XoZo | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/337.%20House%20Robber%20III 14 | 403 | Frog jump | https://leetcode.com/problems/frog-jump/ | https://youtu.be/3FYCPlIx3YA | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/403.%20Frog%20Jump 15 | 530 | Minimum Absolute Difference in BST | https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ | https://youtu.be/uDykjVZ5s4o | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/530.%20Minimum%20Absolute%20Difference%20in%20BST 16 | 724 | Find Pivot Index | https://leetcode.com/problems/find-pivot-index/description/ | https://youtu.be/HSg9QONpcPw | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/724.%20Find%20Pivot%20Index 17 | 862 | Shortest Subarray with Sum at Least K | https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/description/ | https://youtu.be/eWbH_j6Lgnk | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/862.%20Shortest%20Subarray%20with%20Sum%20at%20Least%20K 18 | 1071 | Greatest Common Divisor of Strings | https://leetcode.com/problems/greatest-common-divisor-of-strings/description/ | https://youtu.be/41iKYE0n0PQ | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1071.%20Greatest%20Common%20Divisor%20of%20Strings 19 | 1129 | Shortest Path with Alternating Colors | https://leetcode.com/problems/shortest-path-with-alternating-colors/description/ | https://youtu.be/8FcdSwqR3Js | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1129.%20Shortest%20Path%20with%20Alternating%20Colors 20 | 1340 | Jump Game V | https://leetcode.com/problems/jump-game-v/ | https://youtu.be/pQXbujZLTv0 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1340.%20Jump%20Game%20V 21 | 1353 | Maximum Number of Events That Can Be Attended | https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/ | https://youtu.be/dTVB1W7-BvY | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1353.%20Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended 22 | 1365 | How Many Numbers Are Smaller Than the Current Number | https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/description/ | https://youtu.be/CKSdHsQyPYk | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1365.%20How%20Many%20Numbers%20Are%20Smaller%20Than%20the%20Current%20Number 23 | 1498 | Number of Subsequences That Satisfy the Given Sum Condition | https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/description/ | https://youtu.be/CNwBICbW-M8 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1498.%20Number%20of%20Subsequences%20That%20Satisfy%20the%20Given%20Sum%20Condition 24 | 1510 | Stone Game IV | https://leetcode.com/problems/stone-game-iv/ | https://youtu.be/Gcg_a3r8FA0 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1510.%20Stone%20Game%20IV 25 | 1523 | Count Odd Numbers in an Interval Range | https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/description/ | https://youtu.be/HxI78QECe0c | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1523.%20Count%20Odd%20Numbers%20in%20an%20Interval%20Range 26 | 1696 | Jump Game VI | https://leetcode.com/problems/jump-game-vi/ | https://youtu.be/LiEcBMK5PQs | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1696.%20Jump%20Game%20VI 27 | 1751 | Maximum Number of Events That Can Be Attended II | https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/description/ | https://youtu.be/C3r4OTOmfaI | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1751.%20Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II 28 | 1834 | Single-Threaded CPU | https://leetcode.com/problems/single-threaded-cpu/ | https://youtu.be/6104EJTG_T4 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1834.%20Single-Threaded%20CPU 29 | 1871 | Jump Game VII | https://leetcode.com/problems/jump-game-vii/ | https://youtu.be/bZxWLuiqHes | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1871.%20Jump%20Game%20VII 30 | 2328 | Number of Increasing Paths in a Grid | https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/description/ | https://youtu.be/kPAv1t2uBjg | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/2328.%20Number%20of%20Increasing%20Paths%20in%20a%20Grid 31 | 2375 | Construct Smallest Number From DI String | https://leetcode.com/problems/construct-smallest-number-from-di-string/ | https://youtu.be/GEqSg0Otq4Y | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/2375.%20Construct%20Smallest%20Number%20From%20DI%20String 32 | 2531 | Make Number of Distinct Characters Equal | https://leetcode.com/problems/make-number-of-distinct-characters-equal/description/ | https://youtu.be/GwWmlpIEIwc | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/2531.%20Make%20Number%20of%20Distinct%20Characters%20Equal 33 | 2598 | Length Of Longest Subarray with at most K Frequency | https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/ | https://youtu.be/GwWmlpIEIwc | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/2598.%20Length%20Of%20Longest%20Subarray%20with%20at%20most%20K%20Frequency 34 | 2657 | Find the Prefix Common Array of Two Arrays | https://leetcode.com/problems/find-the-prefix-common-array-of-two-arrays/description/ | https://youtu.be/m6s9dBCBocQ | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/2657.%20Find%20the%20Prefix%20Common%20Array%20of%20Two%20Arrays 35 | 36 | # Leetcode-Challenge 37 | 38 | # July Leetcoding Challenge 2021 39 | 40 | Day | Name of Problem | Leetcode Link | Video Link | Code 41 | --- | :---: | --- | --- | --- 42 | 18 | Reverse Nodes in k-Group | https://leetcode.com/problems/reverse-nodes-in-k-group/ | https://youtu.be/FYsYAELWyRs | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/25.%20Reverse%20Nodes%20in%20k-Group 43 | 26 | Non-negative Integers without Consecutive Ones | https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/ | https://youtu.be/Pdeje3QH8G8 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/600.%20Non-negative%20Integers%20without%20Consecutive%20Ones 44 | 45 | # June Leetcoding Challenge 2021 46 | 47 | Day | Name of Problem | Leetcode Link | Video Link | Code 48 | --- | :---: | --- | --- | --- 49 | 12 | Minimum Number of Refueling Stops | https://leetcode.com/problems/minimum-number-of-refueling-stops/ | https://youtu.be/4RgqAQFr9WQ | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/871.%20Minimum%20Number%20of%20Refueling%20Stops 50 | 51 | # May Leetcoding Challenge 2021 52 | 53 | Day | Name of Problem | Leetcode Link | Video Link | Code 54 | --- | :---: | --- | --- | --- 55 | 1 | Prefix and Suffix Search | https://leetcode.com/problems/prefix-and-suffix-search/ | https://youtu.be/U7fIQ7qAeuE | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/745.%20Prefix%20and%20Suffix%20Search 56 | 2 | Course Schedule III | https://leetcode.com/problems/course-schedule-iii/ | https://youtu.be/ey8FxYsFAMU | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/630.%20Course%20Schedule%20III 57 | 3 | Running Sum of 1d Array | https://leetcode.com/problems/running-sum-of-1d-array/ | https://youtu.be/3uMmKCZ_9Go | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1480.%20Running%20Sum%20of%201d%20Array 58 | 4 | Non-decreasing Array | https://leetcode.com/problems/non-decreasing-array/ | https://youtu.be/iL7oSNc3OXA | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/665.%20Non-decreasing%20Array 59 | 5 | Jump Game II | https://leetcode.com/problems/jump-game-ii/ | https://youtu.be/BRnRPLNGWIo | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/45.%20Jump%20Game%20II 60 | 6 | Convert Sorted List to BST | https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ | https://youtu.be/5IQF13nNq6A | https://github.com/Algorithms-Made-Easy/Tree/blob/master/Convert-Sorted-List-to-Binary-Search-Tree 61 | 7 | Delete Operation for Two Strings | https://leetcode.com/problems/delete-operation-for-two-strings/ | https://youtu.be/VSrsUkoG0bk | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/583.%20Delete%20Operation%20for%20Two%20Strings 62 | 8 | Super Palindromes | https://leetcode.com/problems/super-palindromes/ | https://youtu.be/iZ_wJbrlJz0 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/906.%20Super%20Palindromes 63 | 9 | Construct Target Array With Multiple Sums | https://leetcode.com/problems/construct-target-array-with-multiple-sums/ | https://youtu.be/h9t7JF50Mpw | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1354.%20Construct%20Target%20Array%20With%20Multiple%20Sums 64 | 10 | Count Primes | https://leetcode.com/problems/count-primes/ | https://youtu.be/5LMkddl2NCk | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/204.%20Count%20Primes 65 | 11 | Maximum Points You Can Obtain from Cards | https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/ | https://youtu.be/U0utLw_vWGM | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1423.%20Maximum%20Points%20You%20Can%20Obtain%20from%20Cards 66 | 12 | Range Sum Query 2D - Immutable | https://leetcode.com/problems/range-sum-query-2d-immutable/ | https://youtu.be/rkLDDxOcJxU | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/304.%20Range%20Sum%20Query%202D%20-%20Immutable 67 | 13 | Ambiguous Coordinates | https://leetcode.com/problems/ambiguous-coordinates/ | https://youtu.be/rt-lJS5nlOQ | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/816.%20Ambiguous%20Coordinates 68 | 14 | Flatten Binary Tree to Linked List | https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ | https://youtu.be/NOKVBiJwkD0 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/114.%20Flatten%20Binary%20Tree%20to%20Linked%20List 69 | 15 | Valid Number | https://leetcode.com/problems/valid-number/ | https://youtu.be/0qac3ngAZmE | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/65.%20Valid%20Number 70 | 16 | Binary Tree Cameras | https://leetcode.com/problems/binary-tree-cameras/ | https://youtu.be/2Gh5WPjAgJk | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/968.%20Binary%20Tree%20Cameras 71 | 17 | Longest String Chain | https://leetcode.com/problems/longest-string-chain/ |https://youtu.be/pXG3uE_KqZM | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1048.%20Longest%20String%20Chain 72 | 18 | Find Duplicate File in System | https://leetcode.com/problems/find-duplicate-file-in-system/ |https://youtu.be/4KGl6PMwVXE| https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/609.%20Find%20Duplicate%20File%20in%20System 73 | 19 | Minimum Moves to Equal Array Elements II | https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ | https://youtu.be/FGgL5QxZLno | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/462.%20Minimum%20Moves%20to%20Equal%20Array%20Elements%20II 74 | 20 | Binary Tree Level Order Traversal | https://leetcode.com/problems/binary-tree-level-order-traversal/ | https://youtu.be/vQrggrFMyp8 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/102.%20Binary%20Tree%20Level%20Order%20Traversal 75 | 21 | Find and Replace Pattern | https://leetcode.com/problems/find-and-replace-pattern/ | https://youtu.be/JbiV9l5AHQE | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/890.%20Find%20and%20Replace%20Pattern 76 | 22 | N-Queens | https://leetcode.com/problems/n-queens/ | https://youtu.be/jJMWhGKq3SM | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/51.%20N-Queens 77 | 78 | # April Leetcoding Challenge 2021 79 | 80 | Day | Name of Problem | Leetcode Link | Video Link | Code 81 | --- | :---: | --- | --- | --- 82 | 1 | Palindrome Linked List | https://leetcode.com/problems/palindrome-linked-list/ | https://youtu.be/Ll9ZbXaXqlQ | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/234.%20Palindrome%20Linked%20List 83 | 2 | Ones and Zeroes | https://leetcode.com/problems/ones-and-zeroes/ | https://youtu.be/qkUZ87NCYSw | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/474.%20Ones%20and%20Zeroes 84 | 3 | Longest Valid Parentheses | https://leetcode.com/problems/longest-valid-parentheses/ | https://youtu.be/VdQuwtEd10M | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/32.%20Longest%20Valid%20Parentheses 85 | 4 | Design Circular Queue | https://leetcode.com/problems/design-circular-queue/ | https://youtu.be/Q2YhZ6Pq0GQ | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/622.%20Design%20Circular%20Queue 86 | 5 | Global and Local Inversions | https://leetcode.com/problems/global-and-local-inversions/ | https://youtu.be/1QlP6cVLrII | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/775.%20Global%20and%20Local%20Inversions 87 | 6 | Minimum Operations to Make Array Equal | https://leetcode.com/problems/minimum-operations-to-make-array-equal/ | https://youtu.be/9aGx9hoIBjI | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1551.%20Minimum%20Operations%20to%20Make%20Array%20Equal 88 | 7 | Determine if String Halves Are Alike | https://leetcode.com/problems/determine-if-string-halves-are-alike/ | https://youtu.be/752uISt9sCs | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1704.%20Determine%20if%20String%20Halves%20Are%20Alike 89 | 8 | Letter Combinations of a Phone Number | https://leetcode.com/problems/letter-combinations-of-a-phone-number/ | https://youtu.be/Ydur1aYALc4 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/17.%20Letter%20Combinations%20of%20a%20Phone%20Number 90 | 9 | Verifying an Alien Dictionary | https://leetcode.com/problems/verifying-an-alien-dictionary/ | https://youtu.be/jK5a8T9q4pc | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/953.%20Verifying%20an%20Alien%20Dictionary 91 | 10 | Deepest Leaves Sum | https://leetcode.com/problems/deepest-leaves-sum/ | https://youtu.be/kgG2LuxzAHU | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1302.%20Deepest%20Leaves%20Sum 92 | 11 | Longest Increasing Path in a Matrix | https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ | https://youtu.be/WiEqhI7v2FY | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/329.%20Longest%20Increasing%20Path%20in%20a%20Matrix 93 | 12 | Beautiful Arrangement II | https://leetcode.com/problems/beautiful-arrangement-ii/ | https://youtu.be/BiQlqgmJ0BM | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/667.%20Beautiful%20Arrangement%20II 94 | 13 | Flatten Nested List Iterator | https://leetcode.com/problems/flatten-nested-list-iterator/ | https://youtu.be/V-gPWPOyq8I | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/341.%20Flatten%20Nested%20List%20Iterator 95 | 14 | Partition List | https://leetcode.com/problems/partition-list/ | https://youtu.be/b4FeEwAGDtU | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/86.%20Partition%20List 96 | 15 | Fibonacci Number | https://leetcode.com/problems/fibonacci-number/ | https://youtu.be/kIzjdvU_QIU | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/509.%20Fibonacci%20Number 97 | 16 | Remove All Adjacent Duplicates in String II | https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/ | https://youtu.be/RJpy4A7LJrs | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1209.%20Remove%20All%20Adjacent%20Duplicates%20in%20String%20II 98 | 17 | Number of Submatrices That Sum to Target | https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/ | https://youtu.be/elADMOC_hDI | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1074.%20Number%20of%20Submatrices%20That%20Sum%20to%20Target 99 | 18 | Remove Nth Node From End of List | https://leetcode.com/problems/remove-nth-node-from-end-of-list/ | https://youtu.be/Kncuqqg_I18 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/19.%20Remove%20Nth%20Node%20From%20End%20of%20List 100 | 19 | Combination Sum IV | https://leetcode.com/problems/combination-sum-iv/ | https://youtu.be/GWqe_xfqxCA | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/377.%20Combination%20Sum%20IV 101 | 20 | N-ary Tree Preorder Traversal | https://leetcode.com/problems/n-ary-tree-preorder-traversal/ | https://youtu.be/DAIN1ZzvFeA | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/589.%20N-ary%20Tree%20Preorder%20Traversal 102 | 21 | Triangle | https://leetcode.com/problems/triangle/ | https://youtu.be/O2eaAdBpZBQ | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/120.%20Triangle 103 | 22 | Brick Wall | https://leetcode.com/problems/brick-wall/ | https://youtu.be/s4pN9Qfj8EY | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/554.%20Brick%20Wall 104 | 23 | Count Binary Substrings | https://leetcode.com/problems/count-binary-substrings/ | https://youtu.be/MGPHPadxhtQ | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/696.%20Count%20Binary%20Substrings 105 | 24 | Critical Connections in a Network | https://leetcode.com/problems/critical-connections-in-a-network/ | https://youtu.be/5xUdS0hclQ4 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1192.%20Critical%20Connections%20in%20a%20Network 106 | 25 | Rotate Image | https://leetcode.com/problems/rotate-image/ | https://youtu.be/bW_9pjcXP_4 | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/48.%20Rotate%20Image 107 | 26 | Furthest Building You Can Reach | https://leetcode.com/problems/furthest-building-you-can-reach/ | https://youtu.be/wAxhnUhXvHE | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/1642.%20Furthest%20Building%20You%20Can%20Reach 108 | 27 | Power of Three | https://leetcode.com/problems/power-of-three/ | https://youtu.be/GNb8vSyw-WE | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/326.%20Power%20of%20Three 109 | 28 | Unique Paths II | https://leetcode.com/problems/unique-paths-ii/ | https://youtu.be/nZSXWXzn1aM | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/63.%20Unique%20Paths%20II 110 | 29 | Find First and Last Position of Element in Sorted Array | https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ | https://youtu.be/c_HH9sakxpY | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/34.%20Find%20First%20and%20Last%20Position%20of%20Element%20in%20Sorted%20Array 111 | 30 | Powerful Integers | https://leetcode.com/problems/powerful-integers/ | https://youtu.be/dkvMSZ1tRXo | https://github.com/Algorithms-Made-Easy/Leetcode-Challenge/blob/main/970.%20Powerful%20Integers 112 | --------------------------------------------------------------------------------