├── .gitignore ├── scripts ├── package.json ├── index.js └── package-lock.json ├── _config.yml ├── 2938-separate-black-and-white-balls ├── separate-black-and-white-balls.java └── README.md ├── 921-minimum-add-to-make-parentheses-valid ├── minimum-add-to-make-parentheses-valid.java └── README.md ├── 1963-minimum-number-of-swaps-to-make-the-string-balanced ├── minimum-number-of-swaps-to-make-the-string-balanced.java └── README.md ├── 2044-count-number-of-maximum-bitwise-or-subsets ├── count-number-of-maximum-bitwise-or-subsets.java └── README.md ├── 2586-longest-square-streak-in-an-array ├── longest-square-streak-in-an-array.java └── README.md ├── 1497-check-if-array-pairs-are-divisible-by-k ├── check-if-array-pairs-are-divisible-by-k.java └── README.md ├── 962-maximum-width-ramp ├── maximum-width-ramp.java └── README.md ├── 1545-find-kth-bit-in-nth-binary-string ├── find-kth-bit-in-nth-binary-string.java └── README.md ├── 1590-make-sum-divisible-by-p ├── make-sum-divisible-by-p.java └── README.md ├── 1331-rank-transform-of-an-array ├── rank-transform-of-an-array.java └── README.md ├── 2406-divide-intervals-into-minimum-number-of-groups ├── divide-intervals-into-minimum-number-of-groups.java └── README.md ├── 1593-split-a-string-into-the-max-number-of-unique-substrings ├── split-a-string-into-the-max-number-of-unique-substrings.java └── README.md ├── 2696-minimum-string-length-after-removing-substrings ├── minimum-string-length-after-removing-substrings.java └── README.md ├── 1813-sentence-similarity-iii ├── sentence-similarity-iii.java └── README.md ├── 670-maximum-swap ├── README.md └── maximum-swap.java ├── 2491-divide-players-into-teams-of-equal-skill ├── divide-players-into-teams-of-equal-skill.java └── README.md ├── 2530-maximal-score-after-applying-k-operations ├── maximal-score-after-applying-k-operations.java └── README.md ├── 951-flip-equivalent-binary-trees ├── flip-equivalent-binary-trees.java └── README.md ├── .github └── workflows │ ├── readme.yml │ ├── detect-changes.yml │ └── jekyll-gh-pages.yml ├── 1942-the-number-of-the-smallest-unoccupied-chair ├── the-number-of-the-smallest-unoccupied-chair.java └── README.md ├── 567-permutation-in-string ├── permutation-in-string.java └── README.md ├── 2794-maximum-number-of-moves-in-a-grid ├── maximum-number-of-moves-in-a-grid.java └── README.md ├── 2641-cousins-in-binary-tree-ii ├── cousins-in-binary-tree-ii.java └── README.md ├── 1766-minimum-number-of-removals-to-make-mountain-array ├── minimum-number-of-removals-to-make-mountain-array.java └── README.md ├── 1402-count-square-submatrices-with-all-ones ├── count-square-submatrices-with-all-ones.java └── README.md ├── LeetSync2-Metadata.txt ├── _layouts └── default.html ├── 1106-parsing-a-boolean-expression ├── parsing-a-boolean-expression.java └── README.md ├── 2583-kth-largest-sum-in-a-binary-tree ├── kth-largest-sum-in-a-binary-tree.java └── README.md ├── 632-smallest-range-covering-elements-from-k-lists ├── README.md └── smallest-range-covering-elements-from-k-lists.java ├── 2554-minimum-total-distance-traveled ├── minimum-total-distance-traveled.java └── README.md ├── 1302-delete-characters-to-make-fancy-string └── README.md ├── 1405-longest-happy-string └── README.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ -------------------------------------------------------------------------------- /scripts/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module", 3 | "dependencies": { 4 | "dotenv": "^16.4.5", 5 | "node-fetch": "^3.2.0" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | title: October-Leetcode-Daily-2024 2 | description: A Repository to maintain my October Leetcode Coding session 2024 3 | show_downloads: false 4 | google_analytics: 5 | theme: jekyll-theme-hacker 6 | markdown: GFM 7 | include: 8 | - README.md 9 | - LICENSE -------------------------------------------------------------------------------- /2938-separate-black-and-white-balls/separate-black-and-white-balls.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumSteps(String s) { 3 | long swap = 0; 4 | int black = 0; 5 | for (int i = 0; i < s.length(); i++) { 6 | if (s.charAt(i) == '0') 7 | swap += (long) black; 8 | else 9 | black++; 10 | } 11 | return swap; 12 | } 13 | } -------------------------------------------------------------------------------- /921-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minAddToMakeValid(String s) { 3 | int open =0, mismatch=0; 4 | for(int i=0; i0) 11 | open--; 12 | else 13 | mismatch++; 14 | } 15 | } 16 | return open+mismatch; 17 | } 18 | } -------------------------------------------------------------------------------- /1963-minimum-number-of-swaps-to-make-the-string-balanced/minimum-number-of-swaps-to-make-the-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwaps(String s) { 3 | int size = 0; 4 | for (int i = 0; i < s.length(); i++) { 5 | char ch = s.charAt(i); 6 | if (ch == '[') 7 | size++; 8 | else if (size > 0) 9 | size--; 10 | } 11 | return (size + 1) / 2; 12 | } 13 | } -------------------------------------------------------------------------------- /2044-count-number-of-maximum-bitwise-or-subsets/count-number-of-maximum-bitwise-or-subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countMaxOrSubsets(int[] nums) { 3 | int max = 0; 4 | for (int n : nums) max |= n; 5 | return dfs(nums, 0, 0, max); 6 | } 7 | private int dfs(int[] nums, int i, int or, int max) { 8 | if (i == nums.length) return or == max ? 1 : 0; 9 | return dfs(nums, i + 1, or | nums[i], max) + dfs(nums, i + 1, or, max); 10 | } 11 | } -------------------------------------------------------------------------------- /2586-longest-square-streak-in-an-array/longest-square-streak-in-an-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestSquareStreak(int[] nums) { 3 | Map mp = new HashMap<>(); 4 | Arrays.sort(nums); 5 | int res = -1; 6 | 7 | for (int num : nums) { 8 | int sqrt = (int) Math.sqrt(num); 9 | 10 | if (sqrt * sqrt == num && mp.containsKey(sqrt)) { 11 | mp.put(num, mp.get(sqrt) + 1); 12 | res = Math.max(res, mp.get(num)); 13 | } else { 14 | mp.put(num, 1); 15 | } 16 | } 17 | return res; 18 | } 19 | } -------------------------------------------------------------------------------- /1497-check-if-array-pairs-are-divisible-by-k/check-if-array-pairs-are-divisible-by-k.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canArrange(int[] arr, int k) { 3 | int[] mp = new int[k]; 4 | 5 | for (int num : arr) { 6 | int rem = (num % k + k) % k; 7 | mp[rem]++; 8 | } 9 | 10 | if (mp[0] % 2 != 0) { 11 | return false; 12 | } 13 | 14 | for (int rem = 1; rem <= k / 2; rem++) { 15 | int counterHalf = k - rem; 16 | if (mp[counterHalf] != mp[rem]) { 17 | return false; 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /962-maximum-width-ramp/maximum-width-ramp.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxWidthRamp(int[] nums) { 3 | int n = nums.length; 4 | Stack stack = new Stack<>(); 5 | for (int i = 0; i < n; ++i) { 6 | if (stack.isEmpty() || nums[stack.peek()] > nums[i]) { 7 | stack.push(i); 8 | } 9 | } 10 | 11 | int maxWidth = 0; 12 | for (int j = n - 1; j >= 0; --j) { 13 | while (!stack.isEmpty() && nums[stack.peek()] <= nums[j]) { 14 | maxWidth = Math.max(maxWidth, j - stack.pop()); 15 | } 16 | } 17 | return maxWidth; 18 | } 19 | } -------------------------------------------------------------------------------- /1545-find-kth-bit-in-nth-binary-string/find-kth-bit-in-nth-binary-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private char solve(int term, int k) { 3 | if (term == 1) { 4 | return '0'; 5 | } 6 | 7 | int len = (1 << term) - 1; 8 | int mid = len / 2; 9 | 10 | if (mid == k) { 11 | return '1'; 12 | } else if (k < mid) { 13 | return solve(term - 1, k); 14 | } else { 15 | int new_k = len - k - 1; 16 | char ans = solve(term - 1, new_k); 17 | return ans == '1' ? '0' : '1'; 18 | } 19 | } 20 | 21 | public char findKthBit(int term, int k) { 22 | return solve(term, k - 1); 23 | } 24 | } -------------------------------------------------------------------------------- /1590-make-sum-divisible-by-p/make-sum-divisible-by-p.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSubarray(int[] nums, int p) { 3 | int sum = 0; 4 | for(int x : nums) 5 | sum = (sum + x)%p; 6 | 7 | int mod = sum%p; 8 | if(mod==0) 9 | return 0; 10 | 11 | int ans = nums.length; 12 | HashMaphm = new HashMap<>(); 13 | hm.put(0, -1); 14 | int currSumMod = 0; 15 | for(int i=0; i valueToRank = new HashMap<>(); 6 | int[] sortedUniqueNumbers = Arrays.stream(arr).distinct().sorted().toArray(); 7 | 8 | // Assign ranks to sorted unique elements 9 | for (int i = 0; i < sortedUniqueNumbers.length; i++) { 10 | valueToRank.put(sortedUniqueNumbers[i], i + 1); 11 | } 12 | 13 | // Replace each element in the original array with its rank 14 | for (int i = 0; i < arr.length; i++) { 15 | arr[i] = valueToRank.get(arr[i]); 16 | } 17 | 18 | return arr; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2406-divide-intervals-into-minimum-number-of-groups/divide-intervals-into-minimum-number-of-groups.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minGroups(int[][] intervals) { 3 | int n = intervals.length; 4 | int [] start = new int[n]; 5 | int [] end = new int[n]; 6 | 7 | for(int i=0; i end[end_ptr]){ 20 | end_ptr++; 21 | } 22 | else { 23 | group_count++; 24 | } 25 | } 26 | return group_count; 27 | } 28 | } -------------------------------------------------------------------------------- /1593-split-a-string-into-the-max-number-of-unique-substrings/split-a-string-into-the-max-number-of-unique-substrings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxUniqueSplit(String s) { 3 | return backtrack(0, s, new HashSet<>()); 4 | } 5 | private int backtrack(int start, String s, HashSet seen) { 6 | if (start == s.length()) { 7 | return 0; 8 | } 9 | int maxSplits = 0; 10 | for (int end = start + 1; end <= s.length(); end++) { 11 | String substring = s.substring(start, end); 12 | if (!seen.contains(substring)) { 13 | seen.add(substring); 14 | maxSplits = Math.max(maxSplits, 1 + backtrack(end, s, seen)); 15 | seen.remove(substring); 16 | } 17 | } 18 | return maxSplits; 19 | } 20 | } -------------------------------------------------------------------------------- /2696-minimum-string-length-after-removing-substrings/minimum-string-length-after-removing-substrings.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Solution { 4 | public int minLength(String s) { 5 | Stack stack = new Stack<>(); 6 | 7 | for (char x : s.toCharArray()) { 8 | if (x == 'B' && !stack.isEmpty() && stack.peek() == 'A') { 9 | stack.pop(); 10 | } else if (x == 'D' && !stack.isEmpty() && stack.peek() == 'C') { 11 | stack.pop(); 12 | } else { 13 | stack.push(x); 14 | } 15 | } 16 | 17 | return stack.size(); 18 | } 19 | 20 | public static void main(String[] args) { 21 | Solution solution = new Solution(); 22 | System.out.println(solution.minLength("ABCD")); // Example usage 23 | } 24 | } -------------------------------------------------------------------------------- /1813-sentence-similarity-iii/sentence-similarity-iii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private String[] splitWords(String sentence) { 3 | return sentence.split(" "); 4 | } 5 | 6 | public boolean areSentencesSimilar(String sentence1, String sentence2) { 7 | String[] words1 = splitWords(sentence1); 8 | String[] words2 = splitWords(sentence2); 9 | if (words1.length < words2.length) { 10 | String[] temp = words1; 11 | words1 = words2; 12 | words2 = temp; 13 | } 14 | 15 | int start = 0, end = 0; 16 | int n1 = words1.length, n2 = words2.length; 17 | while (start < n2 && words1[start].equals(words2[start])) { 18 | start++; 19 | } 20 | while (end < n2 && words1[n1 - end - 1].equals(words2[n2 - end - 1])) { 21 | end++; 22 | } 23 | return start + end >= n2; 24 | } 25 | } -------------------------------------------------------------------------------- /670-maximum-swap/README.md: -------------------------------------------------------------------------------- 1 |

