├── 2024 Leet_Code ├── 2024 Leet_program ├── 2024 code ├── Minimum_Difficulty_of_a_Job_Schedule.java └── character_string_all_equal.java ├── Arithmetic_Subarrays.java ├── Array.java ├── Binary-Tree-Inorder-Traversal.java ├── Build an Array With Stack Operations.java ├── Bus Routes.java ├── Buy_Two_Chocolates.java ├── Check_If_Two_String_Arrays_are_Equivalent.java ├── Construct-String-from-Binary-Tree.java ├── Count Nodes Equal to Average of Subtree.java ├── Count Number of Homogenous Substrings.java ├── Count-of-Matches-in-Tournament.java ├── Count_Nice_Pairs_in_an_Array.java ├── Count_Sub_Islands.java ├── Decode_Ways.java ├── Design Graph With Shortest Path Calculator.java ├── Design_a_Food_Rating_System.java ├── Determine if a Cell Is Reachable at a Given Time.java ├── Determine_if_Two_Trees_are_Identical.java ├── Diagonal_Traverse.java ├── Difference_Between_Ones_and_Zeros_in_Row_and_Column.java ├── Element-Appearing-More-Than-25%-In-Sorted-Array.java ├── Eliminate Maximum Number of Monsters.java ├── Find Mode in Binary Search Tree.java ├── Find Unique Binary String.java ├── Find the Winner of an Array Game.java ├── FindThe OriginalArray_of_Prefix_Xor.java ├── Find_Words_That_Can_Be_Formed_by_Characters.java ├── Frequency_of_the_Most_Frequent_Element.java ├── How-Many-X's.java ├── Image_Smoother.java ├── Integer_to_English_Words.java ├── Knight_Dialer.java ├── Kth_Distinct_String_in_an_Array.java ├── Largest-Odd-Number-in-String.java ├── Largest_Submatrix_With_Rearrangements.java ├── Last Moment Before All Ants Fall Out of a Plank.java ├── Leet_Code ├── Leet_Code_Leet ├── Arithmetic_Subarrays.java ├── Build an Array With Stack Operations.java ├── Bus Routes.java ├── Check_If_Two_String_Arrays_are_Equivalent.java ├── Count Nodes Equal to Average of Subtree.java ├── Count Number of Homogenous Substrings.java ├── Count_Nice_Pairs_in_an_Array.java ├── Design Graph With Shortest Path Calculator.java ├── Determine if a Cell Is Reachable at a Given Time.java ├── Diagonal_Traverse.java ├── Eliminate Maximum Number of Monsters.java ├── Find Mode in Binary Search Tree.java ├── Find Unique Binary String.java ├── Find the Winner of an Array Game.java ├── FindThe OriginalArray_of_Prefix_Xor.java ├── Frequency_of_the_Most_Frequent_Element.java ├── Largest_Submatrix_With_Rearrangements.java ├── Last Moment Before All Ants Fall Out of a Plank.java ├── Maximum_Element_After_Decreasing_and_Rearranging.java ├── Maximum_Number_of_Coins_You_Can_Get.java ├── Minimize_Maximum_Pair_Sum_in_Array.java ├── Minimum_Amount_of_Time_to_Collect_Garbage.java ├── Minimum_One_Bit_Operations_to_Make_Integers_Zero.java ├── Number_of_1_Bits.java ├── Poor Pigs.java ├── Read.md ├── Reduction_Operations_to_Make_the_Array_Elements_Equal.java ├── Restore the Array From Adjacent Pairs.java ├── Seat Reservation Manager.java ├── Solution.java ├── Solution1.java ├── Solution10.java ├── Solution11.java ├── Solution12.java ├── Solution13.java ├── Solution14.java ├── Solution2.java ├── Solution3.java ├── Solution4.java ├── Solution5.java ├── Solution6.java ├── Solution7.java ├── Solution8.java ├── Solution9.java ├── Sort Integers by The Number of 1 Bits.java ├── Sort Vowels in a String.java ├── Sum_of_Absolute_Differences_in_a_Sorted_Array.java └── Unique Length-3 Palindromic Subsequences.java ├── Magic_Squares_In_Grid.java ├── Maximum-Product-of-Two-Elements-in-an-Array.java ├── Maximum_Element_After_Decreasing_and_Rearranging.java ├── Maximum_Meetings_in_One_Room.java ├── Maximum_Number_of_Coins_You_Can_Get.java ├── Maximum_Product_Difference_Between_Two_Pairs.java ├── Minimize_Maximum_Pair_Sum_in_Array.java ├── Minimum Time to Make Rope Colorful.java ├── Minimum_Amount_of_Time_to_Collect_Garbage.java ├── Minimum_Changes_To_Make_Alternating_Binary_String.java ├── Minimum_Number_of_Pushes_to_Type_Word.java ├── Minimum_One_Bit_Operations_to_Make_Integers_Zero.java ├── Minimum_Time_Visiting_All_Points.java ├── Number-of-Dice-Rolls-With-Target-Sum.java ├── Number_of_1_Bits.java ├── Path_Crossing.java ├── Poor Pigs.java ├── Range_Sum_of_Sorted_Subarray_Sums.java ├── Reduction_Operations_to_Make_the_Array_Elements_Equal.java ├── Restore the Array From Adjacent Pairs.java ├── Seat Reservation Manager.java ├── So.java ├── Solution!.java ├── Solution.java ├── Solution1.java ├── Solution10.java ├── Solution11.java ├── Solution12.java ├── Solution13.java ├── Solution14.java ├── Solution2.java ├── Solution3.java ├── Solution4.java ├── Solution5.java ├── Solution6.java ├── Solution7.java ├── Solution8.java ├── Solution9.java ├── Sort Integers by The Number of 1 Bits.java ├── Sort Vowels in a String.java ├── Special_Positions_in_a_Binary_Matrix.java ├── Spiral_Matrix_III.java ├── String_Compression.java ├── Sum-string.java ├── Sum_of_Absolute_Differences_in_a_Sorted_Array.java ├── Transpose_Matrix.java ├── Unique Length-3 Palindromic Subsequences.java ├── Valid_Anagram.java └── Widest_Vertical_Area_Between_Two_Points_Containing_No _Points.java /2024 Leet_Code: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /2024 Leet_program/2024 code: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /2024 Leet_program/Minimum_Difficulty_of_a_Job_Schedule.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | import java.util.Vector; 4 | 5 | class Solution { 6 | public int minDifficulty(List jobDifficulty, int d) { 7 | int n = jobDifficulty.size(); 8 | if (n < d) { 9 | return -1; 10 | } else if (n == d) { 11 | int totalDifficulty = 0; 12 | for (int difficulty : jobDifficulty) { 13 | totalDifficulty += difficulty; 14 | } 15 | return totalDifficulty; 16 | } 17 | 18 | // dp[j]: the minimum difficulty of the first (j+1) jobs, exactly scheduled in 19 | // (i+1) days 20 | int[] dp = new int[n]; 21 | Arrays.fill(dp, Integer.MAX_VALUE); 22 | dp[0] = jobDifficulty.get(0); 23 | 24 | // Initializing the dp array to store the maximum difficulty encountered so far 25 | for (int i = 1; i < n; i++) { 26 | dp[i] = Math.max(dp[i - 1], jobDifficulty.get(i)); 27 | } 28 | 29 | int[] dpPrev = new int[n]; 30 | 31 | // Dynamic Programming to find the minimum difficulty 32 | for (int i = 1; i < d; i++) { 33 | int[] temp = dpPrev; 34 | dpPrev = dp; 35 | dp = temp; 36 | for (int j = i; j < n; j++) { 37 | int lastDayDifficulty = jobDifficulty.get(j); 38 | int tmpMin = lastDayDifficulty + dpPrev[j - 1]; 39 | 40 | // Iterate to find the minimum difficulty for the current day 41 | for (int t = j - 1; t >= i - 1; t--) { 42 | lastDayDifficulty = Math.max(lastDayDifficulty, jobDifficulty.get(t)); 43 | tmpMin = Math.min(tmpMin, lastDayDifficulty + dpPrev[t - 1]); 44 | } 45 | 46 | dp[j] = tmpMin; 47 | } 48 | } 49 | 50 | return dp[n - 1]; 51 | } 52 | } -------------------------------------------------------------------------------- /2024 Leet_program/character_string_all_equal.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class character_string_all_equal { 5 | public boolean makeEqual(String[] words) { 6 | int length = words.length; 7 | Map charCount = new HashMap<>(); 8 | for (String word : words) { 9 | for (char c : word.toCharArray()) { 10 | charCount.put(c, charCount.getOrDefault(c, 0) + 1); 11 | } 12 | } 13 | for (int count : charCount.values()) { 14 | if (count % length != 0) { 15 | return false; 16 | } 17 | } 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Arithmetic_Subarrays.java: -------------------------------------------------------------------------------- 1 | public class Arithmetic_Subarrays { 2 | 3 | public List checkArithmeticSubarrays(int[] nums, int[] l, int[] r) { 4 | List result = new ArrayList<>(l.length); 5 | for (int i = 0; i < l.length; i++) { 6 | result.add(isArithmetic(nums, l[i], r[i])); 7 | } 8 | return result; 9 | } 10 | 11 | 12 | public boolean isArithmetic(int [] nums, int l, int r){ 13 | int max = Integer.MIN_VALUE; 14 | int min = Integer.MAX_VALUE; 15 | 16 | for (int i = l; i <= r; i++) { 17 | max = Math.max(nums[i],max); // max of nums 18 | min = Math.min(nums[i],min); // min of nums 19 | } 20 | 21 | int len = r -l +1; 22 | // if (max-min)/(length-1) yields remainder = 0 => AP 23 | // else => Not an AP 24 | 25 | if((max-min)%(len-1) !=0) 26 | return false; 27 | 28 | int diff = (max-min)/(len-1); 29 | if(diff == 0) 30 | return true; 31 | 32 | boolean [] visited = new boolean[len]; 33 | 34 | for (int i = l; i <= r; i++) { 35 | int val = nums[i]; 36 | if((val - min)% diff != 0) // checking remainder wrt min 37 | return false; 38 | else { 39 | int pos = (val - min) / diff; 40 | if(visited[pos]) // If node is visited, then it means repeatition of numbers 41 | return false; 42 | visited[pos] = true; // If node isn't visited yet, marked it visited 43 | } 44 | } 45 | return true; 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /Array.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Array { 4 | 5 | int sumOfDependencies(ArrayList> adj, int V) { 6 | // code here 7 | int count = 0; 8 | for (int i = 0; i < adj.size(); i++) { 9 | count += adj.get(i).size(); 10 | } 11 | return count; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Binary-Tree-Inorder-Traversal.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List inorderTraversal(TreeNode root) { 3 | List res = new ArrayList<>(); 4 | helper(root, res); 5 | return res; 6 | } 7 | 8 | public void helper(TreeNode root, List res) { 9 | if (root != null) { 10 | helper(root.left, res); 11 | res.add(root.val); 12 | helper(root.right, res); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Build an Array With Stack Operations.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List buildArray(int[] target, int n) { 3 | List list = new ArrayList<>(); 4 | int count = 0; 5 | for (int i = 1; i <= n; i++) { 6 | if (count == target.length) { 7 | break; 8 | } 9 | list.add("Push"); 10 | if (target[count++] != i) { 11 | list.add("Pop"); 12 | count--; 13 | } 14 | } 15 | return list; 16 | } 17 | } -------------------------------------------------------------------------------- /Bus Routes.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numBusesToDestination(int[][] routes, int source, int target) { 3 | // Edge Case 4 | if (source == target) 5 | return 0; 6 | 7 | // Garph Building 8 | // Key:- the Station 9 | // Value:- Buses can be taken in this stations 10 | Map> map = new HashMap<>(); 11 | for (int i = 0; i < routes.length; i++) { 12 | for (int stop : routes[i]) { 13 | map.putIfAbsent(stop, new ArrayList<>()); 14 | map.get(stop).add(i); 15 | } 16 | } 17 | 18 | Queue q = new ArrayDeque<>(); 19 | Set vis = new HashSet<>(); 20 | 21 | q.offer(source); 22 | int count = 0; 23 | 24 | while (!q.isEmpty()) { 25 | int size = q.size(); 26 | 27 | for (int i = 0; i < size; i++) { 28 | ArrayList buses = map.get(q.poll()); 29 | for (int bus : buses) { 30 | if (vis.contains(bus)) { 31 | continue; 32 | } 33 | 34 | vis.add(bus); 35 | for (int stop : routes[bus]) { 36 | if (stop == target) 37 | return count + 1; 38 | q.offer(stop); 39 | } 40 | } 41 | } 42 | count++; 43 | } 44 | 45 | return -1; 46 | } 47 | } -------------------------------------------------------------------------------- /Buy_Two_Chocolates.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int buyChoco(int[] arr, int key) { 3 | 4 | int ans = Integer.MAX_VALUE; 5 | int fin; 6 | for (int i = 0; i < arr.length; i++) { 7 | for (int j = 0; j < arr.length; j++) { 8 | if (i != j) { 9 | int sum = arr[i] + arr[j]; 10 | ans = Math.min(ans, sum); 11 | } 12 | } 13 | } 14 | 15 | fin = key - ans; 16 | if (fin >= 0) { 17 | return fin; 18 | } else { 19 | return key; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Check_If_Two_String_Arrays_are_Equivalent.java: -------------------------------------------------------------------------------- 1 | public class Check_If_Two_String_Arrays_are_Equivalent { 2 | public boolean arrayStringsAreEqual(String[] word1, String[] word2) { 3 | if (word1.length == 0 || word2.length == 0) 4 | return false; 5 | return String.join("", word1).equals(String.join("", word2)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Construct-String-from-Binary-Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String tree2str(TreeNode root) { 3 | if (root == null) { 4 | return ""; 5 | } 6 | 7 | // Step 1: Start with an empty result string 8 | StringBuilder result = new StringBuilder(); 9 | 10 | // Step 2: Perform preorder traversal 11 | preorderTraversal(root, result); 12 | 13 | // Step 3: Return the final result string 14 | return result.toString(); 15 | } 16 | 17 | private void preorderTraversal(TreeNode node, StringBuilder result) { 18 | if (node == null) { 19 | return; 20 | } 21 | 22 | // Step 4: Append the current node's value to the result 23 | result.append(node.val); 24 | 25 | // Step 5: Check if the current node has a left child or a right child 26 | if (node.left != null || node.right != null) { 27 | 28 | // Step 6: If there is a left child, add empty parentheses for it 29 | result.append("("); 30 | preorderTraversal(node.left, result); 31 | result.append(")"); 32 | } 33 | 34 | // Step 7: If there is a right child, process it similarly 35 | if (node.right != null) { 36 | result.append("("); 37 | preorderTraversal(node.right, result); 38 | result.append(")"); 39 | } 40 | 41 | // Step 8: The recursion will handle all the child nodes 42 | } 43 | } -------------------------------------------------------------------------------- /Count Nodes Equal to Average of Subtree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private int res = 0; 3 | 4 | public int averageOfSubtree(TreeNode root) { 5 | postorder(root); 6 | return res; 7 | } 8 | 9 | private int[] postorder(TreeNode node) { 10 | if (node == null) { 11 | return new int[] { 0, 0 }; // sum, number of nodes 12 | } 13 | 14 | int[] left = postorder(node.left); 15 | int[] right = postorder(node.right); 16 | 17 | int totalSum = left[0] + right[0] + node.val; 18 | int totalCount = 1 + left[1] + right[1]; 19 | res += (node.val == totalSum / totalCount ? 1 : 0); 20 | 21 | return new int[] { totalSum, totalCount }; 22 | } 23 | } -------------------------------------------------------------------------------- /Count Number of Homogenous Substrings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countHomogenous(String s) { 3 | var prev = '?'; 4 | var cnt = 1; 5 | var sum = 0; 6 | 7 | for (var c : s.toCharArray()) { 8 | if (c != prev) { 9 | cnt = 1; 10 | prev = c; 11 | } 12 | sum = (sum + cnt++) % 1000000007; 13 | } 14 | return sum; 15 | } 16 | } -------------------------------------------------------------------------------- /Count-of-Matches-in-Tournament.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfMatches(int n) { 3 | int count = 0; 4 | 5 | while (n > 1) { 6 | int x = n % 2; 7 | if ((n - x) % 2 == 0) { 8 | n = n / 2; 9 | count += n; 10 | } 11 | n += x; 12 | } 13 | return count; 14 | } 15 | } -------------------------------------------------------------------------------- /Count_Nice_Pairs_in_an_Array.java: -------------------------------------------------------------------------------- 1 | public class Count_Nice_Pairs_in_an_Array { 2 | 3 | int reverse(int num) { 4 | int rev = 0; 5 | while (num > 0) { 6 | rev = rev * 10 + num % 10; 7 | num /= 10; 8 | } 9 | return rev; 10 | } 11 | 12 | public int countNicePairs(int[] nums) { 13 | final int mod = 1000000007; 14 | 15 | int len = nums.length; 16 | for (int i = 0; i < len; i++) 17 | nums[i] = nums[i] - reverse(nums[i]); 18 | Arrays.sort(nums); 19 | long res = 0; 20 | for (int i = 0; i < len - 1; i++) { 21 | long cont = 1; 22 | while (i < len - 1 && nums[i] == nums[i + 1]) { 23 | cont++; 24 | i++; 25 | } 26 | res = (res % mod + (cont * (cont - 1)) / 2) % mod; 27 | } 28 | return (int) res % mod; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Count_Sub_Islands.java: -------------------------------------------------------------------------------- 1 | package Auguest; 2 | 3 | public class Count_Sub_Islands { 4 | public void dfs(int[][] grid1, int[][] grid2, int i, int j) { 5 | // If the current position is out of bounds or already visited (grid2[i][j] == 6 | // 0), return 7 | if (i < 0 || i == m || j < 0 || j == n || grid2[i][j] == 0) 8 | return; 9 | 10 | // If the current cell in grid2 is land but not in grid1, mark this island as 11 | // not a sub-island 12 | if (grid1[i][j] != grid2[i][j]) { 13 | isSubIsland = false; 14 | } 15 | 16 | // Mark the current cell as visited by setting grid2[i][j] to 0 17 | grid2[i][j] = 0; 18 | 19 | // Continue the DFS in all four directions 20 | dfs(grid1, grid2, i + 1, j); // Down 21 | dfs(grid1, grid2, i - 1, j); // Up 22 | dfs(grid1, grid2, i, j + 1); // Right 23 | dfs(grid1, grid2, i, j - 1); // Left 24 | } 25 | 26 | public int countSubIslands(int[][] grid1, int[][] grid2) { 27 | m = grid1.length; // Number of rows in the grid 28 | n = grid1[0].length; // Number of columns in the grid 29 | 30 | int subIslandCount = 0; // To store the count of sub-islands 31 | 32 | // Iterate through each cell in grid2 33 | for (int i = 0; i < m; i++) { 34 | for (int j = 0; j < n; j++) { 35 | // If the cell is land in grid2, it could be part of a sub-island 36 | if (grid2[i][j] == 1) { 37 | isSubIsland = true; // Start assuming this is a sub-island 38 | dfs(grid1, grid2, i, j); // Perform DFS to check the whole island 39 | 40 | // If the flag remains true after DFS, it means this island is a sub-island 41 | if (isSubIsland) { 42 | subIslandCount++; // Increment the count of sub-islands 43 | } 44 | } 45 | } 46 | } 47 | 48 | return subIslandCount; // Return the total count of sub-islands 49 | } 50 | 51 | public static void main(String[] args) { 52 | 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Decode_Ways.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isValid(int code, int len) { 3 | if (len == 1) { 4 | return code >= 1 && code <= 26; 5 | } else { 6 | return code >= 10 && code <= 26; 7 | } 8 | } 9 | 10 | public int countOfDecoding(int i, String s, int[] dp) { 11 | if (i >= s.length()) { 12 | return 1; 13 | } 14 | if (dp[i] != -1) { 15 | return dp[i]; 16 | } 17 | dp[i] = 0; 18 | if (isValid(s.charAt(i) - '0', 1)) { 19 | dp[i] += countOfDecoding(i + 1, s, dp); 20 | } 21 | if (i < s.length() - 1 && isValid((s.charAt(i) - '0') * 10 + s.charAt(i + 1) - '0', 2)) { 22 | dp[i] += countOfDecoding(i + 2, s, dp); 23 | } 24 | return dp[i]; 25 | } 26 | 27 | public int numDecodings(String s) { 28 | int[] dp = new int[s.length()]; 29 | Arrays.fill(dp, -1); 30 | return countOfDecoding(0, s, dp); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Design Graph With Shortest Path Calculator.java: -------------------------------------------------------------------------------- 1 | class Graph { 2 | List> adj = new ArrayList<>(); 3 | int n; 4 | 5 | public Graph(int n, int[][] edges) { 6 | for (int i = 0; i < n; i++) { 7 | adj.add(new ArrayList<>()); 8 | } 9 | this.n = n; 10 | for (var edge : edges) { 11 | adj.get(edge[0]).add(new int[] { edge[1], edge[2] }); 12 | } 13 | } 14 | 15 | public void addEdge(int[] edge) { 16 | adj.get(edge[0]).add(new int[] { edge[1], edge[2] }); 17 | } 18 | 19 | public int shortestPath(int node1, int node2) { 20 | int[] distance = new int[n + 1]; 21 | Arrays.fill(distance, Integer.MAX_VALUE); 22 | 23 | distance[node1] = 0; 24 | 25 | PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); 26 | pq.add(new int[] { node1, 0 }); 27 | while (!pq.isEmpty()) { 28 | int temp = pq.poll()[0]; 29 | 30 | for (int[] i : adj.get(temp)) { 31 | int x = i[0]; 32 | int y = i[1]; 33 | 34 | if (distance[x] > distance[temp] + y) { 35 | distance[x] = distance[temp] + y; 36 | pq.add(new int[] { x, distance[x] }); 37 | } 38 | } 39 | } 40 | 41 | if (distance[node2] == Integer.MAX_VALUE) { 42 | return -1; 43 | } 44 | return distance[node2]; 45 | } 46 | } 47 | 48 | /** 49 | * Your Graph object will be instantiated and called as such: 50 | * Graph obj = new Graph(n, edges); 51 | * obj.addEdge(edge); 52 | * int param_2 = obj.shortestPath(node1,node2); 53 | */ -------------------------------------------------------------------------------- /Design_a_Food_Rating_System.java: -------------------------------------------------------------------------------- 1 | class FoodRatings { 2 | public class Info { 3 | String food; 4 | String cuisine; 5 | int rating; 6 | 7 | public Info(String food, String cuisine, int rating) { 8 | this.food = food; 9 | this.cuisine = cuisine; 10 | this.rating = rating; 11 | } 12 | } 13 | 14 | Map> cuisineMap; 15 | Map foodMap; 16 | 17 | public FoodRatings(String[] foods, String[] cuisines, int[] ratings) { 18 | cuisineMap = new HashMap<>(); 19 | foodMap = new HashMap<>(); 20 | for (int i = 0; i < foods.length; i++) { 21 | Info combo = new Info(foods[i], cuisines[i], ratings[i]); 22 | foodMap.put(foods[i], combo); 23 | if (cuisineMap.containsKey(cuisines[i])) { 24 | cuisineMap.get(cuisines[i]).add(combo); 25 | } else { 26 | PriorityQueue pq = new PriorityQueue(new Comparator() { 27 | @Override 28 | public int compare(Info a, Info b) { 29 | int result = b.rating - a.rating; 30 | if (result == 0) { 31 | return (a.food).compareTo(b.food); 32 | } 33 | return result; 34 | } 35 | }); 36 | pq.add(combo); 37 | cuisineMap.put(cuisines[i], pq); 38 | } 39 | } 40 | } 41 | 42 | public void changeRating(String food, int newRating) { 43 | Info prev = foodMap.get(food); 44 | Info curr = new Info(food, prev.cuisine, newRating); 45 | foodMap.put(food, curr); 46 | prev.food = ""; 47 | cuisineMap.get(prev.cuisine).add(curr); 48 | 49 | } 50 | 51 | public String highestRated(String cuisine) { 52 | while (cuisineMap.get(cuisine).peek().food.equals("")) { 53 | cuisineMap.get(cuisine).remove(); 54 | } 55 | return cuisineMap.get(cuisine).peek().food; 56 | 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /Determine if a Cell Is Reachable at a Given Time.java: -------------------------------------------------------------------------------- 1 | { 2 | public boolean isReachableAtTime(int sx, int sy, int fx, int fy, int t) { 3 | if(sx==fx && sy==fy) { 4 | return t!=1; 5 | } 6 | return Math.max(Math.abs(sx-fx), Math.abs(sy-fy))<=t; 7 | } 8 | } -------------------------------------------------------------------------------- /Determine_if_Two_Trees_are_Identical.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to check if two trees are identical. 3 | boolean isIdentical(Node root1, Node root2) { 4 | // Code Here 5 | if (root1 == null || root2 == null) 6 | return root1 == root2; 7 | if (root1.data != root2.data) 8 | return false; 9 | 10 | return isIdentical(root1.left, root2.left) && isIdentical(root1.right, root2.right); 11 | 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /Diagonal_Traverse.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findDiagonalOrder(List> nums) { 3 | int count = 0; 4 | 5 | List> lists = new ArrayList<>(); 6 | for (int i = 0; i < nums.size(); i++) { 7 | List row = nums.get(i); 8 | 9 | for (int j = 0; j < row.size(); j++) { 10 | int idx = i + j; 11 | 12 | if (lists.size() < idx + 1) { 13 | lists.add(new ArrayList<>()); 14 | } 15 | lists.get(idx).add(row.get(j)); 16 | 17 | count++; 18 | } 19 | } 20 | 21 | int[] res = new int[count]; 22 | int idx = 0; 23 | for (List list : lists) { 24 | for (int i = list.size() - 1; i >= 0; i--) { 25 | res[idx++] = list.get(i); 26 | } 27 | } 28 | return res; 29 | } 30 | } -------------------------------------------------------------------------------- /Difference_Between_Ones_and_Zeros_in_Row_and_Column.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] onesMinusZeros(int[][] grid) { 3 | int[] rowOnes = new int[grid.length]; 4 | int[] colOnes = new int[grid[0].length]; 5 | for (int i = 0; i < grid.length; i++) { 6 | for (int j = 0; j < grid[0].length; j++) { 7 | rowOnes[i] += grid[i][j]; 8 | colOnes[j] += grid[i][j]; 9 | } 10 | } 11 | for (int i = 0; i < grid.length; i++) { 12 | for (int j = 0; j < grid[0].length; j++) { 13 | grid[i][j] = 2 * (rowOnes[i] + colOnes[j]) - grid.length - grid[0].length; 14 | } 15 | } 16 | 17 | return grid; 18 | } 19 | } -------------------------------------------------------------------------------- /Element-Appearing-More-Than-25%-In-Sorted-Array.java: -------------------------------------------------------------------------------- 1 | public class Element-Appearing-More-Than-25%-In-Sorted-Array 2 | { 3 | 4 | public int findSpecialInteger(int[] arr) { 5 | int size = arr.length; 6 | int qtr = size / 4; 7 | int cnt = 1; 8 | int p = arr[0]; 9 | for (int i = 1 ; i < arr.length ; i++) { 10 | 11 | if ( p == arr[i]) cnt++; 12 | else cnt = 1; 13 | 14 | if (cnt > qtr) return arr[i]; 15 | 16 | p = arr[i]; 17 | } 18 | 19 | return p; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Eliminate Maximum Number of Monsters.java: -------------------------------------------------------------------------------- 1 | public class Eliminate 2 | Maximum Number 3 | of Monsters 4 | { 5 | 6 | public int eliminateMaximum(int[] dist, int[] speed) { 7 | int n = dist.length; 8 | double[] monstArrivalTime = new double[n]; 9 | 10 | // Finding the arrival time of monster based on formula 11 | // (Time = Distance / Speed) 12 | for (int i = 0; i < n; i++) { 13 | monstArrivalTime[i] = ((double) (dist[i]) / (double) speed[i]); 14 | } 15 | 16 | // Sorting the arrival time of monster that helps in determining 17 | // the maximum monster to eliminate 18 | Arrays.sort(monstArrivalTime); 19 | int res = 0; 20 | double stick = 0.0; 21 | 22 | // Checking what monster arrive at what time and how much monster 23 | // I can eliminate 24 | for (int i = 0; i < n; i++) { 25 | if (stick < monstArrivalTime[i]) { 26 | res++; 27 | stick++; 28 | } else { 29 | break; 30 | } 31 | } 32 | return res; 33 | } 34 | }} 35 | -------------------------------------------------------------------------------- /Find Mode in Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findMode(TreeNode root) { 3 | Map counts = new HashMap<>(); 4 | int[] maxCount = { 0 }; // Using an array to simulate nonlocal 5 | List modes = new ArrayList<>(); 6 | 7 | inorder(root, counts, maxCount, modes); 8 | 9 | int[] result = new int[modes.size()]; 10 | for (int i = 0; i < modes.size(); i++) { 11 | result[i] = modes.get(i); 12 | } 13 | 14 | return result; 15 | } 16 | 17 | private void inorder(TreeNode node, Map counts, int[] maxCount, List modes) { 18 | if (node == null) { 19 | return; 20 | } 21 | 22 | inorder(node.left, counts, maxCount, modes); 23 | 24 | int count = counts.getOrDefault(node.val, 0) + 1; 25 | counts.put(node.val, count); 26 | 27 | if (count > maxCount[0]) { 28 | maxCount[0] = count; 29 | modes.clear(); 30 | modes.add(node.val); 31 | } else if (count == maxCount[0]) { 32 | modes.add(node.val); 33 | } 34 | 35 | inorder(node.right, counts, maxCount, modes); 36 | } 37 | } -------------------------------------------------------------------------------- /Find Unique Binary String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String findDifferentBinaryString(String[] nums) { 3 | StringBuilder sb = new StringBuilder(); 4 | 5 | for (int i = 0; i < nums.length; i++) { 6 | sb.append(nums[i].charAt(i) == '0' ? "1" : "0"); 7 | } 8 | return sb.toString(); 9 | } 10 | } -------------------------------------------------------------------------------- /Find the Winner of an Array Game.java: -------------------------------------------------------------------------------- 1 | public class Find 2 | the Winner 3 | of an 4 | Array Game 5 | { 6 | 7 | public int getWinner(int[] arr, int k) { 8 | int winner = arr[0]; 9 | int wins = 0; 10 | 11 | for (int i = 1; i < arr.length; i++) { 12 | if (winner > arr[i]) 13 | wins++; 14 | else { 15 | wins = 1; 16 | winner = arr[i]; 17 | } 18 | 19 | if (wins == k) 20 | break; 21 | } 22 | 23 | return winner; 24 | } 25 | }} 26 | -------------------------------------------------------------------------------- /FindThe OriginalArray_of_Prefix_Xor.java: -------------------------------------------------------------------------------- 1 | public class FindThe OriginalArray_of_Prefix_Xor{ 2 | 3 | public int[] findArray(int[] pref) { 4 | int[] result = new int[pref.length]; 5 | result[0] = pref[0]; 6 | for (int i = 1; i < pref.length; i++) { 7 | result[i] = pref[i] ^ pref[i - 1]; 8 | } 9 | return result; 10 | } 11 | } -------------------------------------------------------------------------------- /Find_Words_That_Can_Be_Formed_by_Characters.java: -------------------------------------------------------------------------------- 1 | public class Find_Words_That_Can_Be_Formed_by_Characters { 2 | public int countCharacters(String[] words, String chars) { 3 | int[] counts = new int[26]; 4 | // Step 1: Initialize Character Counts Array 5 | for (int i = 0; i < chars.length(); i++) { 6 | counts[chars.charAt(i) - 'a']++; 7 | } 8 | int res = 0; 9 | // Step 3: Check Words 10 | for (String s : words) { 11 | if (canForm(s, counts)) 12 | // Step 4: Calculate Lengths 13 | res += s.length(); 14 | } 15 | return res; 16 | } 17 | 18 | boolean canForm(String word, int[] counts) { 19 | int[] c = new int[26]; 20 | // Step 2: Update Counts Array 21 | for (int i = 0; i < word.length(); i++) { 22 | int x = word.charAt(i) - 'a'; 23 | c[x]++; 24 | if (c[x] > counts[x]) 25 | return false; 26 | } 27 | return true; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Frequency_of_the_Most_Frequent_Element.java: -------------------------------------------------------------------------------- 1 | public class Frequency_of_the_Most_Frequent_Element { 2 | public int maxFrequency(int[] nums, int k) { 3 | int maxFrequency = 0; // Initialize the maximum frequency 4 | long currentSum = 0; // Initialize the current sum of the subarray elements 5 | 6 | Arrays.sort(nums); // Sort the array in ascending order 7 | 8 | for (int left = 0, right = 0; right < nums.length; ++right) { 9 | currentSum += nums[right]; // Include the current element in the subarray sum 10 | 11 | // Check if the current subarray violates the condition (sum + k < nums[right] * 12 | // length) 13 | while (currentSum + k < (long) nums[right] * (right - left + 1)) { 14 | currentSum -= nums[left]; // Adjust the subarray sum by removing the leftmost element 15 | left++; // Move the left pointer to the right 16 | } 17 | 18 | // Update the maximum frequency based on the current subarray length 19 | maxFrequency = Math.max(maxFrequency, right - left + 1); 20 | } 21 | 22 | return maxFrequency; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /How-Many-X's.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | int countX(int L, int R, int X) { 4 | 5 | // code here 6 | 7 | // code here 8 | 9 | int count = 0; 10 | 11 | for (int a = L + 1; a < R; a++) { 12 | 13 | int temp = a; // Temporary variable to extract digits 14 | 15 | while (temp > 0) { 16 | 17 | int lastDigit = temp % 10; // found the last digit 18 | 19 | if (lastDigit == X) { 20 | 21 | count++; 22 | 23 | } 24 | 25 | temp /= 10;// reduce the digit 2 digit tha to ek digit hoga 26 | 27 | } 28 | 29 | } 30 | 31 | return count; 32 | 33 | } 34 | 35 | }; -------------------------------------------------------------------------------- /Image_Smoother.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] imageSmoother(int[][] img) { 3 | int rows = img.length; 4 | int cols = img[0].length; 5 | int[][] result = new int[rows][cols]; 6 | 7 | for (int i = 0; i < rows; ++i) { 8 | for (int j = 0; j < cols; ++j) { 9 | int totalSum = 0; 10 | int count = 0; 11 | 12 | for (int x = Math.max(0, i-1); x < Math.min(rows, i+2); ++x) { 13 | for (int y = Math.max(0, j-1); y < Math.min(cols, j+2); ++y) { 14 | totalSum += img[x][y]; 15 | count += 1; 16 | } 17 | } 18 | 19 | result[i][j] = totalSum / count; 20 | } 21 | } 22 | 23 | return result; 24 | } 25 | } -------------------------------------------------------------------------------- /Integer_to_English_Words.java: -------------------------------------------------------------------------------- 1 | package Auguest; 2 | 3 | import java.util.*; 4 | 5 | public class Integer_to_English_Words { 6 | public String numberToWords(int num) { 7 | if (num == 0) 8 | return "Zero"; 9 | String[] bigString = new String[] { "Thousand", "Million", "Billion" }; 10 | String result = numberToWordsHelper(num % 1000); 11 | num = num / 1000; 12 | if (num > 0 && num % 1000 > 0) { 13 | result = numberToWordsHelper(num % 1000) + "Thousand " + result; 14 | } 15 | num = num / 1000; 16 | if (num > 0 && num % 1000 > 0) { 17 | result = numberToWordsHelper(num % 1000) + "Million " + result; 18 | } 19 | num = num / 1000; 20 | if (num > 0) { 21 | result = numberToWordsHelper(num % 1000) + "Billion " + result; 22 | } 23 | return result.trim(); 24 | } 25 | 26 | public String numberToWordsHelper(int num) { 27 | String[] digitString = new String[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", 28 | "Nine" }; 29 | String[] teenString = new String[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", 30 | "Seventeen", "Eighteen", "Nineteen" }; 31 | String[] tenString = new String[] { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", 32 | "Eighty", "Ninety" }; 33 | String result = ""; 34 | if (num > 99) { 35 | result += digitString[num / 100] + " Hundred "; 36 | } 37 | num = num % 100; 38 | if (num < 20 && num > 9) { 39 | result += teenString[num % 10] + " "; 40 | } else { 41 | if (num > 19) { 42 | result += tenString[num / 10] + " "; 43 | } 44 | num = num % 10; 45 | if (num > 0) 46 | result += digitString[num] + " "; 47 | } 48 | return result; 49 | } 50 | 51 | public static void main(String[] args) { 52 | 53 | } 54 | } -------------------------------------------------------------------------------- /Knight_Dialer.java: -------------------------------------------------------------------------------- 1 | public class Knight_Dialer { 2 | static final int mod = (int) 1e9 + 7; 3 | static final int[][] MOVES = { 4 | /* 0 */ { 4, 6 }, 5 | /* 1 */ { 6, 8 }, 6 | /* 2 */ { 7, 9 }, 7 | /* 3 */ { 4, 8 }, 8 | /* 4 */ { 0, 3, 9 }, 9 | /* 5 */ {}, 10 | /* 6 */ { 0, 1, 7 }, 11 | /* 7 */ { 2, 6 }, 12 | /* 8 */ { 1, 3 }, 13 | /* 9 */ { 2, 4 } 14 | }; 15 | static final int[][] cache = new int[5001][10]; 16 | 17 | public int knightDialer(int n) { 18 | return knightDialer(n, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); 19 | } 20 | 21 | int knightDialer(int remaining, int[] nextNumbers) { 22 | if (remaining == 1) 23 | return nextNumbers.length; 24 | int count = 0; 25 | 26 | for (int nextNumber : nextNumbers) { 27 | int cur = cache[remaining][nextNumber]; 28 | if (cur == 0) { 29 | cur = knightDialer(remaining - 1, MOVES[nextNumber]); 30 | cache[remaining][nextNumber] = cur; 31 | } 32 | count += cur; 33 | count %= mod; 34 | } 35 | return count; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Kth_Distinct_String_in_an_Array.java: -------------------------------------------------------------------------------- 1 | package Auguest; 2 | 3 | import java.util.*; 4 | 5 | public class Kth_Distinct_String_in_an_Array { 6 | public String kthDistinct(String[] arr, int k) { 7 | Map counter = new HashMap<>(); 8 | for (String v : arr) { 9 | counter.put(v, counter.getOrDefault(v, 0) + 1); 10 | } 11 | for (String v : arr) { 12 | if (counter.get(v) == 1) { 13 | --k; 14 | if (k == 0) { 15 | return v; 16 | } 17 | } 18 | } 19 | return ""; 20 | } 21 | 22 | public static void main(String[] args) { 23 | 24 | } 25 | } -------------------------------------------------------------------------------- /Largest-Odd-Number-in-String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String largestOddNumber(String num) { 3 | if ((int) num.charAt(num.length() - 1) % 2 == 1) 4 | return num; 5 | int i = num.length() - 1; 6 | while (i >= 0) { 7 | int n = num.charAt(i); 8 | if (n % 2 == 1) 9 | return num.substring(0, i + 1); 10 | i--; 11 | } 12 | return ""; 13 | } 14 | } -------------------------------------------------------------------------------- /Largest_Submatrix_With_Rearrangements.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Largest_Submatrix_With_Rearrangements { 4 | public int largestSubmatrix(int[][] matrix) { 5 | int m = matrix.length, n = matrix[0].length; 6 | for (int i = 1; i < m; ++i) { 7 | for (int j = 0; j < n; ++j) { 8 | if (matrix[i][j] == 1) { 9 | matrix[i][j] = matrix[i - 1][j] + 1; 10 | } 11 | } 12 | } 13 | int ans = 0; 14 | for (var row : matrix) { 15 | Arrays.sort(row); 16 | for (int j = n - 1, k = 1; j >= 0 && row[j] > 0; --j, ++k) { 17 | int s = row[j] * k; 18 | ans = Math.max(ans, s); 19 | } 20 | } 21 | return ans; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Last Moment Before All Ants Fall Out of a Plank.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int getLastMoment(int n, int[] left, int[] right) { 3 | // Initialize a variable to keep track of the maximum time 4 | int time = 0; 5 | 6 | // Iterate through the positions of ants moving to the left 7 | for (int pos : left) { 8 | // Update the maximum time if the current left-moving ant's position is greater 9 | // than the previously recorded maximum time 10 | time = Math.max(time, pos); 11 | } 12 | 13 | // Iterate through the positions of ants moving to the right 14 | for (int pos : right) { 15 | // Update the maximum time if the current right-moving ant's position (relative to 16 | // the right end of the plank) is greater than the previously recorded maximum time 17 | time = Math.max(time, n - pos); 18 | } 19 | 20 | // The final 'time' variable contains the maximum time, which is when the last ant(s) 21 | // fall off the plank, so return it as the result. 22 | return time; 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /Leet_Code: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Arithmetic_Subarrays.java: -------------------------------------------------------------------------------- 1 | public class Arithmetic_Subarrays { 2 | 3 | public List checkArithmeticSubarrays(int[] nums, int[] l, int[] r) { 4 | List result = new ArrayList<>(l.length); 5 | for (int i = 0; i < l.length; i++) { 6 | result.add(isArithmetic(nums, l[i], r[i])); 7 | } 8 | return result; 9 | } 10 | 11 | 12 | public boolean isArithmetic(int [] nums, int l, int r){ 13 | int max = Integer.MIN_VALUE; 14 | int min = Integer.MAX_VALUE; 15 | 16 | for (int i = l; i <= r; i++) { 17 | max = Math.max(nums[i],max); // max of nums 18 | min = Math.min(nums[i],min); // min of nums 19 | } 20 | 21 | int len = r -l +1; 22 | // if (max-min)/(length-1) yields remainder = 0 => AP 23 | // else => Not an AP 24 | 25 | if((max-min)%(len-1) !=0) 26 | return false; 27 | 28 | int diff = (max-min)/(len-1); 29 | if(diff == 0) 30 | return true; 31 | 32 | boolean [] visited = new boolean[len]; 33 | 34 | for (int i = l; i <= r; i++) { 35 | int val = nums[i]; 36 | if((val - min)% diff != 0) // checking remainder wrt min 37 | return false; 38 | else { 39 | int pos = (val - min) / diff; 40 | if(visited[pos]) // If node is visited, then it means repeatition of numbers 41 | return false; 42 | visited[pos] = true; // If node isn't visited yet, marked it visited 43 | } 44 | } 45 | return true; 46 | } 47 | } 48 | 49 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Build an Array With Stack Operations.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List buildArray(int[] target, int n) { 3 | List list = new ArrayList<>(); 4 | int count = 0; 5 | for (int i = 1; i <= n; i++) { 6 | if (count == target.length) { 7 | break; 8 | } 9 | list.add("Push"); 10 | if (target[count++] != i) { 11 | list.add("Pop"); 12 | count--; 13 | } 14 | } 15 | return list; 16 | } 17 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Bus Routes.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numBusesToDestination(int[][] routes, int source, int target) { 3 | // Edge Case 4 | if (source == target) 5 | return 0; 6 | 7 | // Garph Building 8 | // Key:- the Station 9 | // Value:- Buses can be taken in this stations 10 | Map> map = new HashMap<>(); 11 | for (int i = 0; i < routes.length; i++) { 12 | for (int stop : routes[i]) { 13 | map.putIfAbsent(stop, new ArrayList<>()); 14 | map.get(stop).add(i); 15 | } 16 | } 17 | 18 | Queue q = new ArrayDeque<>(); 19 | Set vis = new HashSet<>(); 20 | 21 | q.offer(source); 22 | int count = 0; 23 | 24 | while (!q.isEmpty()) { 25 | int size = q.size(); 26 | 27 | for (int i = 0; i < size; i++) { 28 | ArrayList buses = map.get(q.poll()); 29 | for (int bus : buses) { 30 | if (vis.contains(bus)) { 31 | continue; 32 | } 33 | 34 | vis.add(bus); 35 | for (int stop : routes[bus]) { 36 | if (stop == target) 37 | return count + 1; 38 | q.offer(stop); 39 | } 40 | } 41 | } 42 | count++; 43 | } 44 | 45 | return -1; 46 | } 47 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Check_If_Two_String_Arrays_are_Equivalent.java: -------------------------------------------------------------------------------- 1 | public class Check_If_Two_String_Arrays_are_Equivalent { 2 | public boolean arrayStringsAreEqual(String[] word1, String[] word2) { 3 | if (word1.length == 0 || word2.length == 0) 4 | return false; 5 | return String.join("", word1).equals(String.join("", word2)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Count Nodes Equal to Average of Subtree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private int res = 0; 3 | 4 | public int averageOfSubtree(TreeNode root) { 5 | postorder(root); 6 | return res; 7 | } 8 | 9 | private int[] postorder(TreeNode node) { 10 | if (node == null) { 11 | return new int[] { 0, 0 }; // sum, number of nodes 12 | } 13 | 14 | int[] left = postorder(node.left); 15 | int[] right = postorder(node.right); 16 | 17 | int totalSum = left[0] + right[0] + node.val; 18 | int totalCount = 1 + left[1] + right[1]; 19 | res += (node.val == totalSum / totalCount ? 1 : 0); 20 | 21 | return new int[] { totalSum, totalCount }; 22 | } 23 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Count Number of Homogenous Substrings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countHomogenous(String s) { 3 | var prev = '?'; 4 | var cnt = 1; 5 | var sum = 0; 6 | 7 | for (var c : s.toCharArray()) { 8 | if (c != prev) { 9 | cnt = 1; 10 | prev = c; 11 | } 12 | sum = (sum + cnt++) % 1000000007; 13 | } 14 | return sum; 15 | } 16 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Count_Nice_Pairs_in_an_Array.java: -------------------------------------------------------------------------------- 1 | public class Count_Nice_Pairs_in_an_Array { 2 | 3 | int reverse(int num) { 4 | int rev = 0; 5 | while (num > 0) { 6 | rev = rev * 10 + num % 10; 7 | num /= 10; 8 | } 9 | return rev; 10 | } 11 | 12 | public int countNicePairs(int[] nums) { 13 | final int mod = 1000000007; 14 | 15 | int len = nums.length; 16 | for (int i = 0; i < len; i++) 17 | nums[i] = nums[i] - reverse(nums[i]); 18 | Arrays.sort(nums); 19 | long res = 0; 20 | for (int i = 0; i < len - 1; i++) { 21 | long cont = 1; 22 | while (i < len - 1 && nums[i] == nums[i + 1]) { 23 | cont++; 24 | i++; 25 | } 26 | res = (res % mod + (cont * (cont - 1)) / 2) % mod; 27 | } 28 | return (int) res % mod; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Design Graph With Shortest Path Calculator.java: -------------------------------------------------------------------------------- 1 | class Graph { 2 | List> adj = new ArrayList<>(); 3 | int n; 4 | 5 | public Graph(int n, int[][] edges) { 6 | for (int i = 0; i < n; i++) { 7 | adj.add(new ArrayList<>()); 8 | } 9 | this.n = n; 10 | for (var edge : edges) { 11 | adj.get(edge[0]).add(new int[] { edge[1], edge[2] }); 12 | } 13 | } 14 | 15 | public void addEdge(int[] edge) { 16 | adj.get(edge[0]).add(new int[] { edge[1], edge[2] }); 17 | } 18 | 19 | public int shortestPath(int node1, int node2) { 20 | int[] distance = new int[n + 1]; 21 | Arrays.fill(distance, Integer.MAX_VALUE); 22 | 23 | distance[node1] = 0; 24 | 25 | PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); 26 | pq.add(new int[] { node1, 0 }); 27 | while (!pq.isEmpty()) { 28 | int temp = pq.poll()[0]; 29 | 30 | for (int[] i : adj.get(temp)) { 31 | int x = i[0]; 32 | int y = i[1]; 33 | 34 | if (distance[x] > distance[temp] + y) { 35 | distance[x] = distance[temp] + y; 36 | pq.add(new int[] { x, distance[x] }); 37 | } 38 | } 39 | } 40 | 41 | if (distance[node2] == Integer.MAX_VALUE) { 42 | return -1; 43 | } 44 | return distance[node2]; 45 | } 46 | } 47 | 48 | /** 49 | * Your Graph object will be instantiated and called as such: 50 | * Graph obj = new Graph(n, edges); 51 | * obj.addEdge(edge); 52 | * int param_2 = obj.shortestPath(node1,node2); 53 | */ -------------------------------------------------------------------------------- /Leet_Code_Leet/Determine if a Cell Is Reachable at a Given Time.java: -------------------------------------------------------------------------------- 1 | { 2 | public boolean isReachableAtTime(int sx, int sy, int fx, int fy, int t) { 3 | if(sx==fx && sy==fy) { 4 | return t!=1; 5 | } 6 | return Math.max(Math.abs(sx-fx), Math.abs(sy-fy))<=t; 7 | } 8 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Diagonal_Traverse.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findDiagonalOrder(List> nums) { 3 | int count = 0; 4 | 5 | List> lists = new ArrayList<>(); 6 | for (int i = 0; i < nums.size(); i++) { 7 | List row = nums.get(i); 8 | 9 | for (int j = 0; j < row.size(); j++) { 10 | int idx = i + j; 11 | 12 | if (lists.size() < idx + 1) { 13 | lists.add(new ArrayList<>()); 14 | } 15 | lists.get(idx).add(row.get(j)); 16 | 17 | count++; 18 | } 19 | } 20 | 21 | int[] res = new int[count]; 22 | int idx = 0; 23 | for (List list : lists) { 24 | for (int i = list.size() - 1; i >= 0; i--) { 25 | res[idx++] = list.get(i); 26 | } 27 | } 28 | return res; 29 | } 30 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Eliminate Maximum Number of Monsters.java: -------------------------------------------------------------------------------- 1 | public class Eliminate 2 | Maximum Number 3 | of Monsters 4 | { 5 | 6 | public int eliminateMaximum(int[] dist, int[] speed) { 7 | int n = dist.length; 8 | double[] monstArrivalTime = new double[n]; 9 | 10 | // Finding the arrival time of monster based on formula 11 | // (Time = Distance / Speed) 12 | for (int i = 0; i < n; i++) { 13 | monstArrivalTime[i] = ((double) (dist[i]) / (double) speed[i]); 14 | } 15 | 16 | // Sorting the arrival time of monster that helps in determining 17 | // the maximum monster to eliminate 18 | Arrays.sort(monstArrivalTime); 19 | int res = 0; 20 | double stick = 0.0; 21 | 22 | // Checking what monster arrive at what time and how much monster 23 | // I can eliminate 24 | for (int i = 0; i < n; i++) { 25 | if (stick < monstArrivalTime[i]) { 26 | res++; 27 | stick++; 28 | } else { 29 | break; 30 | } 31 | } 32 | return res; 33 | } 34 | }} 35 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Find Mode in Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findMode(TreeNode root) { 3 | Map counts = new HashMap<>(); 4 | int[] maxCount = { 0 }; // Using an array to simulate nonlocal 5 | List modes = new ArrayList<>(); 6 | 7 | inorder(root, counts, maxCount, modes); 8 | 9 | int[] result = new int[modes.size()]; 10 | for (int i = 0; i < modes.size(); i++) { 11 | result[i] = modes.get(i); 12 | } 13 | 14 | return result; 15 | } 16 | 17 | private void inorder(TreeNode node, Map counts, int[] maxCount, List modes) { 18 | if (node == null) { 19 | return; 20 | } 21 | 22 | inorder(node.left, counts, maxCount, modes); 23 | 24 | int count = counts.getOrDefault(node.val, 0) + 1; 25 | counts.put(node.val, count); 26 | 27 | if (count > maxCount[0]) { 28 | maxCount[0] = count; 29 | modes.clear(); 30 | modes.add(node.val); 31 | } else if (count == maxCount[0]) { 32 | modes.add(node.val); 33 | } 34 | 35 | inorder(node.right, counts, maxCount, modes); 36 | } 37 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Find Unique Binary String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String findDifferentBinaryString(String[] nums) { 3 | StringBuilder sb = new StringBuilder(); 4 | 5 | for (int i = 0; i < nums.length; i++) { 6 | sb.append(nums[i].charAt(i) == '0' ? "1" : "0"); 7 | } 8 | return sb.toString(); 9 | } 10 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Find the Winner of an Array Game.java: -------------------------------------------------------------------------------- 1 | public class Find 2 | the Winner 3 | of an 4 | Array Game 5 | { 6 | 7 | public int getWinner(int[] arr, int k) { 8 | int winner = arr[0]; 9 | int wins = 0; 10 | 11 | for (int i = 1; i < arr.length; i++) { 12 | if (winner > arr[i]) 13 | wins++; 14 | else { 15 | wins = 1; 16 | winner = arr[i]; 17 | } 18 | 19 | if (wins == k) 20 | break; 21 | } 22 | 23 | return winner; 24 | } 25 | }} 26 | -------------------------------------------------------------------------------- /Leet_Code_Leet/FindThe OriginalArray_of_Prefix_Xor.java: -------------------------------------------------------------------------------- 1 | public class FindThe OriginalArray_of_Prefix_Xor{ 2 | 3 | public int[] findArray(int[] pref) { 4 | int[] result = new int[pref.length]; 5 | result[0] = pref[0]; 6 | for (int i = 1; i < pref.length; i++) { 7 | result[i] = pref[i] ^ pref[i - 1]; 8 | } 9 | return result; 10 | } 11 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Frequency_of_the_Most_Frequent_Element.java: -------------------------------------------------------------------------------- 1 | public class Frequency_of_the_Most_Frequent_Element { 2 | public int maxFrequency(int[] nums, int k) { 3 | int maxFrequency = 0; // Initialize the maximum frequency 4 | long currentSum = 0; // Initialize the current sum of the subarray elements 5 | 6 | Arrays.sort(nums); // Sort the array in ascending order 7 | 8 | for (int left = 0, right = 0; right < nums.length; ++right) { 9 | currentSum += nums[right]; // Include the current element in the subarray sum 10 | 11 | // Check if the current subarray violates the condition (sum + k < nums[right] * 12 | // length) 13 | while (currentSum + k < (long) nums[right] * (right - left + 1)) { 14 | currentSum -= nums[left]; // Adjust the subarray sum by removing the leftmost element 15 | left++; // Move the left pointer to the right 16 | } 17 | 18 | // Update the maximum frequency based on the current subarray length 19 | maxFrequency = Math.max(maxFrequency, right - left + 1); 20 | } 21 | 22 | return maxFrequency; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Largest_Submatrix_With_Rearrangements.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Largest_Submatrix_With_Rearrangements { 4 | public int largestSubmatrix(int[][] matrix) { 5 | int m = matrix.length, n = matrix[0].length; 6 | for (int i = 1; i < m; ++i) { 7 | for (int j = 0; j < n; ++j) { 8 | if (matrix[i][j] == 1) { 9 | matrix[i][j] = matrix[i - 1][j] + 1; 10 | } 11 | } 12 | } 13 | int ans = 0; 14 | for (var row : matrix) { 15 | Arrays.sort(row); 16 | for (int j = n - 1, k = 1; j >= 0 && row[j] > 0; --j, ++k) { 17 | int s = row[j] * k; 18 | ans = Math.max(ans, s); 19 | } 20 | } 21 | return ans; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Last Moment Before All Ants Fall Out of a Plank.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int getLastMoment(int n, int[] left, int[] right) { 3 | // Initialize a variable to keep track of the maximum time 4 | int time = 0; 5 | 6 | // Iterate through the positions of ants moving to the left 7 | for (int pos : left) { 8 | // Update the maximum time if the current left-moving ant's position is greater 9 | // than the previously recorded maximum time 10 | time = Math.max(time, pos); 11 | } 12 | 13 | // Iterate through the positions of ants moving to the right 14 | for (int pos : right) { 15 | // Update the maximum time if the current right-moving ant's position (relative to 16 | // the right end of the plank) is greater than the previously recorded maximum time 17 | time = Math.max(time, n - pos); 18 | } 19 | 20 | // The final 'time' variable contains the maximum time, which is when the last ant(s) 21 | // fall off the plank, so return it as the result. 22 | return time; 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Maximum_Element_After_Decreasing_and_Rearranging.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Maximum_Element_After_Decreasing_and_Rearranging { 4 | 5 | public int maximumElementAfterDecrementingAndRearranging(int[] arr) { 6 | Arrays.sort(arr); 7 | int res = 1; 8 | for (int i = 1; i < arr.length; ++i) { 9 | if (arr[i] > res) { 10 | ++res; 11 | } 12 | } 13 | return res; 14 | } 15 | 16 | public static void main(String[] args) { 17 | Maximum_Element_After_Decreasing_and_Rearranging solution = new Maximum_Element_After_Decreasing_and_Rearranging(); 18 | 19 | // Example usage: 20 | int[] arr = { 2, 2, 1, 2, 1 }; 21 | int result = solution.maximumElementAfterDecrementingAndRearranging(arr); 22 | System.out.println("The maximum element after decrementing and rearranging is: " + result); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Maximum_Number_of_Coins_You_Can_Get.java: -------------------------------------------------------------------------------- 1 | public class Maximum_Number_of_Coins_You_Can_Get { 2 | public int maxCoins(int[] piles) { 3 | int max = 0; 4 | int n = piles.length; 5 | 6 | for (int i : piles) { 7 | if (max < i) 8 | max = i; 9 | } 10 | 11 | int[] freq = new int[max + 1]; 12 | 13 | for (int i : piles) { 14 | freq[i]++; 15 | } 16 | 17 | int coins = 0; 18 | int chance = n / 3; 19 | 20 | int turn = 1; 21 | int i = max; 22 | 23 | while (chance != 0) { 24 | if (freq[i] > 0) { 25 | if (turn == 1) 26 | turn = 0; 27 | else { 28 | chance--; 29 | turn = 1; 30 | coins += i; 31 | } 32 | freq[i]--; 33 | } else { 34 | i--; 35 | } 36 | } 37 | 38 | return coins; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Minimize_Maximum_Pair_Sum_in_Array.java: -------------------------------------------------------------------------------- 1 | class Minimize_Maximum_Pair_Sum_in_Array { 2 | public int minPairSum(int[] nums) { 3 | int max = Integer.MIN_VALUE; 4 | int min = Integer.MAX_VALUE; 5 | int hash[] = new int[100001]; 6 | for (int num : nums) { 7 | hash[num]++; 8 | max = Math.max(max, num); 9 | min = Math.min(min, num); 10 | } 11 | 12 | int low = min; 13 | int high = max; 14 | max = Integer.MIN_VALUE; 15 | while (low <= high) { 16 | if (hash[low] == 0) 17 | low++; 18 | else if (hash[high] == 0) 19 | high--; 20 | else { 21 | max = Math.max(max, low + high); 22 | hash[low]--; 23 | hash[high]--; 24 | } 25 | } 26 | return max; 27 | } 28 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Minimum_Amount_of_Time_to_Collect_Garbage.java: -------------------------------------------------------------------------------- 1 | public class Minimum_Amount_of_Time_to_Collect_Garbage { 2 | public int garbageCollection(String[] garbage, int[] travel) { 3 | int n = garbage.length; 4 | int ans = 0; 5 | for (int i = 0; i < n - 1; i++) { 6 | ans += 3 * travel[i]; 7 | } 8 | for (String s : garbage) { 9 | ans += s.length(); 10 | } 11 | for (int i = n - 1; i > 0; i--) { 12 | if (!garbage[i].contains("G")) { 13 | ans -= travel[i - 1]; 14 | } else { 15 | break; 16 | } 17 | } 18 | for (int i = n - 1; i > 0; i--) { 19 | if (!garbage[i].contains("P")) { 20 | ans -= travel[i - 1]; 21 | } else { 22 | break; 23 | } 24 | } 25 | for (int i = n - 1; i > 0; i--) { 26 | if (!garbage[i].contains("M")) { 27 | ans -= travel[i - 1]; 28 | } else { 29 | break; 30 | } 31 | } 32 | return ans; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Minimum_One_Bit_Operations_to_Make_Integers_Zero.java: -------------------------------------------------------------------------------- 1 | public class Minimum_One_Bit_Operations_to_Make_Integers_Zero { 2 | int min = Integer.MAX_VALUE; 3 | 4 | public int minimumOneBitOperations(int n) { 5 | if (n <= 1) 6 | return n; 7 | int count = 0; 8 | while ((1 << count) <= n) 9 | count++; 10 | return ((1 << count) - 1) - minimumOneBitOperations(n - (1 << (count - 1))); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Number_of_1_Bits.java: -------------------------------------------------------------------------------- 1 | public class Number_of_1_Bits { 2 | public int hammingWeight(int n) { 3 | int count = 0; 4 | while (n != 0) { 5 | n = n & (n - 1); 6 | count++; 7 | } 8 | return count; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Poor Pigs.java: -------------------------------------------------------------------------------- 1 | public class Poor Pigs 2 | { 3 | 4 | public int poorPigs(int buckets, int timeToDie, int timeToTest) { 5 | int testsPerPig = timeToTest / timeToDie; 6 | int numPigs = 0; 7 | int states = 1; // Number of unique states a pig can represent 8 | while (states < buckets) { 9 | states *= (testsPerPig + 1); 10 | numPigs++; 11 | } 12 | return numPigs; 13 | } 14 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Read.md: -------------------------------------------------------------------------------- 1 | hello.text 2 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Reduction_Operations_to_Make_the_Array_Elements_Equal.java: -------------------------------------------------------------------------------- 1 | class Reduction_Operations_to_Make_the_Array_Elements_Equal { 2 | public int reductionOperations(int[] nums) { 3 | int n = nums.length; 4 | int[] freq = new int[50001]; 5 | for (int i = 0; i < n; i++) { 6 | freq[nums[i]]++; 7 | } 8 | int res = 0, operations = 0; 9 | for (int i = 50000; i >= 1; i--) { 10 | if (freq[i] > 0) { 11 | operations += freq[i]; 12 | res += operations - freq[i]; 13 | } 14 | } 15 | return res; 16 | } 17 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Restore the Array From Adjacent Pairs.java: -------------------------------------------------------------------------------- 1 | public class Restore 2 | the Array 3 | From Adjacent Pairs 4 | { 5 | 6 | public int[] restoreArray(int[][] adjacentPairs) { 7 | int n = adjacentPairs.length; 8 | int m = adjacentPairs[0].length; 9 | int ans[] = new int[n + 1]; 10 | HashSet set = new HashSet<>();// stores all the unique elements 11 | for (int i = 0; i < n; i++) { 12 | for (int j = 0; j < m; j++) { 13 | set.add(adjacentPairs[i][j]); 14 | } 15 | } 16 | HashMap> map = new HashMap<>();// stores adjacent elements for each element 17 | for (int k : set) { 18 | ArrayList temp = new ArrayList<>(); 19 | map.put(k, temp); 20 | } 21 | for (int i = 0; i < n; i++) { 22 | map.get(adjacentPairs[i][0]).add(adjacentPairs[i][1]); 23 | map.get(adjacentPairs[i][1]).add(adjacentPairs[i][0]); 24 | } 25 | // Reconstructing the array 26 | int start = 0; 27 | for (int key : map.keySet()) { 28 | if (map.get(key).size() == 1) { 29 | start = key; 30 | break; 31 | } 32 | } 33 | ans[0] = start; 34 | ans[1] = map.get(start).get(0); 35 | 36 | for (int i = 2; i < n + 1; i++) { 37 | ArrayList neighbours = map.get(ans[i - 1]); 38 | ans[i] = (ans[i - 2] == neighbours.get(0) ? neighbours.get(1) : neighbours.get(0)); 39 | } 40 | return ans; 41 | } 42 | }} 43 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Seat Reservation Manager.java: -------------------------------------------------------------------------------- 1 | class SeatManager { 2 | private PriorityQueue seats; // Declare a priority queue to manage seat reservations. 3 | 4 | // Constructor to initialize the SeatManager with 'n' seats. 5 | public SeatManager(int n) { 6 | seats = new PriorityQueue<>(); 7 | // Initialize the priority queue with seat numbers from 1 to 'n'. 8 | for (int i = 1; i <= n; i++) { 9 | seats.offer(i); 10 | } 11 | } 12 | 13 | // Reserve a seat. 14 | public int reserve() { 15 | if (!seats.isEmpty()) { // Check if there are available seats in the priority queue. 16 | int reservedSeat = seats.poll(); // Get the smallest seat number from the queue. 17 | return reservedSeat; // Return the reserved seat number. 18 | } else { 19 | return -1; // Return -1 to indicate that there are no available seats. 20 | } 21 | } 22 | 23 | // Unreserve a seat. 24 | public void unreserve(int seatNumber) { 25 | seats.offer(seatNumber); // Add the unreserved seat back to the priority queue. 26 | } 27 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minOperations(int[] nums) { 3 | int n = nums.length; 4 | int ans = n; 5 | 6 | HashSet unique = new HashSet<>(); 7 | for (int num : nums) { 8 | unique.add(num); 9 | } 10 | 11 | int[] newNums = new int[unique.size()]; 12 | int index = 0; 13 | 14 | for (int num : unique) { 15 | newNums[index++] = num; 16 | } 17 | 18 | Arrays.sort(newNums); 19 | 20 | for (int i = 0; i < newNums.length; i++) { 21 | int left = newNums[i]; 22 | int right = left + n - 1; 23 | int j = binarySearch(newNums, right); 24 | int count = j - i; 25 | ans = Math.min(ans, n - count); 26 | } 27 | 28 | return ans; 29 | } 30 | 31 | public int binarySearch(int[] newNums, int target) { 32 | int left = 0; 33 | int right = newNums.length; 34 | 35 | while (left < right) { 36 | int mid = (left + right) / 2; 37 | if (target < newNums[mid]) { 38 | right = mid; 39 | } else { 40 | left = mid + 1; 41 | } 42 | } 43 | 44 | return left; 45 | } 46 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution1.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution1 { 4 | public int[] fullBloomFlowers(int[][] flowers, int[] people) { 5 | // Create a list of Flower objects to keep track of bloom times 6 | List flowerList = new ArrayList<>(); 7 | for (int i = 0; i < flowers.length; i++) { 8 | flowerList.add(new Flower(flowers[i][0], flowers[i][1])); 9 | } 10 | 11 | // Sort the list of flowers based on their bloom times 12 | Collections.sort(flowerList, (a, b) -> a.bloomTime - b.bloomTime); 13 | 14 | int[] result = new int[people.length]; 15 | int bloomIndex = 0; // Index to track the current flower in bloom 16 | 17 | for (int i = 0; i < people.length; i++) { 18 | int personTime = people[i]; 19 | 20 | // Count flowers in full bloom when the person arrives 21 | while (bloomIndex < flowerList.size() && flowerList.get(bloomIndex).bloomTime <= personTime) { 22 | bloomIndex++; 23 | } 24 | result[i] = bloomIndex; 25 | } 26 | 27 | return result; 28 | } 29 | 30 | private class Flower { 31 | int bloomTime; 32 | int wiltTime; 33 | 34 | public Flower(int bloomTime, int wiltTime) { 35 | this.bloomTime = bloomTime; 36 | this.wiltTime = wiltTime; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution10.java: -------------------------------------------------------------------------------- 1 | public class Solution10 { 2 | class Solution { 3 | public int constrainedSubsetSum(int[] nums, int k) { 4 | int n = nums.length; 5 | int[] dp = new int[n]; 6 | int res = nums[0]; 7 | Queue queue = new PriorityQueue<>((a, b) -> dp[b] - dp[a]); // Declaring Max heap 8 | 9 | Arrays.fill(dp, Integer.MIN_VALUE); 10 | dp[0] = nums[0]; 11 | queue.offer(0); 12 | 13 | for (int j = 1; j < n; j++) { 14 | int i = Math.max(j - k, 0); // get the furthest index possible 15 | while (!queue.isEmpty() && queue.peek() < i) 16 | queue.poll(); // find the global max in the specified range for that particular j index 17 | int idx = queue.peek(); 18 | dp[j] = Math.max(dp[idx] + nums[j], nums[j]); 19 | res = Math.max(res, dp[j]); 20 | queue.offer(j); 21 | } 22 | return res; 23 | } 24 | 25 | public static void main(String[] args) { 26 | 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution11.java: -------------------------------------------------------------------------------- 1 | class Solution11 { 2 | public int maximumScore(int[] nums, int k) { 3 | 4 | int left = k - 1; 5 | int right = k + 1; 6 | int minvalue = nums[k]; 7 | int maxscore = nums[k]; 8 | int length = nums.length; 9 | 10 | while (left >= 0 || right < length) { 11 | if (left >= 0 && right < length && nums[left] >= nums[right]) { 12 | minvalue = Math.min(minvalue, nums[left]); 13 | maxscore = Math.max(maxscore, (right - left) * minvalue); 14 | left--; 15 | } else if (left >= 0 && right < length && nums[left] <= nums[right]) { 16 | minvalue = Math.min(minvalue, nums[right]); 17 | maxscore = Math.max(maxscore, (right - left) * minvalue); 18 | right++; 19 | } else if (left < 0) { 20 | minvalue = Math.min(minvalue, nums[right]); 21 | maxscore = Math.max(maxscore, (right - left) * minvalue); 22 | right++; 23 | } else { 24 | minvalue = Math.min(minvalue, nums[left]); 25 | maxscore = Math.max(maxscore, (right - left) * minvalue); 26 | left--; 27 | } 28 | } 29 | return maxscore; 30 | } 31 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution12.java: -------------------------------------------------------------------------------- 1 | class Solution12 { 2 | public boolean isPowerOfFour(int n) { 3 | if (n == 0) 4 | return false; 5 | if (n == 1) 6 | return true; 7 | if (n % 4 != 0) 8 | return false; 9 | 10 | return isPowerOfFour(n / 4); 11 | } 12 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution13.java: -------------------------------------------------------------------------------- 1 | class Solution13 { 2 | public List largestValues(TreeNode root) { 3 | Queue queue = new LinkedList<>(); 4 | List ans = new ArrayList<>(); 5 | queue.offer(root); 6 | if (root == null) 7 | return ans; 8 | while (!queue.isEmpty()) { 9 | int level = queue.size(); 10 | int max = Integer.MIN_VALUE; 11 | for (int i = 0; i < level; i++) { 12 | TreeNode temp = queue.poll(); 13 | if (temp.left != null) { 14 | queue.offer(temp.left); 15 | } 16 | if (temp.right != null) { 17 | queue.offer(temp.right); 18 | } 19 | max = Math.max(max, temp.val); 20 | } 21 | ans.add(max); 22 | } 23 | return ans; 24 | } 25 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution14.java: -------------------------------------------------------------------------------- 1 | public class Solution14 { 2 | public String longestPalindrome(String s) { 3 | if (s.length() <= 1) { 4 | return s; 5 | } 6 | 7 | int maxLen = 1; 8 | String maxStr = s.substring(0, 1); 9 | 10 | for (int i = 0; i < s.length(); i++) { 11 | for (int j = i + maxLen; j <= s.length(); j++) { 12 | if (j - i > maxLen && isPalindrome(s.substring(i, j))) { 13 | maxLen = j - i; 14 | maxStr = s.substring(i, j); 15 | } 16 | } 17 | } 18 | 19 | return maxStr; 20 | } 21 | 22 | private boolean isPalindrome(String str) { 23 | int left = 0; 24 | int right = str.length() - 1; 25 | 26 | while (left < right) { 27 | if (str.charAt(left) != str.charAt(right)) { 28 | return false; 29 | } 30 | left++; 31 | right--; 32 | } 33 | 34 | return true; 35 | } 36 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution2.java: -------------------------------------------------------------------------------- 1 | public class Solution2 { 2 | 3 | public int findInMountainArray(int target, MountainArray mountainArray) { 4 | int peak = peakIndex(mountainArray); 5 | int index = binarySearch(mountainArray, target,0,peak); 6 | if(index!=-1) 7 | { 8 | return index; 9 | } 10 | return binarySearch(mountainArray,target, peak+1,mountainArray.length()-1); 11 | } 12 | private int peakIndex(MountainArray mountainArray) 13 | { 14 | int left=0; 15 | int right = mountainArray.length()-1; 16 | while(leftmountainArray.get(mid+1)) 20 | { 21 | right = mid; 22 | } 23 | else 24 | { 25 | left = mid+1; 26 | } 27 | } 28 | return left; 29 | } 30 | private int binarySearch(MountainArray mountainArray, int target, int left , int right) 31 | { 32 | boolean isAscending = mountainArray.get(left)midElement) 46 | { 47 | left=mid+1; 48 | } 49 | else 50 | { 51 | right=mid-1; 52 | } 53 | } 54 | else 55 | { 56 | if(target>midElement) 57 | { 58 | right=mid-1; 59 | } 60 | else 61 | { 62 | left=mid+1; 63 | } 64 | } 65 | } 66 | return -1; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution3.java: -------------------------------------------------------------------------------- 1 | class Solution3 { 2 | public int minCostClimbingStairs(int[] cost) { 3 | int n = cost.length; 4 | for(int i=n-3;i>=0;i--){ 5 | cost[i] += Math.min(cost[i+1],cost[i+2]); 6 | } 7 | return Math.min(cost[0],cost[1]); 8 | } 9 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution4.java: -------------------------------------------------------------------------------- 1 | class Solution4 { 2 | public int paintWalls(int[] cost, int[] time) { 3 | // code 4 | int n = cost.length; 5 | int[][] dp = new int[n + 1][n + 1]; 6 | 7 | for (int i = 1; i <= n; i++) { 8 | dp[n][i] = (int) 1e9; 9 | } 10 | int opt1; 11 | int opt2; 12 | for (int i = n - 1; i >= 0; i--) { 13 | for (int remain = 1; remain <= n; remain++) { 14 | opt1 = cost[i] + dp[i + 1][Math.max(0, remain - 1 - time[i])]; 15 | opt2 = dp[i + 1][remain]; 16 | dp[i][remain] = Math.min(opt1, opt2); 17 | } 18 | } 19 | 20 | return dp[0][n]; 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution5.java: -------------------------------------------------------------------------------- 1 | class Solution5 { 2 | public List getRow(int rowIndex) { 3 | List> pascalTriangle = new ArrayList<>(); 4 | 5 | // Generate the Pascal's Triangle up to the rowIndex 6 | for (int i = 0; i <= rowIndex; i++) { 7 | List row = new ArrayList<>(); 8 | 9 | for (int j = 0; j <= i; j++) { 10 | if (j == 0 || j == i) { 11 | row.add(1); 12 | } else { 13 | // Calculate the value in the middle based on the values from the previous row. 14 | List prevRow = pascalTriangle.get(i - 1); 15 | int value = prevRow.get(j - 1) + prevRow.get(j); 16 | row.add(value); 17 | } 18 | } 19 | 20 | pascalTriangle.add(row); 21 | } 22 | 23 | // The result is the row at the given rowIndex. 24 | return pascalTriangle.get(rowIndex); 25 | } 26 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution6.java: -------------------------------------------------------------------------------- 1 | class Solution6 { 2 | public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) { 3 | Map> graph = new HashMap<>(); 4 | int[] inDegree = new int[n]; 5 | 6 | for (int node = 0; node < n; node++) { 7 | int left = leftChild[node]; 8 | int right = rightChild[node]; 9 | if (left != -1) { 10 | graph.computeIfAbsent(node, k -> new ArrayList<>()).add(left); 11 | inDegree[left]++; 12 | } 13 | if (right != -1) { 14 | graph.computeIfAbsent(node, k -> new ArrayList<>()).add(right); 15 | inDegree[right]++; 16 | } 17 | } 18 | 19 | List rootCandidates = new ArrayList<>(); 20 | for (int node = 0; node < n; node++) { 21 | if (inDegree[node] == 0) { 22 | rootCandidates.add(node); 23 | } 24 | } 25 | 26 | if (rootCandidates.size() != 1) { 27 | return false; 28 | } 29 | int root = rootCandidates.get(0); 30 | 31 | Queue queue = new LinkedList<>(); 32 | Set seen = new HashSet<>(); 33 | queue.add(root); 34 | seen.add(root); 35 | 36 | while (!queue.isEmpty()) { 37 | int node = queue.poll(); 38 | if (graph.containsKey(node)) { 39 | for (int child : graph.get(node)) { 40 | if (seen.contains(child)) { 41 | return false; 42 | } 43 | seen.add(child); 44 | queue.add(child); 45 | } 46 | } 47 | } 48 | 49 | return seen.size() == n; 50 | } 51 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution7.java: -------------------------------------------------------------------------------- 1 | class Solution7 { 2 | private int[] startNodes; 3 | private int[][] graph; 4 | private int[] time; 5 | private boolean[] visited; 6 | private int[] ans; 7 | 8 | private void toGraph(int[][] edges, int n) { 9 | int[] incoming = new int[n], outgoing = new int[n]; 10 | for (int[] e : edges) { 11 | outgoing[e[0] - 1]++; 12 | incoming[e[1] - 1]++; 13 | } 14 | int startCnt = 0; 15 | for (int i : incoming) { 16 | if (i == 0) { 17 | startCnt++; 18 | } 19 | } 20 | startNodes = new int[startCnt]; 21 | for (int sni = 0, i = 0; sni < startNodes.length; i++) { 22 | if (incoming[i] == 0) { 23 | startNodes[sni++] = i; 24 | } 25 | } 26 | graph = new int[n][]; 27 | for (int i = 0; i < n; i++) { 28 | graph[i] = new int[outgoing[i]]; 29 | } 30 | for (int[] e : edges) { 31 | graph[e[0] - 1][--outgoing[e[0] - 1]] = e[1] - 1; 32 | } 33 | } 34 | 35 | private int calculate(int node) { 36 | if (ans[node] > 0) { 37 | return ans[node]; 38 | } 39 | 40 | int worstPrereq = 0; 41 | visited[node] = true; 42 | for (int child : graph[node]) { 43 | if (!visited[child]) { 44 | worstPrereq = Math.max(calculate(child), worstPrereq); 45 | } 46 | } 47 | visited[node] = false; 48 | return ans[node] = worstPrereq + time[node]; 49 | } 50 | 51 | public int minimumTime(int n, int[][] relations, int[] time) { 52 | toGraph(relations, n); 53 | this.time = time; 54 | ans = new int[n]; 55 | visited = new boolean[n]; 56 | int longest = 0; 57 | for (int node : startNodes) { 58 | longest = Math.max(longest, calculate(node)); 59 | } 60 | return longest; 61 | } 62 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution8.java: -------------------------------------------------------------------------------- 1 | class Solution8 { 2 | public boolean backspaceCompare(String s, String t) { 3 | StringBuilder sb1 = new StringBuilder(); 4 | StringBuilder sb2 = new StringBuilder(); 5 | 6 | for (char ch : s.toCharArray()) { 7 | if (ch == '#') { 8 | if (!sb1.isEmpty()) { 9 | sb1.deleteCharAt(sb1.length() - 1); 10 | } 11 | } else { 12 | sb1.append(ch); 13 | } 14 | } 15 | 16 | for (char ch : t.toCharArray()) { 17 | if (ch == '#') { 18 | if (!sb2.isEmpty()) { 19 | sb2.deleteCharAt(sb2.length() - 1); 20 | } 21 | } else { 22 | sb2.append(ch); 23 | } 24 | } 25 | 26 | return sb1.toString().equals(sb2.toString()); 27 | } 28 | } -------------------------------------------------------------------------------- /Leet_Code_Leet/Solution9.java: -------------------------------------------------------------------------------- 1 | public class Solution9 { 2 | public class NestedIterator implements Iterator { 3 | Deque stack = new ArrayDeque<>(); 4 | 5 | public NestedIterator(List nestedList) { 6 | // Initialize the stack with the provided nested list. 7 | prepareStack(nestedList); 8 | } 9 | 10 | @Override 11 | public Integer next() { 12 | if (!hasNext()) { 13 | return null; // If there's no next element, return null. 14 | } 15 | return stack.pop().getInteger(); // Pop and return the next integer. 16 | } 17 | 18 | @Override 19 | public boolean hasNext() { 20 | while (!stack.isEmpty() && !stack.peek().isInteger()) { 21 | // While the stack is not empty and the top element is a nested list, 22 | // prepare the stack with the elements from that nested list. 23 | List list = stack.pop().getList(); 24 | prepareStack(list); 25 | } 26 | return !stack.isEmpty(); // Check if there's more to iterate. 27 | } 28 | 29 | // Helper function to prepare the stack with a list of nested integers. 30 | private void prepareStack(List nestedList) { 31 | for (int i = nestedList.size() - 1; i >= 0; i--) { 32 | // Push elements onto the stack in reverse order to process them in the correct 33 | // order. 34 | stack.push(nestedList.get(i)); 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Sort Integers by The Number of 1 Bits.java: -------------------------------------------------------------------------------- 1 | public class Sort 2 | Integers by 3 | The Number of 1 Bits 4 | { 5 | 6 | public int[] sortByBits(int[] arr) { 7 | int n = arr.length; 8 | int res[] = new int[n]; 9 | for (int i = 0; i < n; i++) { 10 | res[i] = countBit(arr[i]) * 10001 + arr[i]; 11 | } 12 | Arrays.sort(res); 13 | for (int i = 0; i < n; i++) { 14 | res[i] %= 10001; 15 | } 16 | return res; 17 | } 18 | 19 | private int countBit(int n) { 20 | int res = 0; 21 | while (n != 0) { 22 | res += (n & 1); 23 | n >>= 1; 24 | } 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Sort Vowels in a String.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | // Function to find the minimum number of buses needed to reach the target from 5 | // the source. 6 | public int numBusesToDestination(int[][] routes, int source, int target) { 7 | // If source and target are the same, no buses are needed. 8 | if (source == target) { 9 | return 0; 10 | } 11 | 12 | // Create an adjacency list to represent stops and the routes that include each 13 | // stop. 14 | Map> adjList = new HashMap<>(); 15 | for (int route = 0; route < routes.length; route++) { 16 | for (int stop : routes[route]) { 17 | adjList.computeIfAbsent(stop, k -> new ArrayList<>()).add(route); 18 | } 19 | } 20 | 21 | // Initialize a queue for BFS and a set to keep track of visited routes. 22 | Queue q = new LinkedList<>(); 23 | Set vis = new HashSet<>(); 24 | 25 | // Insert all the routes in the queue that have the source stop. 26 | for (int route : adjList.getOrDefault(source, new ArrayList<>())) { 27 | q.add(route); 28 | vis.add(route); 29 | } 30 | 31 | int busCount = 1; // Initialize the bus count. 32 | 33 | // Perform BFS to find the minimum number of buses needed. 34 | while (!q.isEmpty()) { 35 | int size = q.size(); 36 | 37 | for (int i = 0; i < size; i++) { 38 | int route = q.poll(); 39 | 40 | // Iterate over the stops in the current route. 41 | for (int stop : routes[route]) { 42 | // Return the current count if the target is found. 43 | if (stop == target) { 44 | return busCount; 45 | } 46 | 47 | // Iterate over the next possible routes from the current stop. 48 | for (int nextRoute : adjList.getOrDefault(stop, new ArrayList<>())) { 49 | if (!vis.contains(nextRoute)) { 50 | vis.add(nextRoute); 51 | q.add(nextRoute); 52 | } 53 | } 54 | } 55 | } 56 | busCount++; 57 | } 58 | 59 | // If no route is found, return -1. 60 | return -1; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Sum_of_Absolute_Differences_in_a_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | public class Sum_of_Absolute_Differences_in_a_Sorted_Array { 2 | public int[] getSumAbsoluteDifferences(int[] nums) { 3 | int sz = nums.length; 4 | int[] result = new int[sz], prefSum = new int[sz]; 5 | for (int indx = 0; indx < sz; indx++) { 6 | if (indx == 0) 7 | prefSum[indx] = nums[indx]; 8 | else 9 | prefSum[indx] = prefSum[indx - 1] + nums[indx]; 10 | } 11 | for (int indx = 0; indx < sz; indx++) { 12 | int currNum = nums[indx]; 13 | int leftSum = currNum * (indx + 1) - prefSum[indx]; 14 | int rightSum = (prefSum[sz - 1] - prefSum[indx] - (sz - 1 - indx) * currNum); 15 | result[indx] = leftSum + rightSum; 16 | } 17 | return result; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Leet_Code_Leet/Unique Length-3 Palindromic Subsequences.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countPalindromicSubsequence(String inputString) { 3 | // Arrays to store the minimum and maximum occurrences of each character in the 4 | // input string 5 | int[] minExist = new int[26]; 6 | int[] maxExist = new int[26]; 7 | for (int i = 0; i < 26; i++) { 8 | minExist[i] = Integer.MAX_VALUE; 9 | maxExist[i] = Integer.MIN_VALUE; 10 | } 11 | 12 | // Populate minExist and maxExist arrays 13 | for (int i = 0; i < inputString.length(); i++) { 14 | int charIndex = inputString.charAt(i) - 'a'; 15 | minExist[charIndex] = Math.min(minExist[charIndex], i); 16 | maxExist[charIndex] = Math.max(maxExist[charIndex], i); 17 | } 18 | 19 | // Variable to store the final count of unique palindromic subsequences 20 | int uniqueCount = 0; 21 | 22 | // Iterate over each character in the alphabet 23 | for (int charIndex = 0; charIndex < 26; charIndex++) { 24 | // Check if the character has occurred in the input string 25 | if (minExist[charIndex] == Integer.MAX_VALUE || maxExist[charIndex] == Integer.MIN_VALUE) { 26 | continue; // No occurrences, move to the next character 27 | } 28 | 29 | // Set to store unique characters between the minimum and maximum occurrences 30 | HashSet uniqueCharsBetween = new HashSet<>(); 31 | 32 | // Iterate over the characters between the minimum and maximum occurrences 33 | for (int j = minExist[charIndex] + 1; j < maxExist[charIndex]; j++) { 34 | uniqueCharsBetween.add(inputString.charAt(j)); 35 | } 36 | 37 | // Add the count of unique characters between the occurrences to the final count 38 | uniqueCount += uniqueCharsBetween.size(); 39 | } 40 | 41 | // Return the total count of unique palindromic subsequences 42 | return uniqueCount; 43 | } 44 | } -------------------------------------------------------------------------------- /Magic_Squares_In_Grid.java: -------------------------------------------------------------------------------- 1 | package Auguest; 2 | 3 | import java.util.*; 4 | 5 | public class Magic_Squares_In_Grid { 6 | private boolean isMagicSquare(int[][] grid, int i, int j) { 7 | // Check for distinct numbers from 1 to 9 8 | boolean[] seen = new boolean[10]; 9 | for (int x = 0; x < 3; x++) { 10 | for (int y = 0; y < 3; y++) { 11 | int num = grid[i + x][j + y]; 12 | if (num < 1 || num > 9 || seen[num]) 13 | return false; 14 | seen[num] = true; 15 | } 16 | } 17 | 18 | int sum = grid[i][j] + grid[i][j + 1] + grid[i][j + 2]; // First row sum 19 | 20 | // Check rows 21 | for (int x = 0; x < 3; x++) { 22 | if (sum != grid[i + x][j] + grid[i + x][j + 1] + grid[i + x][j + 2]) 23 | return false; 24 | } 25 | 26 | // Check columns 27 | for (int y = 0; y < 3; y++) { 28 | if (sum != grid[i][j + y] + grid[i + 1][j + y] + grid[i + 2][j + y]) 29 | return false; 30 | } 31 | 32 | // Check diagonals 33 | if (sum != grid[i][j] + grid[i + 1][j + 1] + grid[i + 2][j + 2]) 34 | return false; 35 | if (sum != grid[i + 2][j] + grid[i + 1][j + 1] + grid[i][j + 2]) 36 | return false; 37 | 38 | return true; 39 | } 40 | 41 | public int numMagicSquaresInside(int[][] grid) { 42 | int count = 0; 43 | int rows = grid.length; 44 | int cols = grid[0].length; 45 | 46 | for (int i = 0; i <= rows - 3; i++) { 47 | for (int j = 0; j <= cols - 3; j++) { 48 | if (isMagicSquare(grid, i, j)) { 49 | count++; 50 | } 51 | } 52 | } 53 | 54 | return count; 55 | } 56 | 57 | public static void main(String[] args) { 58 | 59 | } 60 | } -------------------------------------------------------------------------------- /Maximum-Product-of-Two-Elements-in-an-Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProduct(int[] nums) { 3 | int max1 = Integer.MIN_VALUE; 4 | int max2 = Integer.MIN_VALUE; 5 | 6 | for (int num : nums) { 7 | if (num >= max1) { 8 | max2 = max1; 9 | max1 = num; 10 | } else if (num > max2) { 11 | max2 = num; 12 | } 13 | } 14 | 15 | return (max1 - 1) * (max2 - 1); 16 | } 17 | } -------------------------------------------------------------------------------- /Maximum_Element_After_Decreasing_and_Rearranging.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Maximum_Element_After_Decreasing_and_Rearranging { 4 | 5 | public int maximumElementAfterDecrementingAndRearranging(int[] arr) { 6 | Arrays.sort(arr); 7 | int res = 1; 8 | for (int i = 1; i < arr.length; ++i) { 9 | if (arr[i] > res) { 10 | ++res; 11 | } 12 | } 13 | return res; 14 | } 15 | 16 | public static void main(String[] args) { 17 | Maximum_Element_After_Decreasing_and_Rearranging solution = new Maximum_Element_After_Decreasing_and_Rearranging(); 18 | 19 | // Example usage: 20 | int[] arr = { 2, 2, 1, 2, 1 }; 21 | int result = solution.maximumElementAfterDecrementingAndRearranging(arr); 22 | System.out.println("The maximum element after decrementing and rearranging is: " + result); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Maximum_Meetings_in_One_Room.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static class Pair { 3 | int s; 4 | int f; 5 | int ind; 6 | 7 | Pair(int s, int f, int ind) { 8 | this.s = s; 9 | this.f = f; 10 | this.ind = ind; 11 | } 12 | 13 | } 14 | 15 | public static ArrayList maxMeetings(int N, int[] S, int[] F) { 16 | // code here 17 | List list = new ArrayList<>(); 18 | for (int i = 0; i < N; i++) { 19 | list.add(new Pair(S[i], F[i], i + 1)); 20 | } 21 | Collections.sort(list, (a, b) -> a.f - b.f); 22 | ArrayList ans = new ArrayList<>(); 23 | int last = -1; 24 | for (int i = 0; i < N; i++) { 25 | if (list.get(i).s > last) { 26 | ans.add(list.get(i).ind); 27 | last = list.get(i).f; 28 | } 29 | } 30 | Collections.sort(ans); 31 | return ans; 32 | } 33 | } -------------------------------------------------------------------------------- /Maximum_Number_of_Coins_You_Can_Get.java: -------------------------------------------------------------------------------- 1 | public class Maximum_Number_of_Coins_You_Can_Get { 2 | public int maxCoins(int[] piles) { 3 | int max = 0; 4 | int n = piles.length; 5 | 6 | for (int i : piles) { 7 | if (max < i) 8 | max = i; 9 | } 10 | 11 | int[] freq = new int[max + 1]; 12 | 13 | for (int i : piles) { 14 | freq[i]++; 15 | } 16 | 17 | int coins = 0; 18 | int chance = n / 3; 19 | 20 | int turn = 1; 21 | int i = max; 22 | 23 | while (chance != 0) { 24 | if (freq[i] > 0) { 25 | if (turn == 1) 26 | turn = 0; 27 | else { 28 | chance--; 29 | turn = 1; 30 | coins += i; 31 | } 32 | freq[i]--; 33 | } else { 34 | i--; 35 | } 36 | } 37 | 38 | return coins; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Maximum_Product_Difference_Between_Two_Pairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProductDifference(int[] nums) { 3 | int firstBig = 0, secondBig = 0; 4 | int firstSmall = Integer.MAX_VALUE, secondSmall = Integer.MAX_VALUE; 5 | 6 | for (int n : nums) { 7 | if (n < firstSmall) { 8 | secondSmall = firstSmall; 9 | firstSmall = n; 10 | } else if (n < secondSmall) { 11 | secondSmall = n; 12 | } 13 | 14 | if (n > firstBig) { 15 | secondBig = firstBig; 16 | firstBig = n; 17 | } else if (n > secondBig) { 18 | secondBig = n; 19 | } 20 | } 21 | 22 | return firstBig * secondBig - firstSmall * secondSmall; 23 | } 24 | } -------------------------------------------------------------------------------- /Minimize_Maximum_Pair_Sum_in_Array.java: -------------------------------------------------------------------------------- 1 | class Minimize_Maximum_Pair_Sum_in_Array { 2 | public int minPairSum(int[] nums) { 3 | int max = Integer.MIN_VALUE; 4 | int min = Integer.MAX_VALUE; 5 | int hash[] = new int[100001]; 6 | for (int num : nums) { 7 | hash[num]++; 8 | max = Math.max(max, num); 9 | min = Math.min(min, num); 10 | } 11 | 12 | int low = min; 13 | int high = max; 14 | max = Integer.MIN_VALUE; 15 | while (low <= high) { 16 | if (hash[low] == 0) 17 | low++; 18 | else if (hash[high] == 0) 19 | high--; 20 | else { 21 | max = Math.max(max, low + high); 22 | hash[low]--; 23 | hash[high]--; 24 | } 25 | } 26 | return max; 27 | } 28 | } -------------------------------------------------------------------------------- /Minimum Time to Make Rope Colorful.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minCost(String colors, int[] neededTime) { 3 | int totalTime = 0; 4 | int i = 0, j = 0; 5 | 6 | while (i < neededTime.length && j < neededTime.length) { 7 | int currTotal = 0, currMax = 0; 8 | 9 | while (j < neededTime.length && colors.charAt(i) == colors.charAt(j)) { 10 | currTotal += neededTime[j]; 11 | currMax = Math.max(currMax, neededTime[j]); 12 | j++; 13 | } 14 | 15 | totalTime += currTotal - currMax; 16 | i = j; 17 | } 18 | return totalTime; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Minimum_Amount_of_Time_to_Collect_Garbage.java: -------------------------------------------------------------------------------- 1 | public class Minimum_Amount_of_Time_to_Collect_Garbage { 2 | public int garbageCollection(String[] garbage, int[] travel) { 3 | int n = garbage.length; 4 | int ans = 0; 5 | for (int i = 0; i < n - 1; i++) { 6 | ans += 3 * travel[i]; 7 | } 8 | for (String s : garbage) { 9 | ans += s.length(); 10 | } 11 | for (int i = n - 1; i > 0; i--) { 12 | if (!garbage[i].contains("G")) { 13 | ans -= travel[i - 1]; 14 | } else { 15 | break; 16 | } 17 | } 18 | for (int i = n - 1; i > 0; i--) { 19 | if (!garbage[i].contains("P")) { 20 | ans -= travel[i - 1]; 21 | } else { 22 | break; 23 | } 24 | } 25 | for (int i = n - 1; i > 0; i--) { 26 | if (!garbage[i].contains("M")) { 27 | ans -= travel[i - 1]; 28 | } else { 29 | break; 30 | } 31 | } 32 | return ans; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Minimum_Changes_To_Make_Alternating_Binary_String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minOperations(String s) { 3 | char c_0 = s.charAt(0); 4 | int count1 = count(s, c_0); 5 | int count2 = count(s, c_0 == '0' ? '1' : '0') + 1; 6 | return Math.min(count1, count2); 7 | } 8 | 9 | private int count(String s, char c_pre) { 10 | int count = 0; 11 | for (int i = 1; i < s.length(); i++) { 12 | char current = s.charAt(i); 13 | if (current == c_pre) { 14 | count++; 15 | c_pre = c_pre == '0' ? '1' : '0'; 16 | } else { 17 | c_pre = current; 18 | } 19 | } 20 | return count; 21 | } 22 | } -------------------------------------------------------------------------------- /Minimum_Number_of_Pushes_to_Type_Word.java: -------------------------------------------------------------------------------- 1 | package Auguest; 2 | 3 | import java.util.*; 4 | 5 | public class Minimum_Number_of_Pushes_to_Type_Word { 6 | public int minimumPushes(String word) { 7 | HashMap map = new HashMap<>(); 8 | for (int i = 0; i < word.length(); i++) { 9 | char c = word.charAt(i); 10 | map.put(c, map.getOrDefault(c, 0) + 1); 11 | 12 | } 13 | PriorityQueue> maxHeap = new PriorityQueue<>( 14 | (entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue())); 15 | 16 | maxHeap.addAll(map.entrySet()); 17 | int count = 0; 18 | for (int j = 1; j <= map.size(); j++) { 19 | Map.Entry entry = maxHeap.poll(); 20 | if (j <= 8) /* 21 | * calculates pushes for used character that should be priotised first and so on 22 | * for rest of condition according to priority 23 | */ 24 | count += entry.getValue(); 25 | else if (j > 8 && j <= 16) 26 | count += entry.getValue() * 2; 27 | else if (j > 16 && j <= 24) 28 | count += entry.getValue() * 3; 29 | else 30 | count += entry.getValue() * 4; 31 | } 32 | return count; 33 | } 34 | 35 | public static void main(String[] args) { 36 | 37 | } 38 | } -------------------------------------------------------------------------------- /Minimum_One_Bit_Operations_to_Make_Integers_Zero.java: -------------------------------------------------------------------------------- 1 | public class Minimum_One_Bit_Operations_to_Make_Integers_Zero { 2 | int min = Integer.MAX_VALUE; 3 | 4 | public int minimumOneBitOperations(int n) { 5 | if (n <= 1) 6 | return n; 7 | int count = 0; 8 | while ((1 << count) <= n) 9 | count++; 10 | return ((1 << count) - 1) - minimumOneBitOperations(n - (1 << (count - 1))); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Minimum_Time_Visiting_All_Points.java: -------------------------------------------------------------------------------- 1 | public class Minimum_Time_Visiting_All_Points { 2 | public int toTime(int[] from, int[] to) { 3 | int xDiff = Math.abs(from[0] - to[0]); 4 | int yDiff = Math.abs(from[1] - to[1]); 5 | 6 | return Math.max(xDiff, yDiff); 7 | } 8 | 9 | public int minTimeToVisitAllPoints(int[][] points) { 10 | int time = 0; 11 | 12 | for (int i = 1; i < points.length; i++) { 13 | time += toTime(points[i - 1], points[i]); 14 | } 15 | 16 | return time; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Number-of-Dice-Rolls-With-Target-Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numRollsToTarget(int n, int k, int target) { 3 | final int MOD = 1000000007; 4 | 5 | // Check if it's impossible to reach the target with the given number of dice 6 | // and faces 7 | if (n * k < target) { 8 | return 0; 9 | } 10 | 11 | // Initialize a 2D array to store the number of ways to achieve each target sum 12 | // using a specific number of dice 13 | long[][] dp = new long[n + 1][target + 1]; 14 | 15 | // Base case: There is one way to get a sum of 0 with 0 dice 16 | dp[0][0] = 1; 17 | 18 | // Dynamic Programming: Iterate over the number of dice and target sums 19 | for (int i = 1; i <= n; i++) { 20 | for (int j = i; j <= Math.min(i * k, target); j++) { 21 | for (int temp = 1; temp <= Math.min(k, j); temp++) { 22 | // Update the number of ways to achieve the current target sum 23 | dp[i][j] = (dp[i][j] + dp[i - 1][j - temp]) % MOD; 24 | } 25 | } 26 | } 27 | 28 | // Return the result, cast to integer 29 | return (int) dp[n][target]; 30 | } 31 | } -------------------------------------------------------------------------------- /Number_of_1_Bits.java: -------------------------------------------------------------------------------- 1 | public class Number_of_1_Bits { 2 | public int hammingWeight(int n) { 3 | int count = 0; 4 | while (n != 0) { 5 | n = n & (n - 1); 6 | count++; 7 | } 8 | return count; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Path_Crossing.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPathCrossing(String path) { 3 | Map> moves = new HashMap(); 4 | moves.put('N', new Pair(0, 1)); 5 | moves.put('S', new Pair(0, -1)); 6 | moves.put('W', new Pair(-1, 0)); 7 | moves.put('E', new Pair(1, 0)); 8 | 9 | Set> visited = new HashSet(); 10 | visited.add(new Pair(0, 0)); 11 | 12 | int x = 0; 13 | int y = 0; 14 | 15 | for (Character c : path.toCharArray()) { 16 | Pair curr = moves.get(c); 17 | int dx = curr.getKey(); 18 | int dy = curr.getValue(); 19 | x += dx; 20 | y += dy; 21 | 22 | Pair pair = new Pair(x, y); 23 | if (visited.contains(pair)) { 24 | return true; 25 | } 26 | 27 | visited.add(pair); 28 | } 29 | 30 | return false; 31 | } 32 | } -------------------------------------------------------------------------------- /Poor Pigs.java: -------------------------------------------------------------------------------- 1 | public class Poor Pigs 2 | { 3 | 4 | public int poorPigs(int buckets, int timeToDie, int timeToTest) { 5 | int testsPerPig = timeToTest / timeToDie; 6 | int numPigs = 0; 7 | int states = 1; // Number of unique states a pig can represent 8 | while (states < buckets) { 9 | states *= (testsPerPig + 1); 10 | numPigs++; 11 | } 12 | return numPigs; 13 | } 14 | } -------------------------------------------------------------------------------- /Range_Sum_of_Sorted_Subarray_Sums.java: -------------------------------------------------------------------------------- 1 | package Auguest; 2 | 3 | import java.util.*; 4 | 5 | public class Range_Sum_of_Sorted_Subarray_Sums { 6 | public int rangeSum(int[] nums, int n, int left, int right) { 7 | List subarraySum = new ArrayList<>(); 8 | 9 | // Calculating sum of subarrays 10 | for (int i = 0; i < nums.length; i++) { 11 | int sum = 0; 12 | for (int j = i; j < nums.length; j++) { 13 | sum += nums[j]; 14 | subarraySum.add(sum); 15 | } 16 | } 17 | 18 | // Sort the subarray sums 19 | Collections.sort(subarraySum); 20 | 21 | // Return the result 22 | long result = 0; 23 | int mod = (int) (1e9 + 7); 24 | for (int i = left - 1; i < right; i++) { 25 | result = (result + subarraySum.get(i)) % mod; 26 | } 27 | return (int) result; 28 | } 29 | 30 | public static void main(String[] args) { 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /Reduction_Operations_to_Make_the_Array_Elements_Equal.java: -------------------------------------------------------------------------------- 1 | class Reduction_Operations_to_Make_the_Array_Elements_Equal { 2 | public int reductionOperations(int[] nums) { 3 | int n = nums.length; 4 | int[] freq = new int[50001]; 5 | for (int i = 0; i < n; i++) { 6 | freq[nums[i]]++; 7 | } 8 | int res = 0, operations = 0; 9 | for (int i = 50000; i >= 1; i--) { 10 | if (freq[i] > 0) { 11 | operations += freq[i]; 12 | res += operations - freq[i]; 13 | } 14 | } 15 | return res; 16 | } 17 | } -------------------------------------------------------------------------------- /Restore the Array From Adjacent Pairs.java: -------------------------------------------------------------------------------- 1 | public class Restore 2 | the Array 3 | From Adjacent Pairs 4 | { 5 | 6 | public int[] restoreArray(int[][] adjacentPairs) { 7 | int n = adjacentPairs.length; 8 | int m = adjacentPairs[0].length; 9 | int ans[] = new int[n + 1]; 10 | HashSet set = new HashSet<>();// stores all the unique elements 11 | for (int i = 0; i < n; i++) { 12 | for (int j = 0; j < m; j++) { 13 | set.add(adjacentPairs[i][j]); 14 | } 15 | } 16 | HashMap> map = new HashMap<>();// stores adjacent elements for each element 17 | for (int k : set) { 18 | ArrayList temp = new ArrayList<>(); 19 | map.put(k, temp); 20 | } 21 | for (int i = 0; i < n; i++) { 22 | map.get(adjacentPairs[i][0]).add(adjacentPairs[i][1]); 23 | map.get(adjacentPairs[i][1]).add(adjacentPairs[i][0]); 24 | } 25 | // Reconstructing the array 26 | int start = 0; 27 | for (int key : map.keySet()) { 28 | if (map.get(key).size() == 1) { 29 | start = key; 30 | break; 31 | } 32 | } 33 | ans[0] = start; 34 | ans[1] = map.get(start).get(0); 35 | 36 | for (int i = 2; i < n + 1; i++) { 37 | ArrayList neighbours = map.get(ans[i - 1]); 38 | ans[i] = (ans[i - 2] == neighbours.get(0) ? neighbours.get(1) : neighbours.get(0)); 39 | } 40 | return ans; 41 | } 42 | }} 43 | -------------------------------------------------------------------------------- /Seat Reservation Manager.java: -------------------------------------------------------------------------------- 1 | class SeatManager { 2 | private PriorityQueue seats; // Declare a priority queue to manage seat reservations. 3 | 4 | // Constructor to initialize the SeatManager with 'n' seats. 5 | public SeatManager(int n) { 6 | seats = new PriorityQueue<>(); 7 | // Initialize the priority queue with seat numbers from 1 to 'n'. 8 | for (int i = 1; i <= n; i++) { 9 | seats.offer(i); 10 | } 11 | } 12 | 13 | // Reserve a seat. 14 | public int reserve() { 15 | if (!seats.isEmpty()) { // Check if there are available seats in the priority queue. 16 | int reservedSeat = seats.poll(); // Get the smallest seat number from the queue. 17 | return reservedSeat; // Return the reserved seat number. 18 | } else { 19 | return -1; // Return -1 to indicate that there are no available seats. 20 | } 21 | } 22 | 23 | // Unreserve a seat. 24 | public void unreserve(int seatNumber) { 25 | seats.offer(seatNumber); // Add the unreserved seat back to the priority queue. 26 | } 27 | } -------------------------------------------------------------------------------- /So.java: -------------------------------------------------------------------------------- 1 | public public class Solution { 2 | private static final int MOD = 1000000007; 3 | 4 | public int numFactoredBinaryTrees(int[] arr) { 5 | // Step 1: Sort the input array in ascending order. 6 | Arrays.sort(arr); 7 | 8 | // Create a set to make the containment check faster. 9 | Set uniqueNumbers = new HashSet<>(); 10 | for (int num : arr) { 11 | uniqueNumbers.add(num); 12 | } 13 | 14 | // Step 2: Initialize a map to store the number of binary trees that end with each element in the array. 15 | Map dp = new HashMap<>(); 16 | for (int num : arr) { 17 | dp.put(num, 1); 18 | } 19 | 20 | // Step 3: Dynamic Programming 21 | for (int i : arr) { 22 | for (int j : arr) { 23 | // If j is larger than the square root of i, break the loop because further j values won't be factors. 24 | if (j > Math.sqrt(i)) break; 25 | 26 | // Check if j is a factor of i and i/j is in the set of unique numbers. 27 | if (i % j == 0 && uniqueNumbers.contains(i / j)) { 28 | long product = (long) dp.get(j) * dp.get(i / j); 29 | 30 | // Update the number of binary trees ending with i based on the factors j and i/j. 31 | dp.put(i, (int) ((dp.get(i) + (i / j == j ? product : product * 2)) % MOD)); 32 | } 33 | } 34 | } 35 | 36 | // Step 4: Calculate the final result. 37 | int result = 0; 38 | for (int value : dp.values()) { 39 | result = (result + value) % MOD; 40 | } 41 | return result; 42 | } 43 | } { 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Solution!.java: -------------------------------------------------------------------------------- 1 | public public class Solution!{ 2 | public int countVowelPermutation(int n) { 3 | final int MOD = 1000000007; 4 | 5 | long countA = 1, countE = 1, countI = 1, countO = 1, countU = 1; 6 | 7 | for (int length = 1; length < n; length++) { 8 | // Calculate the next counts for each vowel based on the previous counts 9 | long nextCountA = countE; 10 | long nextCountE = (countA + countI) % MOD; 11 | long nextCountI = (countA + countE + countO + countU) % MOD; 12 | long nextCountO = (countI + countU) % MOD; 13 | long nextCountU = countA; 14 | 15 | // Update the counts with the newly calculated values for the next length 16 | countA = nextCountA; 17 | countE = nextCountE; 18 | countI = nextCountI; 19 | countO = nextCountO; 20 | countU = nextCountU; 21 | } 22 | 23 | // Calculate the total count of valid strings for length n 24 | long totalCount = (countA + countE + countI + countO + countU) % MOD; 25 | 26 | return (int) totalCount; 27 | } 28 | } { 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int kthGrammar(int n, int k) { 3 | // Initialize a flag to track if the values of k and the first element are the same. 4 | boolean areValuesSame = true; 5 | 6 | // Calculate the total number of elements in the nth row, which is 2^(n-1). 7 | n = (int) Math.pow(2, n - 1); 8 | 9 | // Continue until we reach the first row. 10 | while (n != 1) { 11 | // Halve the number of elements in the row. 12 | n /= 2; 13 | 14 | // If k is in the second half of the row, adjust k and toggle the flag. 15 | if (k > n) { 16 | k -= n; 17 | areValuesSame = !areValuesSame; 18 | } 19 | } 20 | 21 | // Return 0 if the flag indicates that the values are the same; otherwise, return 1. 22 | return (areValuesSame ? 0 : 1); 23 | } 24 | } -------------------------------------------------------------------------------- /Solution1.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution1 { 4 | public int[] fullBloomFlowers(int[][] flowers, int[] people) { 5 | // Create a list of Flower objects to keep track of bloom times 6 | List flowerList = new ArrayList<>(); 7 | for (int i = 0; i < flowers.length; i++) { 8 | flowerList.add(new Flower(flowers[i][0], flowers[i][1])); 9 | } 10 | 11 | // Sort the list of flowers based on their bloom times 12 | Collections.sort(flowerList, (a, b) -> a.bloomTime - b.bloomTime); 13 | 14 | int[] result = new int[people.length]; 15 | int bloomIndex = 0; // Index to track the current flower in bloom 16 | 17 | for (int i = 0; i < people.length; i++) { 18 | int personTime = people[i]; 19 | 20 | // Count flowers in full bloom when the person arrives 21 | while (bloomIndex < flowerList.size() && flowerList.get(bloomIndex).bloomTime <= personTime) { 22 | bloomIndex++; 23 | } 24 | result[i] = bloomIndex; 25 | } 26 | 27 | return result; 28 | } 29 | 30 | private class Flower { 31 | int bloomTime; 32 | int wiltTime; 33 | 34 | public Flower(int bloomTime, int wiltTime) { 35 | this.bloomTime = bloomTime; 36 | this.wiltTime = wiltTime; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Solution10.java: -------------------------------------------------------------------------------- 1 | public class Solution10 { 2 | class Solution { 3 | public int constrainedSubsetSum(int[] nums, int k) { 4 | int n = nums.length; 5 | int[] dp = new int[n]; 6 | int res = nums[0]; 7 | Queue queue = new PriorityQueue<>((a, b) -> dp[b] - dp[a]); // Declaring Max heap 8 | 9 | Arrays.fill(dp, Integer.MIN_VALUE); 10 | dp[0] = nums[0]; 11 | queue.offer(0); 12 | 13 | for (int j = 1; j < n; j++) { 14 | int i = Math.max(j - k, 0); // get the furthest index possible 15 | while (!queue.isEmpty() && queue.peek() < i) 16 | queue.poll(); // find the global max in the specified range for that particular j index 17 | int idx = queue.peek(); 18 | dp[j] = Math.max(dp[idx] + nums[j], nums[j]); 19 | res = Math.max(res, dp[j]); 20 | queue.offer(j); 21 | } 22 | return res; 23 | } 24 | 25 | public static void main(String[] args) { 26 | 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Solution11.java: -------------------------------------------------------------------------------- 1 | class Solution11 { 2 | public int maximumScore(int[] nums, int k) { 3 | 4 | int left = k - 1; 5 | int right = k + 1; 6 | int minvalue = nums[k]; 7 | int maxscore = nums[k]; 8 | int length = nums.length; 9 | 10 | while (left >= 0 || right < length) { 11 | if (left >= 0 && right < length && nums[left] >= nums[right]) { 12 | minvalue = Math.min(minvalue, nums[left]); 13 | maxscore = Math.max(maxscore, (right - left) * minvalue); 14 | left--; 15 | } else if (left >= 0 && right < length && nums[left] <= nums[right]) { 16 | minvalue = Math.min(minvalue, nums[right]); 17 | maxscore = Math.max(maxscore, (right - left) * minvalue); 18 | right++; 19 | } else if (left < 0) { 20 | minvalue = Math.min(minvalue, nums[right]); 21 | maxscore = Math.max(maxscore, (right - left) * minvalue); 22 | right++; 23 | } else { 24 | minvalue = Math.min(minvalue, nums[left]); 25 | maxscore = Math.max(maxscore, (right - left) * minvalue); 26 | left--; 27 | } 28 | } 29 | return maxscore; 30 | } 31 | } -------------------------------------------------------------------------------- /Solution12.java: -------------------------------------------------------------------------------- 1 | class Solution12 { 2 | public boolean isPowerOfFour(int n) { 3 | if (n == 0) 4 | return false; 5 | if (n == 1) 6 | return true; 7 | if (n % 4 != 0) 8 | return false; 9 | 10 | return isPowerOfFour(n / 4); 11 | } 12 | } -------------------------------------------------------------------------------- /Solution13.java: -------------------------------------------------------------------------------- 1 | class Solution13 { 2 | public List largestValues(TreeNode root) { 3 | Queue queue = new LinkedList<>(); 4 | List ans = new ArrayList<>(); 5 | queue.offer(root); 6 | if (root == null) 7 | return ans; 8 | while (!queue.isEmpty()) { 9 | int level = queue.size(); 10 | int max = Integer.MIN_VALUE; 11 | for (int i = 0; i < level; i++) { 12 | TreeNode temp = queue.poll(); 13 | if (temp.left != null) { 14 | queue.offer(temp.left); 15 | } 16 | if (temp.right != null) { 17 | queue.offer(temp.right); 18 | } 19 | max = Math.max(max, temp.val); 20 | } 21 | ans.add(max); 22 | } 23 | return ans; 24 | } 25 | } -------------------------------------------------------------------------------- /Solution14.java: -------------------------------------------------------------------------------- 1 | public class Solution14 { 2 | public String longestPalindrome(String s) { 3 | if (s.length() <= 1) { 4 | return s; 5 | } 6 | 7 | int maxLen = 1; 8 | String maxStr = s.substring(0, 1); 9 | 10 | for (int i = 0; i < s.length(); i++) { 11 | for (int j = i + maxLen; j <= s.length(); j++) { 12 | if (j - i > maxLen && isPalindrome(s.substring(i, j))) { 13 | maxLen = j - i; 14 | maxStr = s.substring(i, j); 15 | } 16 | } 17 | } 18 | 19 | return maxStr; 20 | } 21 | 22 | private boolean isPalindrome(String str) { 23 | int left = 0; 24 | int right = str.length() - 1; 25 | 26 | while (left < right) { 27 | if (str.charAt(left) != str.charAt(right)) { 28 | return false; 29 | } 30 | left++; 31 | right--; 32 | } 33 | 34 | return true; 35 | } 36 | } -------------------------------------------------------------------------------- /Solution2.java: -------------------------------------------------------------------------------- 1 | public class Solution2 { 2 | 3 | public int findInMountainArray(int target, MountainArray mountainArray) { 4 | int peak = peakIndex(mountainArray); 5 | int index = binarySearch(mountainArray, target,0,peak); 6 | if(index!=-1) 7 | { 8 | return index; 9 | } 10 | return binarySearch(mountainArray,target, peak+1,mountainArray.length()-1); 11 | } 12 | private int peakIndex(MountainArray mountainArray) 13 | { 14 | int left=0; 15 | int right = mountainArray.length()-1; 16 | while(leftmountainArray.get(mid+1)) 20 | { 21 | right = mid; 22 | } 23 | else 24 | { 25 | left = mid+1; 26 | } 27 | } 28 | return left; 29 | } 30 | private int binarySearch(MountainArray mountainArray, int target, int left , int right) 31 | { 32 | boolean isAscending = mountainArray.get(left)midElement) 46 | { 47 | left=mid+1; 48 | } 49 | else 50 | { 51 | right=mid-1; 52 | } 53 | } 54 | else 55 | { 56 | if(target>midElement) 57 | { 58 | right=mid-1; 59 | } 60 | else 61 | { 62 | left=mid+1; 63 | } 64 | } 65 | } 66 | return -1; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Solution3.java: -------------------------------------------------------------------------------- 1 | class Solution3 { 2 | public int minCostClimbingStairs(int[] cost) { 3 | int n = cost.length; 4 | for(int i=n-3;i>=0;i--){ 5 | cost[i] += Math.min(cost[i+1],cost[i+2]); 6 | } 7 | return Math.min(cost[0],cost[1]); 8 | } 9 | } -------------------------------------------------------------------------------- /Solution4.java: -------------------------------------------------------------------------------- 1 | class Solution4 { 2 | public int paintWalls(int[] cost, int[] time) { 3 | // code 4 | int n = cost.length; 5 | int[][] dp = new int[n + 1][n + 1]; 6 | 7 | for (int i = 1; i <= n; i++) { 8 | dp[n][i] = (int) 1e9; 9 | } 10 | int opt1; 11 | int opt2; 12 | for (int i = n - 1; i >= 0; i--) { 13 | for (int remain = 1; remain <= n; remain++) { 14 | opt1 = cost[i] + dp[i + 1][Math.max(0, remain - 1 - time[i])]; 15 | opt2 = dp[i + 1][remain]; 16 | dp[i][remain] = Math.min(opt1, opt2); 17 | } 18 | } 19 | 20 | return dp[0][n]; 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /Solution5.java: -------------------------------------------------------------------------------- 1 | class Solution5 { 2 | public List getRow(int rowIndex) { 3 | List> pascalTriangle = new ArrayList<>(); 4 | 5 | // Generate the Pascal's Triangle up to the rowIndex 6 | for (int i = 0; i <= rowIndex; i++) { 7 | List row = new ArrayList<>(); 8 | 9 | for (int j = 0; j <= i; j++) { 10 | if (j == 0 || j == i) { 11 | row.add(1); 12 | } else { 13 | // Calculate the value in the middle based on the values from the previous row. 14 | List prevRow = pascalTriangle.get(i - 1); 15 | int value = prevRow.get(j - 1) + prevRow.get(j); 16 | row.add(value); 17 | } 18 | } 19 | 20 | pascalTriangle.add(row); 21 | } 22 | 23 | // The result is the row at the given rowIndex. 24 | return pascalTriangle.get(rowIndex); 25 | } 26 | } -------------------------------------------------------------------------------- /Solution6.java: -------------------------------------------------------------------------------- 1 | class Solution6 { 2 | public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) { 3 | Map> graph = new HashMap<>(); 4 | int[] inDegree = new int[n]; 5 | 6 | for (int node = 0; node < n; node++) { 7 | int left = leftChild[node]; 8 | int right = rightChild[node]; 9 | if (left != -1) { 10 | graph.computeIfAbsent(node, k -> new ArrayList<>()).add(left); 11 | inDegree[left]++; 12 | } 13 | if (right != -1) { 14 | graph.computeIfAbsent(node, k -> new ArrayList<>()).add(right); 15 | inDegree[right]++; 16 | } 17 | } 18 | 19 | List rootCandidates = new ArrayList<>(); 20 | for (int node = 0; node < n; node++) { 21 | if (inDegree[node] == 0) { 22 | rootCandidates.add(node); 23 | } 24 | } 25 | 26 | if (rootCandidates.size() != 1) { 27 | return false; 28 | } 29 | int root = rootCandidates.get(0); 30 | 31 | Queue queue = new LinkedList<>(); 32 | Set seen = new HashSet<>(); 33 | queue.add(root); 34 | seen.add(root); 35 | 36 | while (!queue.isEmpty()) { 37 | int node = queue.poll(); 38 | if (graph.containsKey(node)) { 39 | for (int child : graph.get(node)) { 40 | if (seen.contains(child)) { 41 | return false; 42 | } 43 | seen.add(child); 44 | queue.add(child); 45 | } 46 | } 47 | } 48 | 49 | return seen.size() == n; 50 | } 51 | } -------------------------------------------------------------------------------- /Solution7.java: -------------------------------------------------------------------------------- 1 | class Solution7 { 2 | private int[] startNodes; 3 | private int[][] graph; 4 | private int[] time; 5 | private boolean[] visited; 6 | private int[] ans; 7 | 8 | private void toGraph(int[][] edges, int n) { 9 | int[] incoming = new int[n], outgoing = new int[n]; 10 | for (int[] e : edges) { 11 | outgoing[e[0] - 1]++; 12 | incoming[e[1] - 1]++; 13 | } 14 | int startCnt = 0; 15 | for (int i : incoming) { 16 | if (i == 0) { 17 | startCnt++; 18 | } 19 | } 20 | startNodes = new int[startCnt]; 21 | for (int sni = 0, i = 0; sni < startNodes.length; i++) { 22 | if (incoming[i] == 0) { 23 | startNodes[sni++] = i; 24 | } 25 | } 26 | graph = new int[n][]; 27 | for (int i = 0; i < n; i++) { 28 | graph[i] = new int[outgoing[i]]; 29 | } 30 | for (int[] e : edges) { 31 | graph[e[0] - 1][--outgoing[e[0] - 1]] = e[1] - 1; 32 | } 33 | } 34 | 35 | private int calculate(int node) { 36 | if (ans[node] > 0) { 37 | return ans[node]; 38 | } 39 | 40 | int worstPrereq = 0; 41 | visited[node] = true; 42 | for (int child : graph[node]) { 43 | if (!visited[child]) { 44 | worstPrereq = Math.max(calculate(child), worstPrereq); 45 | } 46 | } 47 | visited[node] = false; 48 | return ans[node] = worstPrereq + time[node]; 49 | } 50 | 51 | public int minimumTime(int n, int[][] relations, int[] time) { 52 | toGraph(relations, n); 53 | this.time = time; 54 | ans = new int[n]; 55 | visited = new boolean[n]; 56 | int longest = 0; 57 | for (int node : startNodes) { 58 | longest = Math.max(longest, calculate(node)); 59 | } 60 | return longest; 61 | } 62 | } -------------------------------------------------------------------------------- /Solution8.java: -------------------------------------------------------------------------------- 1 | class Solution8 { 2 | public boolean backspaceCompare(String s, String t) { 3 | StringBuilder sb1 = new StringBuilder(); 4 | StringBuilder sb2 = new StringBuilder(); 5 | 6 | for (char ch : s.toCharArray()) { 7 | if (ch == '#') { 8 | if (!sb1.isEmpty()) { 9 | sb1.deleteCharAt(sb1.length() - 1); 10 | } 11 | } else { 12 | sb1.append(ch); 13 | } 14 | } 15 | 16 | for (char ch : t.toCharArray()) { 17 | if (ch == '#') { 18 | if (!sb2.isEmpty()) { 19 | sb2.deleteCharAt(sb2.length() - 1); 20 | } 21 | } else { 22 | sb2.append(ch); 23 | } 24 | } 25 | 26 | return sb1.toString().equals(sb2.toString()); 27 | } 28 | } -------------------------------------------------------------------------------- /Solution9.java: -------------------------------------------------------------------------------- 1 | public class Solution9 { 2 | public class NestedIterator implements Iterator { 3 | Deque stack = new ArrayDeque<>(); 4 | 5 | public NestedIterator(List nestedList) { 6 | // Initialize the stack with the provided nested list. 7 | prepareStack(nestedList); 8 | } 9 | 10 | @Override 11 | public Integer next() { 12 | if (!hasNext()) { 13 | return null; // If there's no next element, return null. 14 | } 15 | return stack.pop().getInteger(); // Pop and return the next integer. 16 | } 17 | 18 | @Override 19 | public boolean hasNext() { 20 | while (!stack.isEmpty() && !stack.peek().isInteger()) { 21 | // While the stack is not empty and the top element is a nested list, 22 | // prepare the stack with the elements from that nested list. 23 | List list = stack.pop().getList(); 24 | prepareStack(list); 25 | } 26 | return !stack.isEmpty(); // Check if there's more to iterate. 27 | } 28 | 29 | // Helper function to prepare the stack with a list of nested integers. 30 | private void prepareStack(List nestedList) { 31 | for (int i = nestedList.size() - 1; i >= 0; i--) { 32 | // Push elements onto the stack in reverse order to process them in the correct 33 | // order. 34 | stack.push(nestedList.get(i)); 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Sort Integers by The Number of 1 Bits.java: -------------------------------------------------------------------------------- 1 | public class Sort 2 | Integers by 3 | The Number of 1 Bits 4 | { 5 | 6 | public int[] sortByBits(int[] arr) { 7 | int n = arr.length; 8 | int res[] = new int[n]; 9 | for (int i = 0; i < n; i++) { 10 | res[i] = countBit(arr[i]) * 10001 + arr[i]; 11 | } 12 | Arrays.sort(res); 13 | for (int i = 0; i < n; i++) { 14 | res[i] %= 10001; 15 | } 16 | return res; 17 | } 18 | 19 | private int countBit(int n) { 20 | int res = 0; 21 | while (n != 0) { 22 | res += (n & 1); 23 | n >>= 1; 24 | } 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Sort Vowels in a String.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | // Function to find the minimum number of buses needed to reach the target from 5 | // the source. 6 | public int numBusesToDestination(int[][] routes, int source, int target) { 7 | // If source and target are the same, no buses are needed. 8 | if (source == target) { 9 | return 0; 10 | } 11 | 12 | // Create an adjacency list to represent stops and the routes that include each 13 | // stop. 14 | Map> adjList = new HashMap<>(); 15 | for (int route = 0; route < routes.length; route++) { 16 | for (int stop : routes[route]) { 17 | adjList.computeIfAbsent(stop, k -> new ArrayList<>()).add(route); 18 | } 19 | } 20 | 21 | // Initialize a queue for BFS and a set to keep track of visited routes. 22 | Queue q = new LinkedList<>(); 23 | Set vis = new HashSet<>(); 24 | 25 | // Insert all the routes in the queue that have the source stop. 26 | for (int route : adjList.getOrDefault(source, new ArrayList<>())) { 27 | q.add(route); 28 | vis.add(route); 29 | } 30 | 31 | int busCount = 1; // Initialize the bus count. 32 | 33 | // Perform BFS to find the minimum number of buses needed. 34 | while (!q.isEmpty()) { 35 | int size = q.size(); 36 | 37 | for (int i = 0; i < size; i++) { 38 | int route = q.poll(); 39 | 40 | // Iterate over the stops in the current route. 41 | for (int stop : routes[route]) { 42 | // Return the current count if the target is found. 43 | if (stop == target) { 44 | return busCount; 45 | } 46 | 47 | // Iterate over the next possible routes from the current stop. 48 | for (int nextRoute : adjList.getOrDefault(stop, new ArrayList<>())) { 49 | if (!vis.contains(nextRoute)) { 50 | vis.add(nextRoute); 51 | q.add(nextRoute); 52 | } 53 | } 54 | } 55 | } 56 | busCount++; 57 | } 58 | 59 | // If no route is found, return -1. 60 | return -1; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Special_Positions_in_a_Binary_Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numSpecial(int[][] mat) { 3 | int ans = 0; 4 | int m = mat.length; 5 | int n = mat[0].length; 6 | 7 | for (int row = 0; row < m; row++) { 8 | for (int col = 0; col < n; col++) { 9 | if (mat[row][col] == 0) { 10 | continue; 11 | } 12 | 13 | boolean good = true; 14 | for (int r = 0; r < m; r++) { 15 | if (r != row && mat[r][col] == 1) { 16 | good = false; 17 | break; 18 | } 19 | } 20 | 21 | for (int c = 0; c < n; c++) { 22 | if (c != col && mat[row][c] == 1) { 23 | good = false; 24 | break; 25 | } 26 | } 27 | 28 | if (good) { 29 | ans++; 30 | } 31 | } 32 | } 33 | 34 | return ans; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Spiral_Matrix_III.java: -------------------------------------------------------------------------------- 1 | package Auguest; 2 | 3 | import java.util.*; 4 | 5 | public class Spiral_Matrix_III { 6 | public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { 7 | int[][] directions = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; // East, South, West, North 8 | int[][] result = new int[rows * cols][2]; 9 | int steps = 0, d = 0, len = 0; 10 | 11 | result[0] = new int[] { rStart, cStart }; 12 | int count = 1; 13 | 14 | while (count < rows * cols) { 15 | if (d == 0 || d == 2) 16 | steps++; // Increase step size after moving East or West 17 | 18 | for (int i = 0; i < steps; i++) { 19 | rStart += directions[d][0]; 20 | cStart += directions[d][1]; 21 | 22 | if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) { 23 | result[count++] = new int[] { rStart, cStart }; 24 | } 25 | 26 | if (count == rows * cols) 27 | return result; 28 | } 29 | 30 | d = (d + 1) % 4; // Change direction 31 | } 32 | 33 | return result; 34 | } 35 | 36 | public static void main(String[] args) { 37 | 38 | } 39 | } -------------------------------------------------------------------------------- /String_Compression.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int getLength(int count) { 3 | if (count == 1) return 1; 4 | else if (count < 10) return 2; 5 | else if (count < 100) return 3; 6 | else return 4; 7 | } 8 | 9 | public int getLengthOfOptimalCompression(String s, int k) { 10 | int n = s.length(); 11 | int[][] dp = new int[n + 1][k + 1]; 12 | 13 | for (int i = n; i >= 0; i--) { 14 | for (int j = 0; j <= k; j++) { 15 | // Base case - initial length declaration 16 | if (i == n) { 17 | dp[n][j] = 0; 18 | continue; 19 | } 20 | 21 | // Case 1 - delete the ith character if possible (j > 0) 22 | dp[i][j] = (j > 0) ? dp[i + 1][j - 1] : Integer.MAX_VALUE; 23 | 24 | // Case 2 - we keep the ith index. 25 | // We have to find the current char's index endpoint 26 | int possible_del = j, count = 0; 27 | for (int end = i; end < n && possible_del >= 0; end++) { 28 | // Check about the same char "b b b .." for encoding 29 | if (s.charAt(end) == s.charAt(i)) { 30 | count++; 31 | 32 | // Assuming the block ends here "aaaa" 33 | dp[i][j] = Math.min(dp[i][j], getLength(count) + dp[end + 1][possible_del]); 34 | } else { 35 | // This character should be deleted to make the length min. 36 | possible_del--; 37 | } 38 | } 39 | } 40 | } 41 | 42 | return dp[0][k]; 43 | } 44 | } -------------------------------------------------------------------------------- /Sum-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String sumStrings(String s1, String s2) { 3 | int i = s1.length() - 1, j = s2.length() - 1; 4 | StringBuilder ans = new StringBuilder(); 5 | int carry = 0; 6 | 7 | while (i >= 0 && j >= 0) { 8 | int x = Character.getNumericValue(s1.charAt(i)); 9 | int y = Character.getNumericValue(s2.charAt(j)); 10 | int res = x + y + carry; 11 | int rem = res % 10; 12 | carry = res / 10; 13 | ans.append(rem); 14 | i--; 15 | j--; 16 | } 17 | 18 | while (i >= 0) { 19 | int x = Character.getNumericValue(s1.charAt(i)); 20 | int res = x + carry; 21 | int rem = res % 10; 22 | carry = res / 10; 23 | ans.append(rem); 24 | i--; 25 | } 26 | 27 | while (j >= 0) { 28 | int y = Character.getNumericValue(s2.charAt(j)); 29 | int res = y + carry; 30 | int rem = res % 10; 31 | carry = res / 10; 32 | ans.append(rem); 33 | j--; 34 | } 35 | 36 | while (carry > 0) { 37 | int rem = carry % 10; 38 | ans.append(rem); 39 | carry /= 10; 40 | } 41 | 42 | return ans.reverse().toString(); 43 | } 44 | 45 | public boolean solve(String s, int pos, int l1, int l2) { 46 | String s1 = s.substring(pos, pos + l1); 47 | String s2 = s.substring(pos + l1, pos + l1 + l2); 48 | String s3 = sumStrings(s1, s2); 49 | int n = s3.length(); 50 | 51 | if (n > s.length() - pos - l1 - l2) { 52 | return false; 53 | } 54 | 55 | if (s.substring(pos + l1 + l2, pos + l1 + l2 + n).equals(s3)) { 56 | if (pos + l1 + l2 + n == s.length()) { 57 | return true; 58 | } 59 | return solve(s, pos + l1, l2, n); 60 | } 61 | 62 | return false; 63 | // @pankaj_meharchandai 64 | } 65 | 66 | public int isSumString(String s) { 67 | int n = s.length(); 68 | for (int i = 1; i < n; i++) { 69 | for (int j = 1; j < n - i; j++) { 70 | if (solve(s, 0, i, j)) { 71 | return 1; 72 | } 73 | } 74 | } 75 | return 0; 76 | } 77 | } -------------------------------------------------------------------------------- /Sum_of_Absolute_Differences_in_a_Sorted_Array.java: -------------------------------------------------------------------------------- 1 | public class Sum_of_Absolute_Differences_in_a_Sorted_Array { 2 | public int[] getSumAbsoluteDifferences(int[] nums) { 3 | int sz = nums.length; 4 | int[] result = new int[sz], prefSum = new int[sz]; 5 | for (int indx = 0; indx < sz; indx++) { 6 | if (indx == 0) 7 | prefSum[indx] = nums[indx]; 8 | else 9 | prefSum[indx] = prefSum[indx - 1] + nums[indx]; 10 | } 11 | for (int indx = 0; indx < sz; indx++) { 12 | int currNum = nums[indx]; 13 | int leftSum = currNum * (indx + 1) - prefSum[indx]; 14 | int rightSum = (prefSum[sz - 1] - prefSum[indx] - (sz - 1 - indx) * currNum); 15 | result[indx] = leftSum + rightSum; 16 | } 17 | return result; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Transpose_Matrix.java: -------------------------------------------------------------------------------- 1 | class Transpose_Matrix { 2 | 3 | public int[][] transpose(int[][] matrix) { 4 | int row = matrix.length; 5 | int col = matrix[0].length; 6 | int arr[][] = new int[col][row]; 7 | for (int i = 0; i < col; i++) { 8 | for (int j = 0; j < row; j++) { 9 | arr[i][j] = matrix[j][i]; 10 | } 11 | } 12 | return arr; 13 | } 14 | } -------------------------------------------------------------------------------- /Unique Length-3 Palindromic Subsequences.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countPalindromicSubsequence(String inputString) { 3 | // Arrays to store the minimum and maximum occurrences of each character in the 4 | // input string 5 | int[] minExist = new int[26]; 6 | int[] maxExist = new int[26]; 7 | for (int i = 0; i < 26; i++) { 8 | minExist[i] = Integer.MAX_VALUE; 9 | maxExist[i] = Integer.MIN_VALUE; 10 | } 11 | 12 | // Populate minExist and maxExist arrays 13 | for (int i = 0; i < inputString.length(); i++) { 14 | int charIndex = inputString.charAt(i) - 'a'; 15 | minExist[charIndex] = Math.min(minExist[charIndex], i); 16 | maxExist[charIndex] = Math.max(maxExist[charIndex], i); 17 | } 18 | 19 | // Variable to store the final count of unique palindromic subsequences 20 | int uniqueCount = 0; 21 | 22 | // Iterate over each character in the alphabet 23 | for (int charIndex = 0; charIndex < 26; charIndex++) { 24 | // Check if the character has occurred in the input string 25 | if (minExist[charIndex] == Integer.MAX_VALUE || maxExist[charIndex] == Integer.MIN_VALUE) { 26 | continue; // No occurrences, move to the next character 27 | } 28 | 29 | // Set to store unique characters between the minimum and maximum occurrences 30 | HashSet uniqueCharsBetween = new HashSet<>(); 31 | 32 | // Iterate over the characters between the minimum and maximum occurrences 33 | for (int j = minExist[charIndex] + 1; j < maxExist[charIndex]; j++) { 34 | uniqueCharsBetween.add(inputString.charAt(j)); 35 | } 36 | 37 | // Add the count of unique characters between the occurrences to the final count 38 | uniqueCount += uniqueCharsBetween.size(); 39 | } 40 | 41 | // Return the total count of unique palindromic subsequences 42 | return uniqueCount; 43 | } 44 | } -------------------------------------------------------------------------------- /Valid_Anagram.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Valid_Anagram { 4 | public boolean isAnagram(String s, String t) { 5 | char[] ss = s.toCharArray(), tt = t.toCharArray(); 6 | Arrays.sort(ss); 7 | Arrays.sort(tt); 8 | return Arrays.equals(ss, tt); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Widest_Vertical_Area_Between_Two_Points_Containing_No _Points.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int maxWidthOfVerticalArea(int[][] points) { 5 | Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0])); 6 | int diff = 0; 7 | for (int i = 1; i < points.length; i++) { 8 | diff = Math.max(diff, points[i][0] - points[i - 1][0]); 9 | } 10 | return diff; 11 | } 12 | } --------------------------------------------------------------------------------