Maximum Swap

Difficulty: Medium

You are given an integer num. You can swap two digits at most once to get the maximum valued number.

2 | 3 |

Return the maximum valued number you can get.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: num = 2736
10 | Output: 7236
11 | Explanation: Swap the number 2 and the number 7.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: num = 9973
18 | Output: 9973
19 | Explanation: No swap.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 0 <= num <= 108
  • 27 |
28 | -------------------------------------------------------------------------------- /2491-divide-players-into-teams-of-equal-skill/divide-players-into-teams-of-equal-skill.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public long dividePlayers(int[] skill) { 5 | // Step 1: Sort the skill array 6 | Arrays.sort(skill); 7 | 8 | int n = skill.length; 9 | int totalSkill = skill[0] + skill[n - 1]; // Required sum for each pair 10 | long chemistrySum = 0; 11 | 12 | // Step 2: Pair players using two pointers 13 | for (int i = 0; i < n / 2; i++) { 14 | // Check if the sum of current pair matches the required totalSkill 15 | if (skill[i] + skill[n - i - 1] != totalSkill) { 16 | return -1; // Invalid configuration, return -1 17 | } 18 | // Calculate the chemistry (product of pair) and add it to the sum 19 | chemistrySum += (long) skill[i] * skill[n - i - 1]; 20 | } 21 | 22 | return chemistrySum; // Return total chemistry 23 | } 24 | } -------------------------------------------------------------------------------- /2530-maximal-score-after-applying-k-operations/maximal-score-after-applying-k-operations.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | class Solution { 4 | public long maxKelements(int[] nums, int k) { 5 | // Priority queue as max-heap 6 | PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> Long.compare(b, a)); 7 | 8 | // Insert all elements into the max-heap 9 | for (int num : nums) { 10 | maxHeap.add((long) num); 11 | } 12 | 13 | long score = 0; 14 | 15 | // Perform k operations 16 | for (int i = 0; i < k; i++) { 17 | long maxVal = maxHeap.poll(); 18 | 19 | // Add the largest value to the score 20 | score += maxVal; 21 | 22 | // Replace the number with ceil(maxVal / 3) 23 | maxHeap.add((maxVal + 2) / 3); // Using (maxVal + 2) / 3 to simulate ceil 24 | } 25 | 26 | return score; 27 | } 28 | } -------------------------------------------------------------------------------- /951-flip-equivalent-binary-trees/flip-equivalent-binary-trees.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public boolean flipEquiv(TreeNode root1, TreeNode root2) { 18 | if(root1==null && root2==null){ 19 | return true; 20 | } 21 | if(root1==null || root2==null){ 22 | return false; 23 | } 24 | if(root1.val!=root2.val){ 25 | return false; 26 | } 27 | boolean without_swap=flipEquiv(root1.left,root2.left) && flipEquiv(root1.right,root2.right); 28 | boolean with_swap=flipEquiv(root1.left,root2.right) && flipEquiv(root1.right,root2.left); 29 | return without_swap || with_swap; 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /.github/workflows/readme.yml: -------------------------------------------------------------------------------- 1 | name: Generate Table of Contents 2 | 3 | on: 4 | push: 5 | branches: ["main"] 6 | workflow_dispatch: 7 | schedule: 8 | - cron: '0 0 * * *' # Runs at 00:00 UTC every day 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - name: Checkout code 16 | uses: actions/checkout@v2 17 | 18 | - name: Set up Node.js 19 | uses: actions/setup-node@v2 20 | with: 21 | node-version: "20" 22 | 23 | - name: Install dependencies 24 | run: npm install 25 | working-directory: scripts 26 | 27 | - name: Run index.js 28 | run: node index.js 29 | working-directory: scripts 30 | 31 | - name: Commit and push if changed 32 | run: | 33 | git config --global user.email "actions@github.com" 34 | git config --global user.name "GitHub Actions" 35 | git add . 36 | git diff --quiet && git diff --staged --quiet || (git commit -m "Update README with table of contents" && git push) 37 | working-directory: ${{ github.workspace }} 38 | -------------------------------------------------------------------------------- /1942-the-number-of-the-smallest-unoccupied-chair/the-number-of-the-smallest-unoccupied-chair.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int smallestChair(int[][] times, int targetFriend) { 3 | int n = times.length; 4 | Integer[] order = new Integer[n]; 5 | 6 | for (int i = 0; i < n; i++) order[i] = i; 7 | 8 | Arrays.sort(order, (a, b) -> Integer.compare(times[a][0], times[b][0])); 9 | 10 | PriorityQueue emptySeats = new PriorityQueue<>(); 11 | PriorityQueue takenSeats = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); 12 | 13 | for (int i = 0; i < n; i++) emptySeats.offer(i); 14 | 15 | for (int i : order) { 16 | int arrival = times[i][0], leave = times[i][1]; 17 | 18 | while (!takenSeats.isEmpty() && takenSeats.peek()[0] <= arrival) { 19 | emptySeats.offer(takenSeats.poll()[1]); 20 | } 21 | 22 | int seat = emptySeats.poll(); 23 | 24 | if (i == targetFriend) return seat; 25 | 26 | takenSeats.offer(new int[]{leave, seat}); 27 | } 28 | 29 | return -1; 30 | } 31 | } -------------------------------------------------------------------------------- /567-permutation-in-string/permutation-in-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean checkInclusion(String s1, String s2) { 3 | if (s1.length() > s2.length()) return false; 4 | 5 | int[] s1Count = new int[26]; 6 | int[] s2Count = new int[26]; 7 | 8 | // Count the frequency of characters in s1 and the first window of s2 9 | for (int i = 0; i < s1.length(); i++) { 10 | s1Count[s1.charAt(i) - 'a']++; 11 | s2Count[s2.charAt(i) - 'a']++; 12 | } 13 | 14 | // Slide the window over s2 15 | for (int i = 0; i < s2.length() - s1.length(); i++) { 16 | if (matches(s1Count, s2Count)) return true; 17 | // Update the window 18 | s2Count[s2.charAt(i) - 'a']--; 19 | s2Count[s2.charAt(i + s1.length()) - 'a']++; 20 | } 21 | 22 | // Check the last window 23 | return matches(s1Count, s2Count); 24 | } 25 | 26 | private boolean matches(int[] s1Count, int[] s2Count) { 27 | for (int i = 0; i < 26; i++) { 28 | if (s1Count[i] != s2Count[i]) return false; 29 | } 30 | return true; 31 | } 32 | } -------------------------------------------------------------------------------- /2794-maximum-number-of-moves-in-a-grid/maximum-number-of-moves-in-a-grid.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxMoves(int[][] grid) { 3 | int m = grid.length; 4 | int n = grid[0].length; 5 | int res = 0; 6 | int[] dp = new int[m]; 7 | for (int j = 1; j < n; j++) { 8 | int leftTop = 0; 9 | boolean found = false; 10 | for (int i = 0; i < m; i++) { 11 | int cur = -1; 12 | int nxtLeftTop = dp[i]; 13 | if (i - 1 >= 0 && leftTop != -1 && grid[i][j] > grid[i - 1][j - 1]) { 14 | cur = Math.max(cur, leftTop + 1); 15 | } 16 | if (dp[i] != -1 && grid[i][j] > grid[i][j - 1]) { 17 | cur = Math.max(cur, dp[i] + 1); 18 | } 19 | if (i + 1 < m && dp[i + 1] != -1 && grid[i][j] > grid[i + 1][j - 1]) { 20 | cur = Math.max(cur, dp[i + 1] + 1); 21 | } 22 | 23 | dp[i] = cur; 24 | found = found || (dp[i] != -1); 25 | leftTop = nxtLeftTop; 26 | } 27 | if (!found) break; 28 | res = j; 29 | } 30 | return res; 31 | } 32 | } -------------------------------------------------------------------------------- /2641-cousins-in-binary-tree-ii/cousins-in-binary-tree-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode replaceValueInTree(TreeNode root) { 3 | dfs(new TreeNode[] {root}); 4 | root.val = 0; 5 | return root; 6 | } 7 | 8 | private void dfs(TreeNode[] arr) { 9 | if (arr.length == 0) return; 10 | 11 | int sum = 0; 12 | for (TreeNode node : arr) { 13 | if (node == null) continue; 14 | if (node.left != null) sum += node.left.val; 15 | if (node.right != null) sum += node.right.val; 16 | } 17 | 18 | TreeNode[] childArr = new TreeNode[arr.length * 2]; 19 | int index = 0; 20 | 21 | for (TreeNode node : arr) { 22 | int curSum = 0; 23 | if (node.left != null) curSum += node.left.val; 24 | if (node.right != null) curSum += node.right.val; 25 | 26 | if (node.left != null) { 27 | node.left.val = sum - curSum; 28 | childArr[index++] = node.left; 29 | } 30 | if (node.right != null) { 31 | node.right.val = sum - curSum; 32 | childArr[index++] = node.right; 33 | } 34 | } 35 | 36 | dfs(java.util.Arrays.copyOf(childArr, index)); 37 | } 38 | } -------------------------------------------------------------------------------- /.github/workflows/detect-changes.yml: -------------------------------------------------------------------------------- 1 | # .github/workflows/detect-changes.yml 2 | # A workflow file that detect changes and trigger another workflow in another repository. 3 | # Here that repository is yashksaini-coder/Update-Leetcode-Gist which is used to update a pinned leetcode github gist. 4 | # Disable this repo if you don't have any pinned leetcode github gist. 5 | 6 | name: Detect Changes and Trigger Workflow 7 | 8 | on: 9 | workflow_dispatch: 10 | push: 11 | branches: 12 | - main # Change this to the branch you want to monitor 13 | pull_request: 14 | branches: 15 | - main # Trigger on pull request to the branch 16 | 17 | jobs: 18 | trigger-workflow: 19 | runs-on: ubuntu-latest 20 | 21 | steps: 22 | - name: Checkout the repository 23 | uses: actions/checkout@v3 24 | 25 | - name: Trigger workflow in another repository 26 | env: 27 | GITHUB_TOKEN: ${{ secrets.OCTOBER_2024 }} 28 | run: | 29 | echo "Changes detected. Workflow Triggered!" 30 | curl -X POST \ 31 | -H "Accept: application/vnd.github+json" \ 32 | -H "Authorization: Bearer $GITHUB_TOKEN" \ 33 | https://api.github.com/repos/yashksaini-coder/Update-Leetcode-Gist/actions/workflows/main.yml/dispatches \ 34 | -d '{"ref":"main"}' 35 | -------------------------------------------------------------------------------- /1766-minimum-number-of-removals-to-make-mountain-array/minimum-number-of-removals-to-make-mountain-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumMountainRemovals(int[] nums) { 3 | int n = nums.length; 4 | int[] LIS = new int[n], LDS = new int[n]; 5 | Arrays.fill(LIS, 1); 6 | Arrays.fill(LDS, 1); 7 | 8 | // Compute LIS for each index 9 | for (int i = 0; i < n; ++i) { 10 | for (int j = 0; j < i; ++j) { 11 | if (nums[i] > nums[j]) { 12 | LIS[i] = Math.max(LIS[i], LIS[j] + 1); 13 | } 14 | } 15 | } 16 | 17 | // Compute LDS from each index 18 | for (int i = n - 1; i >= 0; --i) { 19 | for (int j = n - 1; j > i; --j) { 20 | if (nums[i] > nums[j]) { 21 | LDS[i] = Math.max(LDS[i], LDS[j] + 1); 22 | } 23 | } 24 | } 25 | 26 | int maxMountainLength = 0; 27 | 28 | // Find the maximum mountain length 29 | for (int i = 1; i < n - 1; ++i) { 30 | if (LIS[i] > 1 && LDS[i] > 1) { // Valid peak 31 | maxMountainLength = Math.max(maxMountainLength, LIS[i] + LDS[i] - 1); 32 | } 33 | } 34 | 35 | return n - maxMountainLength; 36 | } 37 | } -------------------------------------------------------------------------------- /567-permutation-in-string/README.md: -------------------------------------------------------------------------------- 1 |

Permutation in String

Difficulty: Medium

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

2 | 3 |

In other words, return true if one of s1's permutations is the substring of s2.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: s1 = "ab", s2 = "eidbaooo"
10 | Output: true
11 | Explanation: s2 contains one permutation of s1 ("ba").
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: s1 = "ab", s2 = "eidboaoo"
18 | Output: false
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • 1 <= s1.length, s2.length <= 104
  • 26 |
  • s1 and s2 consist of lowercase English letters.
  • 27 |
28 | -------------------------------------------------------------------------------- /1402-count-square-submatrices-with-all-ones/count-square-submatrices-with-all-ones.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countSquares(int[][] matrix) { 3 | // Get dimensions of the matrix 4 | int n = matrix.length; // number of rows 5 | int m = matrix[0].length; // number of columns 6 | 7 | // Create a DP table with same dimensions as matrix 8 | int[][] dp = new int[n][m]; 9 | 10 | // Variable to store total count of squares 11 | int ans = 0; 12 | 13 | // Initialize first column of DP table 14 | for (int i = 0; i < n; i++) { 15 | dp[i][0] = matrix[i][0]; 16 | ans += dp[i][0]; 17 | } 18 | 19 | // Initialize first row of DP table 20 | for (int j = 1; j < m; j++) { 21 | dp[0][j] = matrix[0][j]; 22 | ans += dp[0][j]; 23 | } 24 | 25 | // Fill the DP table for remaining cells 26 | for(int i = 1; i < n; i++) { 27 | for(int j = 1; j < m; j++) { 28 | if(matrix[i][j] == 1) { 29 | dp[i][j] = 1 + Math.min(Math.min(dp[i][j-1], dp[i-1][j]), dp[i-1][j-1]); 30 | } 31 | ans += dp[i][j]; 32 | } 33 | } 34 | 35 | return ans; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LeetSync2-Metadata.txt: -------------------------------------------------------------------------------- 1 | 1497-check-if-array-pairs-are-divisible-by-k|Medium|1727721000000 2 | 1331-rank-transform-of-an-array|Easy|1727807400000 3 | 1590-make-sum-divisible-by-p|Medium|1727980200000 4 | 2491-divide-players-into-teams-of-equal-skill|Medium|1727980200000 5 | 567-permutation-in-string|Medium|1728066600000 6 | 1813-sentence-similarity-iii|Medium|1728153000000 7 | 2696-minimum-string-length-after-removing-substrings|Easy|1728239400000 8 | 1963-minimum-number-of-swaps-to-make-the-string-balanced|Medium|1728325800000 9 | 921-minimum-add-to-make-parentheses-valid|Medium|1728412200000 10 | 962-maximum-width-ramp|Medium|1728498600000 11 | 1942-the-number-of-the-smallest-unoccupied-chair|Medium|1728585000000 12 | 2406-divide-intervals-into-minimum-number-of-groups|Medium|1728671400000 13 | 2530-maximal-score-after-applying-k-operations|Medium|1728844200000 14 | 632-smallest-range-covering-elements-from-k-lists|Hard|1728844200000 15 | 2938-separate-black-and-white-balls|Medium|1728930600000 16 | 670-maximum-swap|Medium|1729103400000 17 | 2044-count-number-of-maximum-bitwise-or-subsets|Medium|1729189800000 18 | 1545-find-kth-bit-in-nth-binary-string|Medium|1729276200000 19 | 2583-kth-largest-sum-in-a-binary-tree|Medium|1729535400000 20 | 1106-parsing-a-boolean-expression|Hard|1729535400000 21 | 2641-cousins-in-binary-tree-ii|Medium|1729621800000 22 | 951-flip-equivalent-binary-trees|Medium|1729708200000 23 | -------------------------------------------------------------------------------- /_layouts/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | {% include head-custom.html %} 9 | 10 | {% seo %} 11 | 12 | 13 | 14 | 15 |
16 |
17 | 18 |

{{ site.title | default: site.github.repository_name }}

19 |
20 |

{{ site.description | default: site.github.project_tagline }}

21 | 22 |
23 | {% if site.show_downloads %} 24 | Download as .zip 25 | Download as .tar.gz 26 | {% endif %} 27 | View on GitHub 28 |
29 |
30 |
31 | 32 |
33 |
34 | {{ content }} 35 |
36 |
37 | 38 | 39 | -------------------------------------------------------------------------------- /1106-parsing-a-boolean-expression/parsing-a-boolean-expression.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public boolean parseBoolExpr(String expression) { 4 | Stack st = new Stack<>(); 5 | 6 | for (char currChar : expression.toCharArray()) { 7 | if (currChar == ',' || currChar == '(') continue; 8 | if ( 9 | currChar == 't' || 10 | currChar == 'f' || 11 | currChar == '!' || 12 | currChar == '&' || 13 | currChar == '|' 14 | ) { 15 | st.push(currChar); 16 | } 17 | else if (currChar == ')') { 18 | boolean hasTrue = false, hasFalse = false; 19 | 20 | while ( 21 | st.peek() != '!' && st.peek() != '&' && st.peek() != '|' 22 | ) { 23 | char topValue = st.pop(); 24 | if (topValue == 't') hasTrue = true; 25 | if (topValue == 'f') hasFalse = true; 26 | } 27 | 28 | char op = st.pop(); 29 | if (op == '!') { 30 | st.push(hasTrue ? 'f' : 't'); 31 | } else if (op == '&') { 32 | st.push(hasFalse ? 'f' : 't'); 33 | } else { 34 | st.push(hasTrue ? 't' : 'f'); 35 | } 36 | } 37 | } 38 | return st.peek() == 't'; 39 | } 40 | } -------------------------------------------------------------------------------- /962-maximum-width-ramp/README.md: -------------------------------------------------------------------------------- 1 |

Maximum Width Ramp

Difficulty: Medium

A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.

2 | 3 |

Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [6,0,8,2,1,5]
10 | Output: 4
11 | Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.
12 | 
13 | 14 |

Example 2:

15 | 16 |
17 | Input: nums = [9,8,1,0,1,9,4,0,4,1]
18 | Output: 7
19 | Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 2 <= nums.length <= 5 * 104
  • 27 |
  • 0 <= nums[i] <= 5 * 104
  • 28 |
29 | -------------------------------------------------------------------------------- /.github/workflows/jekyll-gh-pages.yml: -------------------------------------------------------------------------------- 1 | # Sample workflow for building and deploying a Jekyll site to GitHub Pages 2 | name: Deploy Jekyll with GitHub Pages dependencies preinstalled 3 | 4 | on: 5 | # Runs on pushes targeting the default branch 6 | push: 7 | branches: ["main"] 8 | 9 | # Allows you to run this workflow manually from the Actions tab 10 | workflow_dispatch: 11 | 12 | # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages 13 | permissions: 14 | contents: read 15 | pages: write 16 | id-token: write 17 | 18 | # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. 19 | # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. 20 | concurrency: 21 | group: "pages" 22 | cancel-in-progress: false 23 | 24 | jobs: 25 | # Build job 26 | build: 27 | runs-on: ubuntu-latest 28 | steps: 29 | - name: Checkout 30 | uses: actions/checkout@v4 31 | - name: Setup Pages 32 | uses: actions/configure-pages@v5 33 | - name: Build with Jekyll 34 | uses: actions/jekyll-build-pages@v1 35 | with: 36 | source: ./ 37 | destination: ./_site 38 | - name: Upload artifact 39 | uses: actions/upload-pages-artifact@v3 40 | 41 | # Deployment job 42 | deploy: 43 | runs-on: ubuntu-latest 44 | needs: build 45 | steps: 46 | - name: Deploy to GitHub Pages 47 | id: deployment 48 | uses: actions/deploy-pages@v4 49 | -------------------------------------------------------------------------------- /670-maximum-swap/maximum-swap.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximumSwap(int num) { 3 | // Convert the integer to a string for easy manipulation of digits 4 | String numStr = Integer.toString(num); 5 | char[] digits = numStr.toCharArray(); 6 | 7 | // Initialize maxNum to the original number 8 | int maxNum = num; 9 | int n = digits.length; 10 | 11 | // Nested loop to try all possible swaps of digits 12 | for (int i = 0; i < n; i++) { 13 | for (int j = i + 1; j < n; j++) { 14 | // Swap the digits at indices i and j 15 | swap(digits, i, j); 16 | 17 | // Convert the modified char array back to an integer 18 | int swappedNum = Integer.parseInt(new String(digits)); 19 | 20 | // Update maxNum if the new number is larger 21 | if (swappedNum > maxNum) { 22 | maxNum = swappedNum; 23 | } 24 | 25 | // Swap the digits back to restore the original string 26 | swap(digits, i, j); 27 | } 28 | } 29 | 30 | // Return the maximum number found 31 | return maxNum; 32 | } 33 | 34 | // Helper method to swap two digits in the char array 35 | private static void swap(char[] arr, int i, int j) { 36 | char temp = arr[i]; 37 | arr[i] = arr[j]; 38 | arr[j] = temp; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /1402-count-square-submatrices-with-all-ones/README.md: -------------------------------------------------------------------------------- 1 |

Count Square Submatrices with All Ones

Difficulty: Medium

Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
 7 | Input: matrix =
 8 | [
 9 |   [0,1,1,1],
10 |   [1,1,1,1],
11 |   [0,1,1,1]
12 | ]
13 | Output: 15
14 | Explanation: 
15 | There are 10 squares of side 1.
16 | There are 4 squares of side 2.
17 | There is  1 square of side 3.
18 | Total number of squares = 10 + 4 + 1 = 15.
19 | 
20 | 21 |

Example 2:

22 | 23 |
24 | Input: matrix = 
25 | [
26 |   [1,0,1],
27 |   [1,1,0],
28 |   [1,1,0]
29 | ]
30 | Output: 7
31 | Explanation: 
32 | There are 6 squares of side 1.  
33 | There is 1 square of side 2. 
34 | Total number of squares = 6 + 1 = 7.
35 | 
36 | 37 |

 

38 |

Constraints:

39 | 40 |
    41 |
  • 1 <= arr.length <= 300
  • 42 |
  • 1 <= arr[0].length <= 300
  • 43 |
  • 0 <= arr[i][j] <= 1
  • 44 |
45 | -------------------------------------------------------------------------------- /2583-kth-largest-sum-in-a-binary-tree/kth-largest-sum-in-a-binary-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public long kthLargestLevelSum(TreeNode root, int k) { 18 | List res = new ArrayList<>(); // To store sum of each level 19 | Queue q = new LinkedList<>(); // Queue for level-order traversal 20 | q.add(root); // Start BFS from the root node 21 | 22 | while (!q.isEmpty()) { 23 | int n = q.size(); // Number of nodes at the current level 24 | long sum = 0; // Sum of node values at the current level 25 | 26 | for (int i = 0; i < n; i++) { 27 | TreeNode node = q.poll(); 28 | sum += node.val; 29 | 30 | if (node.left != null) q.add(node.left); 31 | if (node.right != null) q.add(node.right); 32 | } 33 | res.add(sum); // Store the sum of the current level 34 | } 35 | 36 | if (k > res.size()) return -1; 37 | 38 | res.sort(Collections.reverseOrder()); // Sort level sums in descending order 39 | 40 | return res.get(k - 1); // Return the k-th largest sum 41 | } 42 | } -------------------------------------------------------------------------------- /1331-rank-transform-of-an-array/README.md: -------------------------------------------------------------------------------- 1 |

Rank Transform of an Array

Difficulty: Easy

Given an array of integers arr, replace each element with its rank.

2 | 3 |

The rank represents how large the element is. The rank has the following rules:

4 | 5 |
    6 |
  • Rank is an integer starting from 1.
  • 7 |
  • The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
  • 8 |
  • Rank should be as small as possible.
  • 9 |
10 | 11 |

 

12 |

Example 1:

13 | 14 |
15 | Input: arr = [40,10,20,30]
16 | Output: [4,1,2,3]
17 | Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.
18 | 19 |

Example 2:

20 | 21 |
22 | Input: arr = [100,100,100]
23 | Output: [1,1,1]
24 | Explanation: Same elements share the same rank.
25 | 
26 | 27 |

Example 3:

28 | 29 |
30 | Input: arr = [37,12,28,9,100,56,80,5,12]
31 | Output: [5,3,4,2,8,6,7,1,3]
32 | 
33 | 34 |

 

35 |

Constraints:

36 | 37 |
    38 |
  • 0 <= arr.length <= 105
  • 39 |
  • -109 <= arr[i] <= 109
  • 40 |
41 | -------------------------------------------------------------------------------- /632-smallest-range-covering-elements-from-k-lists/README.md: -------------------------------------------------------------------------------- 1 |

Smallest Range Covering Elements from K Lists

Difficulty: Hard

You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.

2 | 3 |

We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
 9 | Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
10 | Output: [20,24]
11 | Explanation: 
12 | List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
13 | List 2: [0, 9, 12, 20], 20 is in range [20,24].
14 | List 3: [5, 18, 22, 30], 22 is in range [20,24].
15 | 
16 | 17 |

Example 2:

18 | 19 |
20 | Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
21 | Output: [1,1]
22 | 
23 | 24 |

 

25 |

Constraints:

26 | 27 |
    28 |
  • nums.length == k
  • 29 |
  • 1 <= k <= 3500
  • 30 |
  • 1 <= nums[i].length <= 50
  • 31 |
  • -105 <= nums[i][j] <= 105
  • 32 |
  • nums[i] is sorted in non-decreasing order.
  • 33 |
34 | -------------------------------------------------------------------------------- /632-smallest-range-covering-elements-from-k-lists/smallest-range-covering-elements-from-k-lists.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] smallestRange(List> nums) { 3 | // Min-Heap: stores (value, list index, element index) 4 | PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); 5 | int curMax = Integer.MIN_VALUE; 6 | 7 | // Initialize the heap with the first element of each list 8 | for (int i = 0; i < nums.size(); i++) { 9 | minHeap.offer(new int[]{nums.get(i).get(0), i, 0}); 10 | curMax = Math.max(curMax, nums.get(i).get(0)); 11 | } 12 | 13 | // Track the smallest range 14 | int[] smallRange = new int[]{0, Integer.MAX_VALUE}; 15 | 16 | while (true) { 17 | // Get the minimum element from the heap 18 | int[] curr = minHeap.poll(); 19 | int curMin = curr[0], listIdx = curr[1], elemIdx = curr[2]; 20 | 21 | // Update the smallest range if a better one is found 22 | if (curMax - curMin < smallRange[1] - smallRange[0]) { 23 | smallRange[0] = curMin; 24 | smallRange[1] = curMax; 25 | } 26 | 27 | // Move to the next element in the same list 28 | if (elemIdx + 1 < nums.get(listIdx).size()) { 29 | int nextVal = nums.get(listIdx).get(elemIdx + 1); 30 | minHeap.offer(new int[]{nextVal, listIdx, elemIdx + 1}); 31 | curMax = Math.max(curMax, nextVal); 32 | } else { 33 | // If any list is exhausted, stop 34 | break; 35 | } 36 | } 37 | return smallRange; 38 | } 39 | } -------------------------------------------------------------------------------- /921-minimum-add-to-make-parentheses-valid/README.md: -------------------------------------------------------------------------------- 1 |

Minimum Add to Make Parentheses Valid

Difficulty: Medium

A parentheses string is valid if and only if:

2 | 3 |
    4 |
  • It is the empty string,
  • 5 |
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • 6 |
  • It can be written as (A), where A is a valid string.
  • 7 |
8 | 9 |

You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.

10 | 11 |
    12 |
  • For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))".
  • 13 |
14 | 15 |

Return the minimum number of moves required to make s valid.

16 | 17 |

 

18 |

Example 1:

19 | 20 |
21 | Input: s = "())"
22 | Output: 1
23 | 
24 | 25 |

Example 2:

26 | 27 |
28 | Input: s = "((("
29 | Output: 3
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 1 <= s.length <= 1000
  • 37 |
  • s[i] is either '(' or ')'.
  • 38 |
39 | -------------------------------------------------------------------------------- /2554-minimum-total-distance-traveled/minimum-total-distance-traveled.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumTotalDistance(List robot, int[][] factory) { 3 | Collections.sort(robot); 4 | Arrays.sort(factory, (a, b) -> Integer.compare(a[0], b[0])); 5 | int m = robot.size(); 6 | int n = factory.length; 7 | long[][] dp = new long[m + 1][n + 1]; 8 | for (int i = 0; i < m; i++) { 9 | dp[i][n] = Long.MAX_VALUE; 10 | } 11 | for (int j = n - 1; j >= 0; j--) { 12 | long prefix = 0; 13 | Deque> qq = new ArrayDeque<>(); 14 | qq.offer(new Pair<>(m, 0L)); 15 | for (int i = m - 1; i >= 0; i--) { 16 | prefix += Math.abs(robot.get(i) - factory[j][0]); 17 | while (!qq.isEmpty() && qq.peekFirst().getKey() > i + factory[j][1]) { 18 | qq.pollFirst(); 19 | } 20 | while (!qq.isEmpty() && qq.peekLast().getValue() >= dp[i][j + 1] - prefix) { 21 | qq.pollLast(); 22 | } 23 | qq.offerLast(new Pair<>(i, dp[i][j + 1] - prefix)); 24 | dp[i][j] = qq.peekFirst().getValue() + prefix; 25 | } 26 | } 27 | 28 | return dp[0][0]; 29 | } 30 | 31 | private static class Pair { 32 | private K key; 33 | private V value; 34 | 35 | public Pair(K key, V value) { 36 | this.key = key; 37 | this.value = value; 38 | } 39 | public K getKey() { 40 | return key; 41 | } 42 | public V getValue() { 43 | return value; 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /1497-check-if-array-pairs-are-divisible-by-k/README.md: -------------------------------------------------------------------------------- 1 |

Check If Array Pairs Are Divisible by k

Difficulty: Medium

Given an array of integers arr of even length n and an integer k.

2 | 3 |

We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.

4 | 5 |

Return true If you can find a way to do that or false otherwise.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
12 | Output: true
13 | Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
14 | 
15 | 16 |

Example 2:

17 | 18 |
19 | Input: arr = [1,2,3,4,5,6], k = 7
20 | Output: true
21 | Explanation: Pairs are (1,6),(2,5) and(3,4).
22 | 
23 | 24 |

Example 3:

25 | 26 |
27 | Input: arr = [1,2,3,4,5,6], k = 10
28 | Output: false
29 | Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • arr.length == n
  • 37 |
  • 1 <= n <= 105
  • 38 |
  • n is even.
  • 39 |
  • -109 <= arr[i] <= 109
  • 40 |
  • 1 <= k <= 105
  • 41 |
42 | -------------------------------------------------------------------------------- /951-flip-equivalent-binary-trees/README.md: -------------------------------------------------------------------------------- 1 |

Flip Equivalent Binary Trees

Difficulty: Medium

For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.

2 | 3 |

A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.

4 | 5 |

Given the roots of two binary trees root1 and root2, return true if the two trees are flip equivalent or false otherwise.

6 | 7 |

 

8 |

Example 1:

9 | Flipped Trees Diagram 10 |
11 | Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
12 | Output: true
13 | Explanation: We flipped at nodes with values 1, 3, and 5.
14 | 
15 | 16 |

Example 2:

17 | 18 |
19 | Input: root1 = [], root2 = []
20 | Output: true
21 | 
22 | 23 |

Example 3:

24 | 25 |
26 | Input: root1 = [], root2 = [1]
27 | Output: false
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • The number of nodes in each tree is in the range [0, 100].
  • 35 |
  • Each tree will have unique node values in the range [0, 99].
  • 36 |
37 | -------------------------------------------------------------------------------- /1766-minimum-number-of-removals-to-make-mountain-array/README.md: -------------------------------------------------------------------------------- 1 |

Minimum Number of Removals to Make Mountain Array

Difficulty: Hard

You may recall that an array arr is a mountain array if and only if:

2 | 3 |
    4 |
  • arr.length >= 3
  • 5 |
  • There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: 6 |
      7 |
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • 8 |
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
    • 9 |
    10 |
  • 11 |
12 | 13 |

Given an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array.

14 | 15 |

 

16 |

Example 1:

17 | 18 |
19 | Input: nums = [1,3,1]
20 | Output: 0
21 | Explanation: The array itself is a mountain array so we do not need to remove any elements.
22 | 
23 | 24 |

Example 2:

25 | 26 |
27 | Input: nums = [2,1,1,5,6,2,3,1]
28 | Output: 3
29 | Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 3 <= nums.length <= 1000
  • 37 |
  • 1 <= nums[i] <= 109
  • 38 |
  • It is guaranteed that you can make a mountain array out of nums.
  • 39 |
40 | -------------------------------------------------------------------------------- /2586-longest-square-streak-in-an-array/README.md: -------------------------------------------------------------------------------- 1 |

Longest Square Streak in an Array

Difficulty: Medium

You are given an integer array nums. A subsequence of nums is called a square streak if:

2 | 3 |
    4 |
  • The length of the subsequence is at least 2, and
  • 5 |
  • after sorting the subsequence, each element (except the first element) is the square of the previous number.
  • 6 |
7 | 8 |

Return the length of the longest square streak in nums, or return -1 if there is no square streak.

9 | 10 |

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

11 | 12 |

 

13 |

Example 1:

14 | 15 |
16 | Input: nums = [4,3,6,16,8,2]
17 | Output: 3
18 | Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16].
19 | - 4 = 2 * 2.
20 | - 16 = 4 * 4.
21 | Therefore, [4,16,2] is a square streak.
22 | It can be shown that every subsequence of length 4 is not a square streak.
23 | 
24 | 25 |

Example 2:

26 | 27 |
28 | Input: nums = [2,3,5,6,7]
29 | Output: -1
30 | Explanation: There is no square streak in nums so return -1.
31 | 
32 | 33 |

 

34 |

Constraints:

35 | 36 |
    37 |
  • 2 <= nums.length <= 105
  • 38 |
  • 2 <= nums[i] <= 105
  • 39 |
40 | -------------------------------------------------------------------------------- /2696-minimum-string-length-after-removing-substrings/README.md: -------------------------------------------------------------------------------- 1 |

Minimum String Length After Removing Substrings

Difficulty: Easy

You are given a string s consisting only of uppercase English letters.

2 | 3 |

You can apply some operations to this string where, in one operation, you can remove any occurrence of one of the substrings "AB" or "CD" from s.

4 | 5 |

Return the minimum possible length of the resulting string that you can obtain.

6 | 7 |

Note that the string concatenates after removing the substring and could produce new "AB" or "CD" substrings.

8 | 9 |

 

10 |

Example 1:

11 | 12 |
13 | Input: s = "ABFCACDB"
14 | Output: 2
15 | Explanation: We can do the following operations:
16 | - Remove the substring "ABFCACDB", so s = "FCACDB".
17 | - Remove the substring "FCACDB", so s = "FCAB".
18 | - Remove the substring "FCAB", so s = "FC".
19 | So the resulting length of the string is 2.
20 | It can be shown that it is the minimum length that we can obtain.
21 | 22 |

Example 2:

23 | 24 |
25 | Input: s = "ACBBD"
26 | Output: 5
27 | Explanation: We cannot do any operations on the string so the length remains the same.
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • 1 <= s.length <= 100
  • 35 |
  • s consists only of uppercase English letters.
  • 36 |
37 | -------------------------------------------------------------------------------- /2583-kth-largest-sum-in-a-binary-tree/README.md: -------------------------------------------------------------------------------- 1 |

Kth Largest Sum in a Binary Tree

Difficulty: Medium

You are given the root of a binary tree and a positive integer k.

2 | 3 |

The level sum in the tree is the sum of the values of the nodes that are on the same level.

4 | 5 |

Return the kth largest level sum in the tree (not necessarily distinct). If there are fewer than k levels in the tree, return -1.

6 | 7 |

Note that two nodes are on the same level if they have the same distance from the root.

8 | 9 |

 

10 |

Example 1:

11 | 12 |
13 | Input: root = [5,8,9,2,1,3,7,4,6], k = 2
14 | Output: 13
15 | Explanation: The level sums are the following:
16 | - Level 1: 5.
17 | - Level 2: 8 + 9 = 17.
18 | - Level 3: 2 + 1 + 3 + 7 = 13.
19 | - Level 4: 4 + 6 = 10.
20 | The 2nd largest level sum is 13.
21 | 
22 | 23 |

Example 2:

24 | 25 |
26 | Input: root = [1,2,null,3], k = 1
27 | Output: 3
28 | Explanation: The largest level sum is 3.
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • The number of nodes in the tree is n.
  • 36 |
  • 2 <= n <= 105
  • 37 |
  • 1 <= Node.val <= 106
  • 38 |
  • 1 <= k <= n
  • 39 |
40 | -------------------------------------------------------------------------------- /1590-make-sum-divisible-by-p/README.md: -------------------------------------------------------------------------------- 1 |

Make Sum Divisible by P

Difficulty: Medium

Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.

2 | 3 |

Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.

4 | 5 |

A subarray is defined as a contiguous block of elements in the array.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: nums = [3,1,4,2], p = 6
12 | Output: 1
13 | Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.
14 | 
15 | 16 |

Example 2:

17 | 18 |
19 | Input: nums = [6,3,5,2], p = 9
20 | Output: 2
21 | Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.
22 | 
23 | 24 |

Example 3:

25 | 26 |
27 | Input: nums = [1,2,3], p = 3
28 | Output: 0
29 | Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 1 <= nums.length <= 105
  • 37 |
  • 1 <= nums[i] <= 109
  • 38 |
  • 1 <= p <= 109
  • 39 |
40 | -------------------------------------------------------------------------------- /1593-split-a-string-into-the-max-number-of-unique-substrings/README.md: -------------------------------------------------------------------------------- 1 |

Split a String Into the Max Number of Unique Substrings

Difficulty: Medium

Given a string s, return the maximum number of unique substrings that the given string can be split into.

2 | 3 |

You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.

4 | 5 |

A substring is a contiguous sequence of characters within a string.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: s = "ababccc"
12 | Output: 5
13 | Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
14 | 
15 | 16 |

Example 2:

17 | 18 |
19 | Input: s = "aba"
20 | Output: 2
21 | Explanation: One way to split maximally is ['a', 'ba'].
22 | 
23 | 24 |

Example 3:

25 | 26 |
27 | Input: s = "aa"
28 | Output: 1
29 | Explanation: It is impossible to split the string any further.
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 37 |

    1 <= s.length <= 16

    38 |
  • 39 |
  • 40 |

    s contains only lower case English letters.

    41 |
  • 42 |
43 | -------------------------------------------------------------------------------- /2938-separate-black-and-white-balls/README.md: -------------------------------------------------------------------------------- 1 |

Separate Black and White Balls

Difficulty: Medium

There are n balls on a table, each ball has a color black or white.

2 | 3 |

You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white balls, respectively.

4 | 5 |

In each step, you can choose two adjacent balls and swap them.

6 | 7 |

Return the minimum number of steps to group all the black balls to the right and all the white balls to the left.

8 | 9 |

 

10 |

Example 1:

11 | 12 |
13 | Input: s = "101"
14 | Output: 1
15 | Explanation: We can group all the black balls to the right in the following way:
16 | - Swap s[0] and s[1], s = "011".
17 | Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.
18 | 19 |

Example 2:

20 | 21 |
22 | Input: s = "100"
23 | Output: 2
24 | Explanation: We can group all the black balls to the right in the following way:
25 | - Swap s[0] and s[1], s = "010".
26 | - Swap s[1] and s[2], s = "001".
27 | It can be proven that the minimum number of steps needed is 2.
28 | 
29 | 30 |

Example 3:

31 | 32 |
33 | Input: s = "0111"
34 | Output: 0
35 | Explanation: All the black balls are already grouped to the right.
36 | 
37 | 38 |

 

39 |

Constraints:

40 | 41 |
    42 |
  • 1 <= n == s.length <= 105
  • 43 |
  • s[i] is either '0' or '1'.
  • 44 |
45 | -------------------------------------------------------------------------------- /2406-divide-intervals-into-minimum-number-of-groups/README.md: -------------------------------------------------------------------------------- 1 |

Divide Intervals Into Minimum Number of Groups

Difficulty: Medium

You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti].

2 | 3 |

You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.

4 | 5 |

Return the minimum number of groups you need to make.

6 | 7 |

Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.

8 | 9 |

 

10 |

Example 1:

11 | 12 |
13 | Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
14 | Output: 3
15 | Explanation: We can divide the intervals into the following groups:
16 | - Group 1: [1, 5], [6, 8].
17 | - Group 2: [2, 3], [5, 10].
18 | - Group 3: [1, 10].
19 | It can be proven that it is not possible to divide the intervals into fewer than 3 groups.
20 | 
21 | 22 |

Example 2:

23 | 24 |
25 | Input: intervals = [[1,3],[5,6],[8,10],[11,13]]
26 | Output: 1
27 | Explanation: None of the intervals overlap, so we can put all of them in one group.
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • 1 <= intervals.length <= 105
  • 35 |
  • intervals[i].length == 2
  • 36 |
  • 1 <= lefti <= righti <= 106
  • 37 |
38 | -------------------------------------------------------------------------------- /1302-delete-characters-to-make-fancy-string/README.md: -------------------------------------------------------------------------------- 1 |

Delete Characters to Make Fancy String

Difficulty: Easy

A fancy string is a string where no three consecutive characters are equal.

2 | 3 |

Given a string s, delete the minimum possible number of characters from s to make it fancy.

4 | 5 |

Return the final string after the deletion. It can be shown that the answer will always be unique.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: s = "leeetcode"
12 | Output: "leetcode"
13 | Explanation:
14 | Remove an 'e' from the first group of 'e's to create "leetcode".
15 | No three consecutive characters are equal, so return "leetcode".
16 | 
17 | 18 |

Example 2:

19 | 20 |
21 | Input: s = "aaabaaaa"
22 | Output: "aabaa"
23 | Explanation:
24 | Remove an 'a' from the first group of 'a's to create "aabaaaa".
25 | Remove two 'a's from the second group of 'a's to create "aabaa".
26 | No three consecutive characters are equal, so return "aabaa".
27 | 
28 | 29 |

Example 3:

30 | 31 |
32 | Input: s = "aab"
33 | Output: "aab"
34 | Explanation: No three consecutive characters are equal, so return "aab".
35 | 
36 | 37 |

 

38 |

Constraints:

39 | 40 |
    41 |
  • 1 <= s.length <= 105
  • 42 |
  • s consists only of lowercase English letters.
  • 43 |
44 | -------------------------------------------------------------------------------- /1405-longest-happy-string/README.md: -------------------------------------------------------------------------------- 1 |

Longest Happy String

Difficulty: Medium

A string s is called happy if it satisfies the following conditions:

2 | 3 |
    4 |
  • s only contains the letters 'a', 'b', and 'c'.
  • 5 |
  • s does not contain any of "aaa", "bbb", or "ccc" as a substring.
  • 6 |
  • s contains at most a occurrences of the letter 'a'.
  • 7 |
  • s contains at most b occurrences of the letter 'b'.
  • 8 |
  • s contains at most c occurrences of the letter 'c'.
  • 9 |
10 | 11 |

Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "".

12 | 13 |

A substring is a contiguous sequence of characters within a string.

14 | 15 |

 

16 |

Example 1:

17 | 18 |
19 | Input: a = 1, b = 1, c = 7
20 | Output: "ccaccbcc"
21 | Explanation: "ccbccacc" would also be a correct answer.
22 | 
23 | 24 |

Example 2:

25 | 26 |
27 | Input: a = 7, b = 1, c = 0
28 | Output: "aabaa"
29 | Explanation: It is the only correct answer in this case.
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • 0 <= a, b, c <= 100
  • 37 |
  • a + b + c > 0
  • 38 |
39 | -------------------------------------------------------------------------------- /2530-maximal-score-after-applying-k-operations/README.md: -------------------------------------------------------------------------------- 1 |

Maximal Score After Applying K Operations

Difficulty: Medium

You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0.

2 | 3 |

In one operation:

4 | 5 |
    6 |
  1. choose an index i such that 0 <= i < nums.length,
  2. 7 |
  3. increase your score by nums[i], and
  4. 8 |
  5. replace nums[i] with ceil(nums[i] / 3).
  6. 9 |
10 | 11 |

Return the maximum possible score you can attain after applying exactly k operations.

12 | 13 |

The ceiling function ceil(val) is the least integer greater than or equal to val.

14 | 15 |

 

16 |

Example 1:

17 | 18 |
19 | Input: nums = [10,10,10,10,10], k = 5
20 | Output: 50
21 | Explanation: Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.
22 | 
23 | 24 |

Example 2:

25 | 26 |
27 | Input: nums = [1,10,3,3,3], k = 3
28 | Output: 17
29 | Explanation: You can do the following operations:
30 | Operation 1: Select i = 1, so nums becomes [1,4,3,3,3]. Your score increases by 10.
31 | Operation 2: Select i = 1, so nums becomes [1,2,3,3,3]. Your score increases by 4.
32 | Operation 3: Select i = 2, so nums becomes [1,1,1,3,3]. Your score increases by 3.
33 | The final score is 10 + 4 + 3 = 17.
34 | 
35 | 36 |

 

37 |

Constraints:

38 | 39 |
    40 |
  • 1 <= nums.length, k <= 105
  • 41 |
  • 1 <= nums[i] <= 109
  • 42 |
43 | -------------------------------------------------------------------------------- /2044-count-number-of-maximum-bitwise-or-subsets/README.md: -------------------------------------------------------------------------------- 1 |

Count Number of Maximum Bitwise-OR Subsets

Difficulty: Medium

Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.

2 | 3 |

An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different.

4 | 5 |

The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: nums = [3,1]
12 | Output: 2
13 | Explanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:
14 | - [3]
15 | - [3,1]
16 | 
17 | 18 |

Example 2:

19 | 20 |
21 | Input: nums = [2,2,2]
22 | Output: 7
23 | Explanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.
24 | 
25 | 26 |

Example 3:

27 | 28 |
29 | Input: nums = [3,2,1,5]
30 | Output: 6
31 | Explanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:
32 | - [3,5]
33 | - [3,1,5]
34 | - [3,2,5]
35 | - [3,2,1,5]
36 | - [2,5]
37 | - [2,1,5]
38 | 39 |

 

40 |

Constraints:

41 | 42 |
    43 |
  • 1 <= nums.length <= 16
  • 44 |
  • 1 <= nums[i] <= 105
  • 45 |
46 | -------------------------------------------------------------------------------- /2491-divide-players-into-teams-of-equal-skill/README.md: -------------------------------------------------------------------------------- 1 |

Divide Players Into Teams of Equal Skill

Difficulty: Medium

You are given a positive integer array skill of even length n where skill[i] denotes the skill of the ith player. Divide the players into n / 2 teams of size 2 such that the total skill of each team is equal.

2 | 3 |

The chemistry of a team is equal to the product of the skills of the players on that team.

4 | 5 |

Return the sum of the chemistry of all the teams, or return -1 if there is no way to divide the players into teams such that the total skill of each team is equal.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
11 | Input: skill = [3,2,5,1,3,4]
12 | Output: 22
13 | Explanation: 
14 | Divide the players into the following teams: (1, 5), (2, 4), (3, 3), where each team has a total skill of 6.
15 | The sum of the chemistry of all the teams is: 1 * 5 + 2 * 4 + 3 * 3 = 5 + 8 + 9 = 22.
16 | 
17 | 18 |

Example 2:

19 | 20 |
21 | Input: skill = [3,4]
22 | Output: 12
23 | Explanation: 
24 | The two players form a team with a total skill of 7.
25 | The chemistry of the team is 3 * 4 = 12.
26 | 
27 | 28 |

Example 3:

29 | 30 |
31 | Input: skill = [1,1,2,3]
32 | Output: -1
33 | Explanation: 
34 | There is no way to divide the players into teams such that the total skill of each team is equal.
35 | 
36 | 37 |

 

38 |

Constraints:

39 | 40 |
    41 |
  • 2 <= skill.length <= 105
  • 42 |
  • skill.length is even.
  • 43 |
  • 1 <= skill[i] <= 1000
  • 44 |
45 | -------------------------------------------------------------------------------- /2794-maximum-number-of-moves-in-a-grid/README.md: -------------------------------------------------------------------------------- 1 |

Maximum Number of Moves in a Grid

Difficulty: Medium

You are given a 0-indexed m x n matrix grid consisting of positive integers.

2 | 3 |

You can start at any cell in the first column of the matrix, and traverse the grid in the following way:

4 | 5 |
    6 |
  • From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger than the value of the current cell.
  • 7 |
8 | 9 |

Return the maximum number of moves that you can perform.

10 | 11 |

 

12 |

Example 1:

13 | 14 |
15 | Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]]
16 | Output: 3
17 | Explanation: We can start at the cell (0, 0) and make the following moves:
18 | - (0, 0) -> (0, 1).
19 | - (0, 1) -> (1, 2).
20 | - (1, 2) -> (2, 3).
21 | It can be shown that it is the maximum number of moves that can be made.
22 | 23 |

Example 2:

24 | 25 |
26 | 
27 | Input: grid = [[3,2,4],[2,1,9],[1,1,7]]
28 | Output: 0
29 | Explanation: Starting from any cell in the first column we cannot perform any moves.
30 | 
31 | 32 |

 

33 |

Constraints:

34 | 35 |
    36 |
  • m == grid.length
  • 37 |
  • n == grid[i].length
  • 38 |
  • 2 <= m, n <= 1000
  • 39 |
  • 4 <= m * n <= 105
  • 40 |
  • 1 <= grid[i][j] <= 106
  • 41 |
42 | -------------------------------------------------------------------------------- /1545-find-kth-bit-in-nth-binary-string/README.md: -------------------------------------------------------------------------------- 1 |

Find Kth Bit in Nth Binary String

Difficulty: Medium

Given two positive integers n and k, the binary string Sn is formed as follows:

2 | 3 |
    4 |
  • S1 = "0"
  • 5 |
  • Si = Si - 1 + "1" + reverse(invert(Si - 1)) for i > 1
  • 6 |
7 | 8 |

Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).

9 | 10 |

For example, the first four strings in the above sequence are:

11 | 12 |
    13 |
  • S1 = "0"
  • 14 |
  • S2 = "011"
  • 15 |
  • S3 = "0111001"
  • 16 |
  • S4 = "011100110110001"
  • 17 |
18 | 19 |

Return the kth bit in Sn. It is guaranteed that k is valid for the given n.

20 | 21 |

 

22 |

Example 1:

23 | 24 |
25 | Input: n = 3, k = 1
26 | Output: "0"
27 | Explanation: S3 is "0111001".
28 | The 1st bit is "0".
29 | 
30 | 31 |

Example 2:

32 | 33 |
34 | Input: n = 4, k = 11
35 | Output: "1"
36 | Explanation: S4 is "011100110110001".
37 | The 11th bit is "1".
38 | 
39 | 40 |

 

41 |

Constraints:

42 | 43 |
    44 |
  • 1 <= n <= 20
  • 45 |
  • 1 <= k <= 2n - 1
  • 46 |
47 | -------------------------------------------------------------------------------- /2641-cousins-in-binary-tree-ii/README.md: -------------------------------------------------------------------------------- 1 |

Cousins in Binary Tree II

Difficulty: Medium

Given the root of a binary tree, replace the value of each node in the tree with the sum of all its cousins' values.

2 | 3 |

Two nodes of a binary tree are cousins if they have the same depth with different parents.

4 | 5 |

Return the root of the modified tree.

6 | 7 |

Note that the depth of a node is the number of edges in the path from the root node to it.

8 | 9 |

 

10 |

Example 1:

11 | 12 |
13 | Input: root = [5,4,9,1,10,null,7]
14 | Output: [0,0,0,7,7,null,11]
15 | Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.
16 | - Node with value 5 does not have any cousins so its sum is 0.
17 | - Node with value 4 does not have any cousins so its sum is 0.
18 | - Node with value 9 does not have any cousins so its sum is 0.
19 | - Node with value 1 has a cousin with value 7 so its sum is 7.
20 | - Node with value 10 has a cousin with value 7 so its sum is 7.
21 | - Node with value 7 has cousins with values 1 and 10 so its sum is 11.
22 | 
23 | 24 |

Example 2:

25 | 26 |
27 | Input: root = [3,1,2]
28 | Output: [0,0,0]
29 | Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.
30 | - Node with value 3 does not have any cousins so its sum is 0.
31 | - Node with value 1 does not have any cousins so its sum is 0.
32 | - Node with value 2 does not have any cousins so its sum is 0.
33 | 
34 | 35 |

 

36 |

Constraints:

37 | 38 |
    39 |
  • The number of nodes in the tree is in the range [1, 105].
  • 40 |
  • 1 <= Node.val <= 104
  • 41 |
42 | -------------------------------------------------------------------------------- /1963-minimum-number-of-swaps-to-make-the-string-balanced/README.md: -------------------------------------------------------------------------------- 1 |

Minimum Number of Swaps to Make the String Balanced

Difficulty: Medium

You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.

2 | 3 |

A string is called balanced if and only if:

4 | 5 |
    6 |
  • It is the empty string, or
  • 7 |
  • It can be written as AB, where both A and B are balanced strings, or
  • 8 |
  • It can be written as [C], where C is a balanced string.
  • 9 |
10 | 11 |

You may swap the brackets at any two indices any number of times.

12 | 13 |

Return the minimum number of swaps to make s balanced.

14 | 15 |

 

16 |

Example 1:

17 | 18 |
19 | Input: s = "][]["
20 | Output: 1
21 | Explanation: You can make the string balanced by swapping index 0 with index 3.
22 | The resulting string is "[[]]".
23 | 
24 | 25 |

Example 2:

26 | 27 |
28 | Input: s = "]]][[["
29 | Output: 2
30 | Explanation: You can do the following to make the string balanced:
31 | - Swap index 0 with index 4. s = "[]][][".
32 | - Swap index 1 with index 5. s = "[[][]]".
33 | The resulting string is "[[][]]".
34 | 
35 | 36 |

Example 3:

37 | 38 |
39 | Input: s = "[]"
40 | Output: 0
41 | Explanation: The string is already balanced.
42 | 
43 | 44 |

 

45 |

Constraints:

46 | 47 |
    48 |
  • n == s.length
  • 49 |
  • 2 <= n <= 106
  • 50 |
  • n is even.
  • 51 |
  • s[i] is either '[' or ']'.
  • 52 |
  • The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.
  • 53 |
54 | -------------------------------------------------------------------------------- /1106-parsing-a-boolean-expression/README.md: -------------------------------------------------------------------------------- 1 |

Parsing A Boolean Expression

Difficulty: Hard

A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes:

2 | 3 |
    4 |
  • 't' that evaluates to true.
  • 5 |
  • 'f' that evaluates to false.
  • 6 |
  • '!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr.
  • 7 |
  • '&(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical AND of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1.
  • 8 |
  • '|(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical OR of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1.
  • 9 |
10 | 11 |

Given a string expression that represents a boolean expression, return the evaluation of that expression.

12 | 13 |

It is guaranteed that the given expression is valid and follows the given rules.

14 | 15 |

 

16 |

Example 1:

17 | 18 |
19 | Input: expression = "&(|(f))"
20 | Output: false
21 | Explanation: 
22 | First, evaluate |(f) --> f. The expression is now "&(f)".
23 | Then, evaluate &(f) --> f. The expression is now "f".
24 | Finally, return false.
25 | 
26 | 27 |

Example 2:

28 | 29 |
30 | Input: expression = "|(f,f,f,t)"
31 | Output: true
32 | Explanation: The evaluation of (false OR false OR false OR true) is true.
33 | 
34 | 35 |

Example 3:

36 | 37 |
38 | Input: expression = "!(&(f,t))"
39 | Output: true
40 | Explanation: 
41 | First, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now "!(f)".
42 | Then, evaluate !(f) --> NOT false --> true. We return true.
43 | 
44 | 45 |

 

46 |

Constraints:

47 | 48 |
    49 |
  • 1 <= expression.length <= 2 * 104
  • 50 |
  • expression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','.
  • 51 |
52 | -------------------------------------------------------------------------------- /1942-the-number-of-the-smallest-unoccupied-chair/README.md: -------------------------------------------------------------------------------- 1 |

The Number of the Smallest Unoccupied Chair

Difficulty: Medium

There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.

2 | 3 |
    4 |
  • For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2.
  • 5 |
6 | 7 |

When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.

8 | 9 |

You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct.

10 | 11 |

Return the chair number that the friend numbered targetFriend will sit on.

12 | 13 |

 

14 |

Example 1:

15 | 16 |
17 | Input: times = [[1,4],[2,3],[4,6]], targetFriend = 1
18 | Output: 1
19 | Explanation: 
20 | - Friend 0 arrives at time 1 and sits on chair 0.
21 | - Friend 1 arrives at time 2 and sits on chair 1.
22 | - Friend 1 leaves at time 3 and chair 1 becomes empty.
23 | - Friend 0 leaves at time 4 and chair 0 becomes empty.
24 | - Friend 2 arrives at time 4 and sits on chair 0.
25 | Since friend 1 sat on chair 1, we return 1.
26 | 
27 | 28 |

Example 2:

29 | 30 |
31 | Input: times = [[3,10],[1,5],[2,6]], targetFriend = 0
32 | Output: 2
33 | Explanation: 
34 | - Friend 1 arrives at time 1 and sits on chair 0.
35 | - Friend 2 arrives at time 2 and sits on chair 1.
36 | - Friend 0 arrives at time 3 and sits on chair 2.
37 | - Friend 1 leaves at time 5 and chair 0 becomes empty.
38 | - Friend 2 leaves at time 6 and chair 1 becomes empty.
39 | - Friend 0 leaves at time 10 and chair 2 becomes empty.
40 | Since friend 0 sat on chair 2, we return 2.
41 | 
42 | 43 |

 

44 |

Constraints:

45 | 46 |
    47 |
  • n == times.length
  • 48 |
  • 2 <= n <= 104
  • 49 |
  • times[i].length == 2
  • 50 |
  • 1 <= arrivali < leavingi <= 105
  • 51 |
  • 0 <= targetFriend <= n - 1
  • 52 |
  • Each arrivali time is distinct.
  • 53 |
54 | -------------------------------------------------------------------------------- /1813-sentence-similarity-iii/README.md: -------------------------------------------------------------------------------- 1 |

Sentence Similarity III

Difficulty: Medium

You are given two strings sentence1 and sentence2, each representing a sentence composed of words. A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of only uppercase and lowercase English characters.

2 | 3 |

Two sentences s1 and s2 are considered similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. Note that the inserted sentence must be separated from existing words by spaces.

4 | 5 |

For example,

6 | 7 |
    8 |
  • s1 = "Hello Jane" and s2 = "Hello my name is Jane" can be made equal by inserting "my name is" between "Hello" and "Jane" in s1.
  • 9 |
  • s1 = "Frog cool" and s2 = "Frogs are cool" are not similar, since although there is a sentence "s are" inserted into s1, it is not separated from "Frog" by a space.
  • 10 |
11 | 12 |

Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.

13 | 14 |

 

15 |

Example 1:

16 | 17 |
18 |

Input: sentence1 = "My name is Haley", sentence2 = "My Haley"

19 | 20 |

Output: true

21 | 22 |

Explanation:

23 | 24 |

sentence2 can be turned to sentence1 by inserting "name is" between "My" and "Haley".

25 |
26 | 27 |

Example 2:

28 | 29 |
30 |

Input: sentence1 = "of", sentence2 = "A lot of words"

31 | 32 |

Output: false

33 | 34 |

Explanation:

35 | 36 |

No single sentence can be inserted inside one of the sentences to make it equal to the other.

37 |
38 | 39 |

Example 3:

40 | 41 |
42 |

Input: sentence1 = "Eating right now", sentence2 = "Eating"

43 | 44 |

Output: true

45 | 46 |

Explanation:

47 | 48 |

sentence2 can be turned to sentence1 by inserting "right now" at the end of the sentence.

49 |
50 | 51 |

 

52 |

Constraints:

53 | 54 |
    55 |
  • 1 <= sentence1.length, sentence2.length <= 100
  • 56 |
  • sentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.
  • 57 |
  • The words in sentence1 and sentence2 are separated by a single space.
  • 58 |
59 | -------------------------------------------------------------------------------- /scripts/index.js: -------------------------------------------------------------------------------- 1 | import fetch from "node-fetch"; 2 | import fs from "fs"; 3 | import path from "path"; 4 | import { fileURLToPath } from "url"; 5 | import dotenv from "dotenv"; 6 | 7 | const __filename = fileURLToPath(import.meta.url); 8 | const __dirname = path.dirname(__filename); 9 | 10 | const toc = async () => { 11 | // Fetch from API 12 | dotenv.config(); 13 | 14 | 15 | const data = await fetch( 16 | `https://api.github.com/repos/yashksaini-coder/October-Leetcode-Daily-2024/contents?ref=main` 17 | ) 18 | .then((response) => response.json()) 19 | .then((data) => data); 20 | 21 | var arr = Object.values(data); 22 | 23 | // Filter out the folders 24 | const folders = arr.filter( 25 | (item) => item.type === "dir" && item.name[0] !== "." 26 | ); 27 | 28 | // Make a table of contents 29 | var toc = []; 30 | folders.forEach((item) => { 31 | var num = parseInt(item.name.split("-")[0]); 32 | toc[num] = item.name; 33 | }); 34 | 35 | // Sort toc by key 36 | var sorted = Object.keys(toc) 37 | .sort() 38 | .reduce((obj, key) => { 39 | obj[key] = toc[key]; 40 | return obj; 41 | }, {}); 42 | 43 | // Generate the table of solutions 44 | let solutionsTable = ` 45 | 46 | | Leetcode Problem | Problem Statement | Solution | 47 | |---:|:-----|:----:| 48 | `; 49 | for (var key in sorted) { 50 | var str = sorted[key].split("-"); 51 | var name = str.slice(1).map(word => { 52 | const lowerCaseWord = word.toLowerCase(); 53 | if (["in", "of", "for", "and", "or", "the", "a", "an", "to", "by", "at", "from", "on", "off", "up", "down", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"].includes(lowerCaseWord)) { 54 | return lowerCaseWord; 55 | } else if (lowerCaseWord.startsWith("i") && lowerCaseWord.length <= 3) { 56 | return lowerCaseWord.toUpperCase(); 57 | } else { 58 | return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); 59 | } 60 | }).join(" "); 61 | name = name.charAt(0).toUpperCase() + name.slice(1); 62 | var num = key; 63 | var folderName = str.join("-"); 64 | var fileName = str.slice(1).join("-") + ".java"; 65 | var solutionPath = `./${folderName}/${fileName}`; 66 | solutionsTable += `| [${num}](https://leetcode.com/problems/${str.slice(1).join("-")}/) | ${name} | [Solution](${solutionPath}) |\n`; 67 | } 68 | solutionsTable += ""; 69 | 70 | // Read the existing README content 71 | const readmePath = path.join(__dirname, "..", "README.md"); 72 | let readmeContent = fs.readFileSync(readmePath, "utf8"); 73 | 74 | // Check if the solutions table already exists 75 | if (readmeContent.includes("")) { 76 | // Replace the existing table 77 | readmeContent = readmeContent.replace( 78 | /[\s\S]*/, 79 | solutionsTable 80 | ); 81 | } else { 82 | // Find the "## Solutions" heading and insert the table after it 83 | const solutionsHeading = "## Solutions"; 84 | const headingIndex = readmeContent.indexOf(solutionsHeading); 85 | if (headingIndex !== -1) { 86 | const insertIndex = headingIndex + solutionsHeading.length; 87 | readmeContent = readmeContent.slice(0, insertIndex) + "\n\n" + solutionsTable + readmeContent.slice(insertIndex); 88 | } else { 89 | console.error("Could not find '## Solutions' heading in README.md"); 90 | return; 91 | } 92 | } 93 | 94 | // Write the updated content back to README.md 95 | fs.writeFileSync(readmePath, readmeContent); 96 | console.log("README.md has been updated with the solutions table!"); 97 | }; 98 | 99 | toc(); -------------------------------------------------------------------------------- /scripts/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scripts", 3 | "lockfileVersion": 3, 4 | "requires": true, 5 | "packages": { 6 | "": { 7 | "dependencies": { 8 | "dotenv": "^16.4.5", 9 | "node-fetch": "^3.2.0" 10 | } 11 | }, 12 | "node_modules/data-uri-to-buffer": { 13 | "version": "4.0.1", 14 | "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", 15 | "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", 16 | "license": "MIT", 17 | "engines": { 18 | "node": ">= 12" 19 | } 20 | }, 21 | "node_modules/dotenv": { 22 | "version": "16.4.5", 23 | "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", 24 | "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", 25 | "license": "BSD-2-Clause", 26 | "engines": { 27 | "node": ">=12" 28 | }, 29 | "funding": { 30 | "url": "https://dotenvx.com" 31 | } 32 | }, 33 | "node_modules/fetch-blob": { 34 | "version": "3.2.0", 35 | "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", 36 | "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", 37 | "funding": [ 38 | { 39 | "type": "github", 40 | "url": "https://github.com/sponsors/jimmywarting" 41 | }, 42 | { 43 | "type": "paypal", 44 | "url": "https://paypal.me/jimmywarting" 45 | } 46 | ], 47 | "license": "MIT", 48 | "dependencies": { 49 | "node-domexception": "^1.0.0", 50 | "web-streams-polyfill": "^3.0.3" 51 | }, 52 | "engines": { 53 | "node": "^12.20 || >= 14.13" 54 | } 55 | }, 56 | "node_modules/formdata-polyfill": { 57 | "version": "4.0.10", 58 | "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", 59 | "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", 60 | "license": "MIT", 61 | "dependencies": { 62 | "fetch-blob": "^3.1.2" 63 | }, 64 | "engines": { 65 | "node": ">=12.20.0" 66 | } 67 | }, 68 | "node_modules/node-domexception": { 69 | "version": "1.0.0", 70 | "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", 71 | "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", 72 | "funding": [ 73 | { 74 | "type": "github", 75 | "url": "https://github.com/sponsors/jimmywarting" 76 | }, 77 | { 78 | "type": "github", 79 | "url": "https://paypal.me/jimmywarting" 80 | } 81 | ], 82 | "license": "MIT", 83 | "engines": { 84 | "node": ">=10.5.0" 85 | } 86 | }, 87 | "node_modules/node-fetch": { 88 | "version": "3.3.2", 89 | "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", 90 | "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", 91 | "license": "MIT", 92 | "dependencies": { 93 | "data-uri-to-buffer": "^4.0.0", 94 | "fetch-blob": "^3.1.4", 95 | "formdata-polyfill": "^4.0.10" 96 | }, 97 | "engines": { 98 | "node": "^12.20.0 || ^14.13.1 || >=16.0.0" 99 | }, 100 | "funding": { 101 | "type": "opencollective", 102 | "url": "https://opencollective.com/node-fetch" 103 | } 104 | }, 105 | "node_modules/web-streams-polyfill": { 106 | "version": "3.3.3", 107 | "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", 108 | "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", 109 | "license": "MIT", 110 | "engines": { 111 | "node": ">= 8" 112 | } 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /2554-minimum-total-distance-traveled/README.md: -------------------------------------------------------------------------------- 1 |

Minimum Total Distance Traveled

Difficulty: Hard

There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots.

2 | 3 |

The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially.

4 | 5 |

All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.

6 | 7 |

At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots.

8 | 9 |

Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired.

10 | 11 |

Note that

12 | 13 |
    14 |
  • All robots move at the same speed.
  • 15 |
  • If two robots move in the same direction, they will never collide.
  • 16 |
  • If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other.
  • 17 |
  • If a robot passes by a factory that reached its limits, it crosses it as if it does not exist.
  • 18 |
  • If the robot moved from a position x to a position y, the distance it moved is |y - x|.
  • 19 |
20 | 21 |

 

22 |

Example 1:

23 | 24 |
25 | Input: robot = [0,4,6], factory = [[2,2],[6,2]]
26 | Output: 4
27 | Explanation: As shown in the figure:
28 | - The first robot at position 0 moves in the positive direction. It will be repaired at the first factory.
29 | - The second robot at position 4 moves in the negative direction. It will be repaired at the first factory.
30 | - The third robot at position 6 will be repaired at the second factory. It does not need to move.
31 | The limit of the first factory is 2, and it fixed 2 robots.
32 | The limit of the second factory is 2, and it fixed 1 robot.
33 | The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.
34 | 
35 | 36 |

Example 2:

37 | 38 |
39 | Input: robot = [1,-1], factory = [[-2,1],[2,1]]
40 | Output: 2
41 | Explanation: As shown in the figure:
42 | - The first robot at position 1 moves in the positive direction. It will be repaired at the second factory.
43 | - The second robot at position -1 moves in the negative direction. It will be repaired at the first factory.
44 | The limit of the first factory is 1, and it fixed 1 robot.
45 | The limit of the second factory is 1, and it fixed 1 robot.
46 | The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.
47 | 
48 | 49 |

 

50 |

Constraints:

51 | 52 |
    53 |
  • 1 <= robot.length, factory.length <= 100
  • 54 |
  • factory[j].length == 2
  • 55 |
  • -109 <= robot[i], positionj <= 109
  • 56 |
  • 0 <= limitj <= robot.length
  • 57 |
  • The input will be generated such that it is always possible to repair every robot.
  • 58 |
59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | AI-Coding-Assistant 3 |
4 |

5 | 6 |
7 | GitHub Repo Name 8 | GitHub Author 9 | GitHub commit-activity 10 | GitHub contributors 11 | GitHub Created At 12 | GitHub Last Commit 13 | GitHub Repo Size 14 | GitHub License 15 | GitHub Open Issues 16 | GitHub Closed Issues 17 | GitHub Open PR 18 | GitHub Closed PR 19 | GitHub Forks 20 | GitHub Stars 21 | GitHub Watchers 22 | GitHub language count 23 |
24 |
25 | 26 | 27 |
28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 |
36 |
37 | 38 | ## Solutions 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | | Leetcode Problem | Problem Statement | Solution | 123 | |---:|:-----|:----:| 124 | | [567](https://leetcode.com/problems/permutation-in-string/) | Permutation in String | [Solution](./567-permutation-in-string/permutation-in-string.java) | 125 | | [632](https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/) | Smallest Range Covering Elements from K Lists | [Solution](./632-smallest-range-covering-elements-from-k-lists/smallest-range-covering-elements-from-k-lists.java) | 126 | | [670](https://leetcode.com/problems/maximum-swap/) | Maximum Swap | [Solution](./670-maximum-swap/maximum-swap.java) | 127 | | [921](https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/) | Minimum Add to Make Parentheses Valid | [Solution](./921-minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.java) | 128 | | [951](https://leetcode.com/problems/flip-equivalent-binary-trees/) | Flip Equivalent Binary Trees | [Solution](./951-flip-equivalent-binary-trees/flip-equivalent-binary-trees.java) | 129 | | [962](https://leetcode.com/problems/maximum-width-ramp/) | Maximum Width Ramp | [Solution](./962-maximum-width-ramp/maximum-width-ramp.java) | 130 | | [1106](https://leetcode.com/problems/parsing-a-boolean-expression/) | Parsing a Boolean Expression | [Solution](./1106-parsing-a-boolean-expression/parsing-a-boolean-expression.java) | 131 | | [1302](https://leetcode.com/problems/delete-characters-to-make-fancy-string/) | Delete Characters to Make Fancy String | [Solution](./1302-delete-characters-to-make-fancy-string/delete-characters-to-make-fancy-string.java) | 132 | | [1331](https://leetcode.com/problems/rank-transform-of-an-array/) | Rank Transform of an Array | [Solution](./1331-rank-transform-of-an-array/rank-transform-of-an-array.java) | 133 | | [1402](https://leetcode.com/problems/count-square-submatrices-with-all-ones/) | Count Square Submatrices With all Ones | [Solution](./1402-count-square-submatrices-with-all-ones/count-square-submatrices-with-all-ones.java) | 134 | | [1405](https://leetcode.com/problems/longest-happy-string/) | Longest Happy String | [Solution](./1405-longest-happy-string/longest-happy-string.java) | 135 | | [1497](https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/) | Check IF Array Pairs Are Divisible by K | [Solution](./1497-check-if-array-pairs-are-divisible-by-k/check-if-array-pairs-are-divisible-by-k.java) | 136 | | [1545](https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/) | Find Kth Bit in Nth Binary String | [Solution](./1545-find-kth-bit-in-nth-binary-string/find-kth-bit-in-nth-binary-string.java) | 137 | | [1590](https://leetcode.com/problems/make-sum-divisible-by-p/) | Make Sum Divisible by P | [Solution](./1590-make-sum-divisible-by-p/make-sum-divisible-by-p.java) | 138 | | [1593](https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/) | Split a String Into the Max Number of Unique Substrings | [Solution](./1593-split-a-string-into-the-max-number-of-unique-substrings/split-a-string-into-the-max-number-of-unique-substrings.java) | 139 | | [1766](https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/) | Minimum Number of Removals to Make Mountain Array | [Solution](./1766-minimum-number-of-removals-to-make-mountain-array/minimum-number-of-removals-to-make-mountain-array.java) | 140 | | [1813](https://leetcode.com/problems/sentence-similarity-iii/) | Sentence Similarity III | [Solution](./1813-sentence-similarity-iii/sentence-similarity-iii.java) | 141 | | [1942](https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair/) | The Number of the Smallest Unoccupied Chair | [Solution](./1942-the-number-of-the-smallest-unoccupied-chair/the-number-of-the-smallest-unoccupied-chair.java) | 142 | | [1963](https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/) | Minimum Number of Swaps to Make the String Balanced | [Solution](./1963-minimum-number-of-swaps-to-make-the-string-balanced/minimum-number-of-swaps-to-make-the-string-balanced.java) | 143 | | [2044](https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/) | Count Number of Maximum Bitwise or Subsets | [Solution](./2044-count-number-of-maximum-bitwise-or-subsets/count-number-of-maximum-bitwise-or-subsets.java) | 144 | | [2406](https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/) | Divide Intervals Into Minimum Number of Groups | [Solution](./2406-divide-intervals-into-minimum-number-of-groups/divide-intervals-into-minimum-number-of-groups.java) | 145 | | [2491](https://leetcode.com/problems/divide-players-into-teams-of-equal-skill/) | Divide Players Into Teams of Equal Skill | [Solution](./2491-divide-players-into-teams-of-equal-skill/divide-players-into-teams-of-equal-skill.java) | 146 | | [2530](https://leetcode.com/problems/maximal-score-after-applying-k-operations/) | Maximal Score After Applying K Operations | [Solution](./2530-maximal-score-after-applying-k-operations/maximal-score-after-applying-k-operations.java) | 147 | | [2554](https://leetcode.com/problems/minimum-total-distance-traveled/) | Minimum Total Distance Traveled | [Solution](./2554-minimum-total-distance-traveled/minimum-total-distance-traveled.java) | 148 | | [2583](https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/) | Kth Largest Sum in a Binary Tree | [Solution](./2583-kth-largest-sum-in-a-binary-tree/kth-largest-sum-in-a-binary-tree.java) | 149 | | [2586](https://leetcode.com/problems/longest-square-streak-in-an-array/) | Longest Square Streak in an Array | [Solution](./2586-longest-square-streak-in-an-array/longest-square-streak-in-an-array.java) | 150 | | [2641](https://leetcode.com/problems/cousins-in-binary-tree-ii/) | Cousins in Binary Tree II | [Solution](./2641-cousins-in-binary-tree-ii/cousins-in-binary-tree-ii.java) | 151 | | [2696](https://leetcode.com/problems/minimum-string-length-after-removing-substrings/) | Minimum String Length After Removing Substrings | [Solution](./2696-minimum-string-length-after-removing-substrings/minimum-string-length-after-removing-substrings.java) | 152 | | [2794](https://leetcode.com/problems/maximum-number-of-moves-in-a-grid/) | Maximum Number of Moves in a Grid | [Solution](./2794-maximum-number-of-moves-in-a-grid/maximum-number-of-moves-in-a-grid.java) | 153 | | [2938](https://leetcode.com/problems/separate-black-and-white-balls/) | Separate Black and White Balls | [Solution](./2938-separate-black-and-white-balls/separate-black-and-white-balls.java) | 154 | | [NaN](https://leetcode.com/problems//) | | [Solution](./scripts/.java) | 155 | 156 | 157 |
158 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------