```java
public int[] noZeroIntegers(int n) {
    for (int a = 1; a < n; ++a) {
        if (Integer.toString(a).indexOf('0') == -1 &&
            Integer.toString(n - a).indexOf('0') == -1) {
            return new int[]{a, n - a};
        }
    }
    return new int[]{0, 0}; // never gets here
}
```

```python
def no_zero_integers(n: int):
    for a in range(1, n):
        if '0' not in str(a) and '0' not in str(n - a):
            return [a, n - a]
    return [0, 0]  # never gets here
```


```java
import java.util.HashMap;
import java.util.HashSet;

public boolean uniqueOccurrences(int[] arr) {
    HashMap<Integer, Integer> counts = new HashMap<>();
    for (int num : arr) {
        counts.put(num, counts.getOrDefault(num, 0) + 1);
    }

    HashSet<Integer> uniqueCounts = new HashSet<>();
    for (int count : counts.values()) {
        if (uniqueCounts.contains(count)) {
            return false;
        }
        uniqueCounts.add(count);
    }

    return true;
}
```

true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true

```cpp
#include <map>
#include <unordered_set>
using namespace std;

bool uniqueOccurrences(vector<int>& arr) {
    map<int, int> counts;
    for (int num : arr) {
        counts[num]++;
    }

    unordered_set<int> unique_counts;
    for (auto& count : counts) {
        if (unique_counts.count(count.second) > 0) {
            return false;
        }
        unique_counts.insert(count.second);
    }

    return true;
}
```


```java
public String breakPalindrome(String palindrome) {
    int length = palindrome.length();
    if (length == 1) return "";

    char[] chars = palindrome.toCharArray();
    for (int i = 0; i < length / 2; i++) {
        if (chars[i] != 'a') {
            chars[i] = 'a';
            return String.valueOf(chars);
        }
    }

    chars[length - 1] = 'b';
    return String.valueOf(chars);
}
```

abcccb abba abcbaaaaaaaa a abcbaa a accccb aa aaaaaaa abccbaaaaa aba accba abccbaaaaaaa aaaaaaaa abccca aaaa abcba aaaaaa abccbaaa acccca abcbaaa abccbaaaa abccba abcbaaaaaa abccbaa abba abccba acccca aaa abccab abcdefedcba ab abcbaaaaaaa abccbaaaaaaaa aaaaaa abccba abccbaaaaaa abccba aaaaa abcbaaaaa abcbaaaa

aacba aacbaaaaaaa aacbaa aaaaab aaccbaaaa aaccca aacbaaa aacccb aaaaab aaccbaaaaaaa aaaab aacbaaaa abb aaccbaa aacbaaaaaa aaccab aaba aacba aaba aaccba ab aaccca aacbaaaaaaaa aab aaccba aaccbaaaaaaaa aacbaaaaa aacccb aacdefedcba aaab aaaaaab aaaaaaab ab aaccba aaccca aaccbaaaaaa aaccbaaa aaccbaaaaa aaccba

```python
def breakPalindrome(palindrome: str) -> str:
    length = len(palindrome)
    if length == 1:
        return ""

    chars = list(palindrome)
    for i in range(length // 2):
        if chars[i] != 'a':
            chars[i] = 'a'
            return "".join(chars)

    chars[length - 1] = 'b'
    return "".join(chars)
```


```java
public int longestSubsequence(int[] arr, int difference) {
    HashMap<Integer, Integer> dp = new HashMap<>();
    int maxLength = 0;
    for (int num : arr) {
        dp.put(num, dp.getOrDefault(num - difference, 0) + 1);
        maxLength = Math.max(maxLength, dp.get(num));
    }
    return maxLength;
}
```

```cpp
int longestSubsequence(vector<int>& arr, int difference) {
    unordered_map<int, int> dp;
    int maxLength = 0;
    for (int num : arr) {
        dp[num] = dp[num - difference] + 1;
        maxLength = max(maxLength, dp[num]);
    }
    return maxLength;
}
```


```java
import java.util.Arrays;

public int[] sortBasedOnMapping(int[] mapping, int[] nums) {
    Integer[] boxedNums = Arrays.stream(nums).boxed().toArray(Integer[]::new);
    Arrays.sort(boxedNums, (a, b) -> {
        String aStr = Integer.toString(a);
        String bStr = Integer.toString(b);
        for (int i = 0; i < aStr.length(); i++)
            aStr = aStr.substring(0, i) + mapping[aStr.charAt(i) - '0'] + aStr.substring(i + 1);
        for (int i = 0; i < bStr.length(); i++)
            bStr = bStr.substring(0, i) + mapping[bStr.charAt(i) - '0'] + bStr.substring(i + 1);
        return aStr.compareTo(bStr);
    });
    return Arrays.stream(boxedNums).mapToInt(Integer::intValue).toArray();
}
```

```cpp
#include <vector>
#include <algorithm>

std::vector<int> sortBasedOnMapping(std::vector<int>& mapping, std::vector<int>& nums) {
    std::sort(nums.begin(), nums.end(), [&](int a, int b) {
        std::string aStr = std::to_string(a);
        std::string bStr = std::to_string(b);
        for (char &c : aStr) c = '0' + mapping[c - '0'];
        for (char &c : bStr) c = '0' + mapping[c - '0'];
        return aStr < bStr;
    });
    return nums;
}
```


```python
def findTheCity(n, edges, distanceThreshold):
    distance = [[1e5] * n for _ in range(n)]

    for edge in edges:
        distance[edge[0]][edge[1]] = edge[2]
        distance[edge[1]][edge[0]] = edge[2]

    for i in range(n):
        distance[i][i] = 0

    for k in range(n):
        for i in range(n):
            for j in range(n):
                distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])

    res, minReachable = 0, n
    for i in range(n):
        reachable = sum(1 for j in range(n) if distance[i][j] <= distanceThreshold)
        if reachable <= minReachable:
            minReachable = reachable
            res = i
    return res
```

```java
public int findTheCity(int n, int[][] edges, int distanceThreshold) {
    int[][] distance = new int[n][n];

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            distance[i][j] = 10001;
        }
    }

    for (int[] edge : edges) {
        distance[edge[0]][edge[1]] = edge[2];
        distance[edge[1]][edge[0]] = edge[2];
    }

    for (int i = 0; i < n; i++) distance[i][i] = 0;

    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                distance[i][j] = Math.min(distance[i][j], distance[i][k] + distance[k][j]);
            }
        }
    }

    int res = 0, minReachable = n;
    for (int i = 0; i < n; i++) {
        int reachable = 0;
        for (int j = 0; j < n; j++) {
            if (distance[i][j] <= distanceThreshold) reachable++;
        }
        if (reachable <= minReachable) {
            minReachable = reachable;
            res = i;
        }
    }
    return res;
}
```


```cpp
#include <vector>
#include <algorithm>

int maxCandies(const std::vector<int>& candies, int k) {
    int left = 1;
    int right = *std::max_element(candies.begin(), candies.end());

    while (left <= right) {
        int mid = left + (right - left) / 2;
        int count = 0;
        for (int candy : candies) {
            count += candy / mid;
        }
        if (count >= k) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return right;
}
```

```python
def max_candies(candies, k):
    left, right = 1, max(candies)

    while left <= right:
        mid = left + (right - left) // 2
        count = sum(candy // mid for candy in candies)
        if count >= k:
            left = mid + 1
        else:
            right = mid - 1
    return right
```


```cpp
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;

int minSetSize(vector<int>& arr) {
    unordered_map<int, int> freq_map;
    priority_queue<int> max_heap;
    for (int x : arr)
        freq_map[x]++;
    for (auto &[_, cnt] : freq_map)
        max_heap.push(cnt);
    int half = arr.size() / 2;
    int cnt = 0;
    int size = 0;
    while (size < half) {
        size += max_heap.top();
        max_heap.pop();
        cnt++;
    }
    return cnt;
}
```

```python
from collections import Counter
import heapq

def minSetSize(arr):
    freq_map = Counter(arr)
    max_heap = [-cnt for cnt in freq_map.values()]
    heapq.heapify(max_heap)
    half = len(arr) // 2
    cnt = 0
    size = 0
    while size < half:
        size -= heapq.heappop(max_heap)
        cnt += 1
    return cnt
```


```java
import java.util.ArrayList;

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
}

class Solution {
    private int sumSubtrees(TreeNode root, ArrayList<Integer> sums) {
        if (root == null) return 0;
        int sum = root.val + sumSubtrees(root.left, sums) + sumSubtrees(root.right, sums);
        sums.add(sum);
        return sum;
    }

    public int maxProduct(TreeNode root) {
        ArrayList<Integer> sums = new ArrayList<>();
        long total = sumSubtrees(root, sums);
        long max_product = 0;

        for (long sum : sums) {
            max_product = Math.max(max_product, sum * (total - sum));
        }

        return (int)(max_product % 1000000007L);
    }
}
```

```cpp
#include <algorithm>
#include <vector>
using std::max;
using std::vector;

class TreeNode {
public:
    int val;
    TreeNode* left;
    TreeNode* right;
};

class Solution {
    int sumSubtrees(TreeNode* root, vector<int>& sums) {
        if (!root) return 0;
        int sum = root->val + sumSubtrees(root->left, sums) + sumSubtrees(root->right, sums);
        sums.push_back(sum);
        return sum;
    }

public:
    int maxProduct(TreeNode* root) {
        vector<int> sums;
        long long total = sumSubtrees(root, sums);
        long long max_product = 0;

        for (long long sum : sums) {
            max_product = max(max_product, sum * (total - sum));
        }

        return max_product % 1000000007;
    }
};
```


```python
def maxEqualFreq(nums):
    count, freq = {}, {}
    max_len, max_freq = 0, 0
    for i, num in enumerate(nums):
        count[num] = count.get(num, 0) + 1
        freq[count[num] - 1] = freq.get(count[num] - 1, 0) - 1
        freq[count[num]] = freq.get(count[num], 0) + 1

        max_freq = max(max_freq, count[num])
        if max_freq * (i + 1) == i or max_freq * (freq.get(max_freq - 1, 0) + 1) + (max_freq - 1) * freq.get(max_freq - 1, 0) == i:
            max_len = i + 1
    return max_len
```

```cpp
int maxEqualFreq(vector<int>& nums) {
    unordered_map<int, int> count, freq;
    int max_len = 0, max_freq = 0;
    for (int i = 0; i < nums.size(); i++) {
        count[nums[i]]++;
        freq[count[nums[i]] - 1]--;
        freq[count[nums[i]]]++;

        max_freq = max(max_freq, count[nums[i]]);
        if (max_freq * (i + 1) == i || max_freq * (freq[max_freq - 1] + 1) + (max_freq - 1) * freq[max_freq - 1] == i) {
            max_len = i + 1;
        }
    }
    return max_len;
}
```


```cpp
#include <vector>
#include <queue>
#include <unordered_map>

int minJumps(std::vector<int>& arr) {
    int n = arr.size();
    if (n <= 1) return 0;

    std::unordered_map<int, std::vector<int>> value_indices;
    for (int i = 0; i < n; ++i) {
        value_indices[arr[i]].push_back(i);
    }

    std::queue<int> q;
    std::vector<bool> visited(n, false);

    q.push(0);
    visited[0] = true;
    int steps = 0;

    while (!q.empty()) {
        int size = q.size();

        for (int i = 0; i < size; ++i) {
            int index = q.front();
            q.pop();

            if (index == n - 1) return steps;

            if (index > 0 && !visited[index - 1]) {
                q.push(index - 1);
                visited[index - 1] = true;
            }

            if (index < n - 1 && !visited[index + 1]) {
                q.push(index + 1);
                visited[index + 1] = true;
            }

            for (int neighbor : value_indices[arr[index]]) {
                if (!visited[neighbor]) {
                    q.push(neighbor);
                    visited[neighbor] = true;
                }
            }

            value_indices[arr[index]].clear();
        }

        ++steps;
    }

    return -1;
}
```

```java
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

public int minJumps(int[] arr) {
    int n = arr.length;
    if (n <= 1) return 0;

    HashMap<Integer, LinkedList<Integer>> valueIndices = new HashMap<>();

    for (int i = 0; i < n; ++i) {
        valueIndices.computeIfAbsent(arr[i], v -> new LinkedList<>()).add(i);
    }

    Queue<Integer> queue = new LinkedList<>();
    boolean[] visited = new boolean[n];

    queue.offer(0);
    visited[0] = true;
    int steps = 0;

    while (!queue.isEmpty()) {
        int size = queue.size();

        for (int i = 0; i < size; ++i) {
            int index = queue.poll();

            if (index == n - 1) return steps;

            if (index > 0 && !visited[index - 1]) {
                queue.offer(index - 1);
                visited[index - 1] = true;
            }

            if (index < n - 1 && !visited[index + 1]) {
                queue.offer(index + 1);
                visited[index + 1] = true;
            }

            for (int neighbor : valueIndices.get(arr[index])) {
                if (!visited[neighbor]) {
                    queue.offer(neighbor);
                    visited[neighbor] = true;
                }
            }

            valueIndices.get(arr[index]).clear();
        }

        ++steps;
    }

    return -1;
}
```


```java
public int[] findClosestDivisors(int num) {
    for (int i = (int)Math.sqrt(num + 2); i >= 1; i--) {
        if ((num + 1) % i == 0) return new int[]{i, (num + 1) / i};
        if ((num + 2) % i == 0) return new int[]{i, (num + 2) / i};
    }
    return new int[0];
}
```

```python
def findClosestDivisors(num):
    for i in range(int((num + 2) ** 0.5), 0, -1):
        if (num + 1) % i == 0:
            return [i, (num + 1) // i]
        if (num + 2) % i == 0:
            return [i, (num + 2) // i]
    return []
```


```python
from collections import defaultdict

def largest_multiple_of_three(digits):
    digits.sort(reverse=True)
    sum_digits = sum(digits)

    if sum_digits % 3 == 0:
        return '0' if digits[-1] == 0 else ''.join(map(str, digits))

    mod = defaultdict(list)
    for digit in digits:
        mod[digit % 3].append(digit)

    if sum_digits % 3 == 1:
        if mod[1]:
            mod[1].pop()
        else:
            mod[2].pop(), mod[2].pop()
    else:
        if mod[2]:
            mod[2].pop()
        else:
            mod[1].pop(), mod[1].pop()

    result = "".join(str(digit) for value in mod.values() for digit in value)
    result = "".join(sorted(result, reverse=True))

    return '0' if not result or result[0] == '0' else result
```

```cpp
#include <vector>
#include <string>
#include <algorithm>

std::string largestMultipleOfThree(std::vector<int>& digits) {
    std::sort(digits.rbegin(), digits.rend());
    int sum = 0;
    for (int digit : digits) {
        sum += digit;
    }

    if (sum % 3 == 0) {
        if (digits.back() == 0) return "0";
        std::string result(digits.begin(), digits.end());
        return result;
    }

    std::vector<int> mod[3];
    for (int digit : digits) {
        mod[digit % 3].push_back(digit);
    }

    if (sum % 3 == 1) {
        if (!mod[1].empty()) {
            mod[1].pop_back();
        } else {
            mod[2].pop_back();
            mod[2].pop_back();
        }
    } else {
        if (!mod[2].empty()) {
            mod[2].pop_back();
        } else {
            mod[1].pop_back();
            mod[1].pop_back();
        }
    }

    std::string result;
    for (int i = 0; i < 3; ++i) {
        for (int digit : mod[i]) {
            result += std::to_string(digit);
        }
    }

    std::sort(result.rbegin(), result.rend());
    if (result.empty() || result[0] == '0') {
        return "0";
    }

    return result;
}
```


```java
public int[] smallerNumbersThanCurrent(int[] nums) {
    int[] result = new int[nums.length];
    for (int i = 0; i < nums.length; i++) {
        int count = 0;
        for (int j = 0; j < nums.length; j++) {
            if (i != j && nums[j] < nums[i]) {
                count++;
            }
        }
        result[i] = count;
    }
    return result;
}
```

```python
def smallerNumbersThanCurrent(nums):
    result = []
    for i in range(len(nums)):
        count = 0
        for j in range(len(nums)):
            if i != j and nums[j] < nums[i]:
                count += 1
        result.append(count)
    return result
```


```python
from collections import deque

def minCost(grid):
    m, n = len(grid), len(grid[0])
    cost = 0

    visited = [[1000000] * n for _ in range(m)]
    q = deque([(0, 0)])
    visited[0][0] = 0

    while q:
        y, x = q.popleft()
        if y == m - 1 and x == n - 1:
            cost = visited[y][x]
            break

        dx = [1, 0, -1, 0]
        dy = [0, 1, 0, -1]

        for dir in range(4):
            newY, newX = y + dy[dir], x + dx[dir]
            if 0 <= newY < m and 0 <= newX < n:
                newCost = visited[y][x] + (1 if dir + 1 != grid[y][x] else 0)
                if newCost < visited[newY][newX]:
                    visited[newY][newX] = newCost
                    q.append((newY, newX))

    return cost
```

```cpp
#include <vector>
#include <queue>
#include <utility>

using namespace std;

int minCost(vector<vector<int>>& grid) {
    int m = grid.size(), n = grid[0].size(), cost = 0;

    vector<vector<int>> visited(m, vector<int>(n, 1000000));
    queue<pair<int, int>> q;
    q.push({0, 0});
    visited[0][0] = 0;

    while (!q.empty()) {
        pair<int, int> curr = q.front();
        q.pop();
        int y = curr.first, x = curr.second;
        if (y == m - 1 && x == n - 1) {
            cost = visited[y][x];
            break;
        }

        int dx[4] = {1, 0, -1, 0};
        int dy[4] = {0, 1, 0, -1};

        for (int dir = 0; dir < 4; ++dir) {
            int newY = y + dy[dir], newX = x + dx[dir];
            if (0 <= newY && newY < m && 0 <= newX && newX < n) {
                int newCost = visited[y][x] + (dir + 1 != grid[y][x]);
                if (newCost < visited[newY][newX]) {
                    visited[newY][newX] = newCost;
                    q.push({newY, newX});
                }
            }
        }
    }
    return cost;
}
```


```cpp
#include <string>
#include <stack>

std::string minRemoveToMakeValid(const std::string &s) {
    std::stack<int> stk;
    std::string result = s;

    for (int i = 0; i < s.size(); i++) {
        if (s[i] == '(') {
            stk.push(i);
        } else if (s[i] == ')') {
            if (!stk.empty()) {
                stk.pop();
            } else {
                result[i] = '-';
            }
        }
    }

    while (!stk.empty()) {
        result[stk.top()] = '-';
        stk.pop();
    }

    result.erase(std::remove(result.begin(), result.end(), '-'), result.end());
    return result;
}
```

e aoooooeiouuuuueieee nn jj l mmm uuu k ppp xx eleetminicoworoep ff leetcodeisgreat oo ee www bcbcbc sss bb hhh ww abcde dddd x qqq w j y aeeioouuoaeeioouuoaeeioouuo tt bbc q eee aa cc kk xxx n gg dd g rr h eleetminicoworoep i fff mm ll yyy vvv zz cccc v t a f kkk o p vv nnn a ttt rrr z c aoieuaoieuaoieuaoieu uu d iii u r jjj b uuoioieeeuuoioieee lll ii m qq ooo eleetminicoworoep aaa ss pp hh yy zzz ggg

cc eleetminicoworoep r iii ff h qq ppp mmm eee g ee kkk b j aaa ggg rrr abcde fff sss www xx mm z t tt i p c zzz aoooooeiouuuuueieee ss uuu dddd kk nn aeeioouuoaeeioouuoaeeioouuo xxx rr ttt cccc eleetminicoworoep d zz oo q v nnn ww u x f jj o a a jjj hh leetcodeisgreat e pp l aoieuaoieuaoieuaoieu aa y m yyy bb w ooo vv bbc bcbcbc n eleetminicoworoep qqq ll dd yy ii k gg vvv lll hhh uuoioieeeuuoioieee uu

```java
import java.util.Stack;

public String minRemoveToMakeValid(String s) {
    Stack<Integer> stk = new Stack<>();
    char[] result = s.toCharArray();

    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '(') {
            stk.push(i);
        } else if (s.charAt(i) == ')') {
            if (!stk.empty()) {
                stk.pop();
            } else {
                result[i] = '-';
            }
        }
    }

    while (!stk.empty()) {
        result[stk.pop()] = '-';
    }

    return new String(result).replace("-", "");
}
```


```java
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    int maxSum = 0;

    public int maxSumBST(TreeNode root) {
        dfs(root);
        return maxSum;
    }

    private int[] dfs(TreeNode node) {
        if (node == null)
            return new int[]{1, 0, Integer.MAX_VALUE, Integer.MIN_VALUE};

        int[] l = dfs(node.left);
        int[] r = dfs(node.right);

        if (l[0] == 0 || r[0] == 0 || node.val <= l[3] || node.val >= r[2])
            return new int[4];

        int currSum = node.val + l[1] + r[1];
        maxSum = Math.max(maxSum, currSum);

        return new int[]{1, currSum, Math.min(node.val, l[2]), Math.max(node.val, r[3])};
    }
}
```

```python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def maxSumBST(self, root: TreeNode) -> int:
        max_sum = [0]

        def dfs(node):
            if not node:
                return 1, 0, float("inf"), float("-inf")

            l = dfs(node.left)
            r = dfs(node.right)

            if not l[0] or not r[0] or node.val <= l[3] or node.val >= r[2]:
                return 0, 0, 0, 0

            curr_sum = node.val + l[1] + r[1]
            max_sum[0] = max(max_sum[0], curr_sum)

            return 1, curr_sum, min(node.val, l[2]), max(node.val, r[3])

        dfs(root)
        return max_sum[0]
```


```java
class Solution {
    public String generateTheString(int n) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < n - 1; i++)
            result.append('a');
        if (n % 2 == 0)
            result.append('b');
        else
            result.append('a');
        return result.toString();
    }
}
```

```python
def generateTheString(n: int) -> str:
    result = 'a' * n
    if n % 2 == 0:
        result = result[:-1] + 'b'
    return result
```


```java
public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {
    List<List<Integer>> subordinates = new ArrayList<>();
    for (int i = 0; i < n; ++i) {
        subordinates.add(new ArrayList<>());
    }
    for (int i = 0; i < n; ++i) {
        if (manager[i] != -1) {
            subordinates.get(manager[i]).add(i);
        }
    }
    return dfs(headID, subordinates, informTime);
}

private int dfs(int employee, List<List<Integer>> subordinates, int[] informTime) {
    if (informTime[employee] == 0) {
        return 0;
    }
    int max_time = 0;
    for (int i : subordinates.get(employee)) {
        max_time = Math.max(max_time, dfs(i, subordinates, informTime));
    }
    return max_time + informTime[employee];
}
```

n = 1, headID = 0, manager = \[-1\], informTime = \[0\]

```cpp
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
    vector<vector<int>> subordinates(n);
    for (int i = 0; i < n; ++i) {
        if (manager[i] != -1) {
            subordinates[manager[i]].push_back(i);
        }
    }
    return dfs(headID, subordinates, informTime);
}

int dfs(int employee, vector<vector<int>>& subordinates, vector<int>& informTime) {
    if (informTime[employee] == 0) {
        return 0;
    }
    int max_time = 0;
    for (int i : subordinates[employee]) {
        max_time = max(max_time, dfs(i, subordinates, informTime));
    }
    return max_time + informTime[employee];
}
```


```python
from collections import defaultdict

def dfs(node, parent, t, target, graph, prob, ans):
    if t == 0:
        if node == target:
            ans[0] += prob
        return

    has_child = False
    for neighbor in graph[node]:
        if neighbor != parent:
            has_child = True
            dfs(neighbor, node, t - 1, target, graph, prob / (len(graph[node]) - (1 if node != 1 else 0)), ans)

    if not has_child and node == target:
        ans[0] += prob

def frogPosition(n, edges, t, target):
    graph = defaultdict(list)
    for a, b in edges:
        graph[a].append(b)
        graph[b].append(a)

    ans = [0.0]
    dfs(1, -1, t, target, graph, 1.0, ans)
    return ans[0]
```

```cpp
#include <vector>
using namespace std;

void dfs(int node, int parent, int t, int target, vector<vector<int>>& graph, double prob, vector<double>& ans) {
    if (t == 0) {
        if(node == target) ans[0] += prob;
        return;
    }

    bool has_child = false;
    for(int i = 0; i < graph[node].size(); ++i) {
        if(graph[node][i] != parent) {
            has_child = true;
            dfs(graph[node][i], node, t - 1, target, graph, prob / (graph[node].size() - (node != 1)), ans);
        }
    }

    if(!has_child && node == target) ans[0] += prob;
}

double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
    vector<vector<int>> graph(n + 1);
    for (int i = 0; i < n - 1; ++i) {
        int a = edges[i][0], b = edges[i][1];
        graph[a].push_back(b);
        graph[b].push_back(a);
    }

    vector<double> ans(1, 0.0);
    dfs(1, -1, t, target, graph, 1.0, ans);
    return ans[0];
}
```


```cpp
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

void dfs(vector<vector<int>>& grid, int x, int y) {
    int n = grid.size(), m = grid[0].size();
    grid[x][y] = 1;
    for (int i = 0; i < 4; i++) {
        int nx = x + dx[i], ny = y + dy[i];
        if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == 0) {
            dfs(grid, nx, ny);
        }
    }
}

int closedIsland(vector<vector<int>>& grid) {
    int n = grid.size(), m = grid[0].size();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {
                if (grid[i][j] == 0) {
                    dfs(grid, i, j);
                }
            }
        }
    }
    int res = 0;
    for (int i = 1; i < n - 1; i++) {
        for (int j = 1; j < m - 1; j++) {
            if (grid[i][j] == 0) {
                dfs(grid, i, j);
                res++;
            }
        }
    }
    return res;
}
```

```java
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, -1, 1};

void dfs(int[][] grid, int x, int y) {
    int n = grid.length, m = grid[0].length;
    grid[x][y] = 1;
    for (int i = 0; i < 4; i++) {
        int nx = x + dx[i], ny = y + dy[i];
        if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == 0) {
            dfs(grid, nx, ny);
        }
    }
}

public int closedIsland(int[][] grid) {
    int n = grid.length, m = grid[0].length;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {
                if (grid[i][j] == 0) {
                    dfs(grid, i, j);
                }
            }
        }
    }
    int res = 0;
    for (int i = 1; i < n - 1; i++) {
        for (int j = 1; j < m - 1; j++) {
            if (grid[i][j] == 0) {
                dfs(grid, i, j);
                res++;
            }
        }
    }
    return res;
}
```


```java
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public TreeNode balanceBST(TreeNode root) {
        List<TreeNode> sortedNodes = new ArrayList<>();
        inorderTraversal(root, sortedNodes);
        return sortedArrayToBST(sortedNodes, 0, sortedNodes.size() - 1);
    }

    private void inorderTraversal(TreeNode node, List<TreeNode> sortedNodes) {
        if (node == null) return;
        inorderTraversal(node.left, sortedNodes);
        sortedNodes.add(node);
        inorderTraversal(node.right, sortedNodes);
    }

    private TreeNode sortedArrayToBST(List<TreeNode> sortedNodes, int start, int end) {
        if (start > end) return null;
        int mid = start + (end - start) / 2;
        TreeNode newNode = sortedNodes.get(mid);
        newNode.left = sortedArrayToBST(sortedNodes, start, mid - 1);
        newNode.right = sortedArrayToBST(sortedNodes, mid + 1, end);
        return newNode;
    }
}
```

```cpp
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    TreeNode* balanceBST(TreeNode* root) {
        vector<TreeNode*> sortedNodes;
        inorderTraversal(root, sortedNodes);
        return sortedArrayToBST(sortedNodes, 0, sortedNodes.size() - 1);
    }

    void inorderTraversal(TreeNode* node, vector<TreeNode*>& sortedNodes) {
        if (node == nullptr) return;
        inorderTraversal(node->left, sortedNodes);
        sortedNodes.push_back(node);
        inorderTraversal(node->right, sortedNodes);
    }

    TreeNode* sortedArrayToBST(vector<TreeNode*>& sortedNodes, int start, int end) {
        if (start > end) return nullptr;
        int mid = start + (end - start) / 2;
        TreeNode* newNode = sortedNodes[mid];
        newNode->left = sortedArrayToBST(sortedNodes, start, mid - 1);
        newNode->right = sortedArrayToBST(sortedNodes, mid + 1, end);
        return newNode;
    }
};
```


```java
public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
    int distance = 0;
    for (int a : arr1) {
        boolean found = true;
        for (int b : arr2) {
            if (Math.abs(a - b) <= d) {
                found = false;
                break;
            }
        }
        if (found) distance++;
    }
    return distance;
}
```

```python
def findTheDistanceValue(arr1, arr2, d):
    distance = 0
    for a in arr1:
        found = True
        for b in arr2:
            if abs(a - b) <= d:
                found = False
                break
        if found:
            distance += 1
    return distance
```


```java
public int maxSumDivThree(int[] nums) {
    int[] dp = new int[3];
    for (int num : nums) {
        int[] temp = Arrays.copyOf(dp, 3);
        for (int s : temp) {
            dp[(s + num) % 3] = Math.max(dp[(s + num) % 3], s + num);
        }
    }
    return dp[0];
}
```

```python
def maxSumDivThree(nums):
    dp = [0, 0, 0]
    for num in nums:
        temp = dp[:]
        for s in temp:
            dp[(s + num) % 3] = max(dp[(s + num) % 3], s + num)
    return dp[0]
```


```java
public int sumOfFourDivisors(int[] nums) {
    int sum = 0;
    for (int num : nums) {
        int count = 0;
        int div_sum = 0;
        for (int i = 1; i * i <= num; ++i) {
            if (num % i == 0) {
                count += (i * i == num) ? 1 : 2;
                div_sum += i + (num / i);
                if (count > 4) break;
            }
        }
        if (count == 4) sum += div_sum;
    }
    return sum;
}
```

```cpp
int sumOfFourDivisors(std::vector<int>& nums) {
    int sum = 0;
    for (int num : nums) {
        int count = 0;
        int div_sum = 0;
        for (int i = 1; i * i <= num; ++i) {
            if (num % i == 0) {
                count += (i * i == num) ? 1 : 2;
                div_sum += i + (num / i);
                if (count > 4) break;
            }
        }
        if (count == 4) sum += div_sum;
    }
    return sum;
}
```


```java
public int findLucky(int[] arr) {
    Map<Integer, Integer> freq = new HashMap<>();
    for (int num : arr) {
        freq.put(num, freq.getOrDefault(num, 0) + 1);
    }
    int maxLucky = -1;
    for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
        if (entry.getKey().equals(entry.getValue())) {
            maxLucky = Math.max(maxLucky, entry.getKey());
        }
    }
    return maxLucky;
}
```

```python
def find_lucky(arr):
    freq = {}
    for num in arr:
        freq[num] = freq.get(num, 0) + 1
    max_lucky = -1
    for num, count in freq.items():
        if num == count:
            max_lucky = max(max_lucky, num)
    return max_lucky
```


```python
def minTimeToVisitAllPoints(points: List[List[int]]) -> int:
    time = 0
    for i in range(1, len(points)):
        dx = abs(points[i][0] - points[i-1][0])
        dy = abs(points[i][1] - points[i-1][1])
        time += max(dx, dy)
    return time
```

```cpp
#include <vector>
#include <cmath>

int minTimeToVisitAllPoints(std::vector<std::vector<int>>& points) {
    int time = 0;
    for(int i = 1; i < points.size(); ++i) {
        int dx = abs(points[i][0] - points[i-1][0]);
        int dy = abs(points[i][1] - points[i-1][1]);
        time += std::max(dx, dy);
    }
    return time;
}
```


```cpp
int countLargestGroup(int n) {
    std::vector<int> groups(37, 0);
    int largest_group_size = 0;
    int count_largest_groups = 0;

    for (int i = 1; i <= n; i++) {
        int sum = 0, num = i;
        while (num) {
            sum += num % 10;
            num /= 10;
        }
        groups[sum]++;
        if (groups[sum] > largest_group_size) {
            largest_group_size = groups[sum];
            count_largest_groups = 1;
        } else if (groups[sum] == largest_group_size) {
            count_largest_groups++;
        }
    }
    return count_largest_groups;
}
```

```python
def countLargestGroup(n: int) -> int:
    groups = [0] * 37
    largest_group_size = 0
    count_largest_groups = 0

    for i in range(1, n + 1):
        sum_of_digits = sum(map(int, str(i)))
        groups[sum_of_digits] += 1
        if groups[sum_of_digits] > largest_group_size:
            largest_group_size = groups[sum_of_digits]
            count_largest_groups = 1
        elif groups[sum_of_digits] == largest_group_size:
            count_largest_groups += 1

    return count_largest_groups
```


```java
import java.util.*;

public String tictactoe(int[][] moves) {
    int[][] grid = new int[3][3];
    int player = 1;
    for (int[] move : moves) {
        grid[move[0]][move[1]] = player;
        if ((grid[0][move[1]] == player && grid[1][move[1]] == player && grid[2][move[1]] == player) ||
            (grid[move[0]][0] == player && grid[move[0]][1] == player && grid[move[0]][2] == player) ||
            (move[0] == move[1] && grid[0][0] == player && grid[1][1] == player && grid[2][2] == player) ||
            (move[0] + move[1] == 2 && grid[0][2] == player && grid[1][1] == player && grid[2][0] == player)) {
            return player == 1 ? "A" : "B";
        }
        player = 3 - player;
    }
    return moves.length == 9 ? "Draw" : "Pending";
}
```

"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"
"Pending"

```cpp
#include <vector>
#include <string>

std::string tictactoe(std::vector<std::vector<int>>& moves) {
    int grid[3][3] = {0};
    int player = 1;
    for (const auto& move : moves) {
        grid[move[0]][move[1]] = player;
        if ((grid[0][move[1]] == player && grid[1][move[1]] == player && grid[2][move[1]] == player) ||
            (grid[move[0]][0] == player && grid[move[0]][1] == player && grid[move[0]][2] == player) ||
            (move[0] == move[1] && grid[0][0] == player && grid[1][1] == player && grid[2][2] == player) ||
            (move[0] + move[1] == 2 && grid[0][2] == player && grid[1][1] == player && grid[2][0] == player)) {
            return player == 1 ? "A" : "B";
        }
        player = 3 - player;
    }
    return moves.size() == 9 ? "Draw" : "Pending";
}
```


```python
def countSquares(matrix: List[List[int]]) -> int:
    m, n, ans = len(matrix), len(matrix[0]), 0
    dp = [[0] * n for _ in range(m)]
    for i in range(m):
        for j in range(n):
            if i == 0 or j == 0:
                dp[i][j] = matrix[i][j]
            elif matrix[i][j]:
                dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
            ans += dp[i][j]
    return ans
```

```cpp
int countSquares(vector<vector<int>>& matrix) {
    int m = matrix.size(), n = matrix[0].size(), ans = 0;
    vector<vector<int>> dp(m, vector<int>(n, 0));
    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            if(i == 0 || j == 0) dp[i][j] = matrix[i][j];
            else if(matrix[i][j]) dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;
            ans += dp[i][j];
        }
    }
    return ans;
}
```


```cpp
int num_steps(const std::string& s) {
    int steps = 0, carry = 0;
    for (int i = s.length() - 1; i > 0; --i) {
        int bit = s[i] - '0';
        if (bit && carry) {
            carry = 1;
            steps += 2;
        } else if (bit || carry) {
            carry ^= 1;
            steps += 2;
        } else {
            steps++;
        }
    }

    return steps + carry;
}
```

```java
public int numSteps(String s) {
    int steps = 0, carry = 0;
    for (int i = s.length() - 1; i > 0; --i) {
        int bit = s.charAt(i) - '0';
        if (bit == 1 && carry == 1) {
            carry = 1;
            steps += 2;
        } else if (bit == 1 || carry == 1) {
            carry ^= 1;
            steps += 2;
        } else {
            steps++;
        }
    }

    return steps + carry;
}
```


```python
import heapq

def longest_diverse_string(a: int, b: int, c: int) -> str:
    result = ""
    pq = [(-a, 'a'), (-b, 'b'), (-c, 'c')]
    heapq.heapify(pq)

    while pq:
        first = heapq.heappop(pq)
        if not result or result[-1] != first[1]:
            result += first[1]
            first = (first[0] + 1, first[1])
            if first[0] < 0:
                heapq.heappush(pq, first)
        elif pq:
            second = heapq.heappop(pq)
            result += second[1]
            second = (second[0] + 1, second[1])
            if second[0] < 0:
                heapq.heappush(pq, second)
            if first[0] < 0:
                heapq.heappush(pq, first)
        else:
            break

    return result
```

"ababacabacaba" "" "bababcbab" "bcbcbcbabcba" "cbacbacba" "cbacbacba" "bababcbabcbab" "cbcacbacbacba" "abababa" "abacaba" "bcbcbcbcb" "acacacacacba" "cbcbcbcbcac" "bcbcbabcbabcba" "ababababa" "abacba" "cbcbcbcbcbca" "cbcbcbcbc" "cbcac" "cbcbcbc" "cbcbca" "babab" "cbcbcbcacba" "cba" "cbcbcbcbcbcba" "cbcac" "cacacacacaca" "cbcbca" "acacaca" "abacabacaba" "bcbcbcb" "bcbab" "cacacacac" "cba" "cacacacacba" "cbcbcacba" "acacacaba" "acaba" "aca" "cbcac" "bcbab" "abacaba" "" "cacacacbcacbca" "babababcba" "cacacacac" "abacba" "cbcac" "cacbcacbcac" "cbcbcbacbacba" "acacacacabacba" "acacabacba" "cacacbcac" "cbcbcbcbcacba" "acaba"

```cpp
#include <algorithm>
#include <queue>
using namespace std;

string longestDiverseString(int a, int b, int c) {
    string result = "";
    using T = pair<int, char>;
    priority_queue<T> pq;
    if (a) pq.push({a, 'a'});
    if (b) pq.push({b, 'b'});
    if (c) pq.push({c, 'c'});

    while (!pq.empty()) {
        T first = pq.top(); pq.pop();
        if (!result.empty() && result.back() == first.second) {
            if (pq.empty()) break;
            T second = pq.top(); pq.pop();
            result += second.second;
            second.first--;
            if (second.first) pq.push(second);
            pq.push(first);
        } else {
            result += first.second;
            first.first--;
            if (first.first) pq.push(first);
        }
    }
    return result;
}
```


```java
public String stoneGameIII(int[] stoneValue) {
    int n = stoneValue.length;
    int[] dp = new int[n + 1];
    dp[n] = 0;

    for (int i = n - 1; i >= 0; --i) {
        dp[i] = Integer.MIN_VALUE;
        int curr = 0;
        for (int j = 0; j < 3 && i + j < n; ++j) {
            curr += stoneValue[i + j];
            dp[i] = Math.max(dp[i], curr - dp[i + j + 1]);
        }
    }

    return dp[0] == 0 ? "Tie " : dp[0] > 0 ? "Alice " : "Bob ";
}
```

"Bob "
"Alice "
"Alice "
"Tie "
"Tie "
"Alice "
"Alice "
"Tie "
"Tie "
"Bob "
"Alice "
"Alice "
"Bob "
"Alice "
"Alice "
"Alice "
"Alice "
"Alice "
"Bob "
"Bob "
"Alice "
"Alice "
"Alice "
"Tie "
"Alice "
"Alice "
"Alice "
"Bob "
"Bob "
"Bob "
"Alice "
"Alice "
"Alice "
"Alice "
"Alice "
"Tie "

```cpp
#include <vector>
#include <string>
using namespace std;

string stoneGameIII(vector<int>& stoneValue) {
    int n = stoneValue.size();
    vector<int> dp(n + 1, INT_MIN);
    dp[n] = 0;

    for (int i = n - 1; i >= 0; --i) {
        int curr = 0;
        for (int j = 0; j < 3 && i + j < n; ++j) {
            curr += stoneValue[i + j];
            dp[i] = max(dp[i], curr - dp[i + j + 1]);
        }
    }

    return dp[0] == 0 ? "Tie " : dp[0] > 0 ? "Alice " : "Bob ";
}
```


```java
public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public int getDecimalValue(ListNode head) {
    int num = 0;
    while (head != null) {
        num = (num << 1) | head.val;
        head = head.next;
    }
    return num;
}
```

```cpp
class ListNode {
public:
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

int getDecimalValue(ListNode* head) {
    int num = 0;
    while (head) {
        num = (num << 1) | head->val;
        head = head->next;
    }
    return num;
}
```


```python
class Solution:
    def generate_strings(self, n: int, current: str, strings: list) -> None:
        if n == 0:
            strings.append(current)
            return
        for c in "abc":
            if not current or current[-1] != c:
                self.generate_strings(n - 1, current + c, strings)

    def getHappyString(self, n: int, k: int) -> str:
        strings = []
        self.generate_strings(n, "", strings)
        return strings[k - 1] if k <= len(strings) else ""
```

```cpp
#include <string>
#include <vector>

using namespace std;

class Solution {
public:
    void generate_strings(int n, string& current, vector<string>& strings) {
        if (n == 0) {
            strings.push_back(current);
            return;
        }
        for (char c = 'a'; c <= 'c'; ++c) {
            if (current.empty() || current.back() != c) {
                current.push_back(c);
                generate_strings(n - 1, current, strings);
                current.pop_back();
            }
        }
    }

    string getHappyString(int n, int k) {
        vector<string> strings;
        string current = "";
        generate_strings(n, current, strings);
        return k <= strings.size() ? strings[k - 1] : "";
    }
};
```


```python
from collections import deque

def reformat(s: str) -> str:
    letters, digits = deque(), deque()

    for c in s:
        if c.isalpha():
            letters.append(c)
        else:
            digits.append(c)

    if abs(len(letters) - len(digits)) > 1:
        return ""

    result = []
    use_letter = len(letters) > len(digits)

    while letters or digits:
        if use_letter:
            result.append(letters.popleft())
        else:
            result.append(digits.popleft())
        use_letter = not use_letter

    return ''.join(result)
```

```java
import java.util.LinkedList;
import java.util.Queue;

public String reformat(String s) {
    Queue<Character> letters = new LinkedList<>();
    Queue<Character> digits = new LinkedList<>();

    for (char c : s.toCharArray()) {
        if (Character.isLetter(c)) letters.add(c);
        else digits.add(c);
    }

    if (Math.abs(letters.size() - digits.size()) > 1) return "";

    StringBuilder result = new StringBuilder();
    boolean useLetter = letters.size() > digits.size();

    while (!letters.isEmpty() || !digits.isEmpty()) {
        if (useLetter) {
            result.append(letters.poll());
        } else {
            result.append(digits.poll());
        }
        useLetter = !useLetter;
    }

    return result.toString();
}
```


```python
from collections import defaultdict
from typing import List

def displayTable(orders: List[List[str]]) -> List[List[str]]:
    tables = defaultdict(lambda: defaultdict(int))
    foodSet = set()

    for order in orders:
        tableNumber = int(order[1])
        foodItem = order[2]
        tables[tableNumber][foodItem] += 1
        foodSet.add(foodItem)

    foodList = sorted(foodSet)
    result = [["Table"] + foodList]

    for tableNumber, table in sorted(tables.items()):
        row = [str(tableNumber)]
        row.extend(str(table[foodItem]) for foodItem in foodList)
        result.append(row)

    return result
```

Table
Dessert
Eggs Benedict
French Fries
Grape Juice

Table Lemonade Lobster Milkshake Noodles

Table
Apple Pie
Banana Split
Cheeseburger

Table
Beef Burrito
Ceviche
Fried Chicken
Water

Table
Waffle
X-treme Burger
Yogurt
Zucchini

```cpp
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>

std::vector<std::vector<std::string>> displayTable(std::vector<std::vector<std::string>>& orders) {
    std::map<int, std::map<std::string, int>> tables;
    std::set<std::string> foodSet;

    for (auto& order : orders) {
        int tableNumber = std::stoi(order[1]);
        std::string foodItem = order[2];
        tables[tableNumber][foodItem]++;
        foodSet.insert(foodItem);
    }

    std::vector<std::vector<std::string>> result;
    std::vector<std::string> header = {"Table"};
    header.insert(header.end(), foodSet.begin(), foodSet.end());
    result.push_back(header);

    for (auto& table : tables) {
        std::vector<std::string> row = {std::to_string(table.first)};
        for (const auto& foodItem : foodSet) {
            row.push_back(std::to_string(table.second[foodItem]));
        }
        result.push_back(row);
    }

    return result;
}
```


```python
from collections import Counter

def is_possible_divide(nums: List[int], k: int) -> bool:
    counts = Counter(nums)

    for key in sorted(counts):
        if counts[key] > 0:
            for i in range(k-1, -1, -1):
                if counts[key+i] < counts[key]:
                    return False
                counts[key+i] -= counts[key]

    return True
```

true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true

```cpp
#include <map>

bool isPossibleDivide(std::vector<int>& nums, int k) {
    std::map<int, int> counts;
    for (int num : nums) counts[num]++;

    for (auto it = counts.begin(); it != counts.end(); ++it) {
        if (it->second > 0) {
            for (int i = k - 1; i >= 0; --i) {
                if ((counts[it->first + i] -= it->second) < 0) return false;
            }
        }
    }

    return true;
}
```


```cpp
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;

int maxSubstringOccurrences(const string &s, int k) {
    int n = s.length(), res = 0;
    unordered_map<char, int> freq;
    for (int i = 0; i < n; ++i) {
        freq[s[i]]++;
        if (freq.size() <= k) {
            res = max(res, freq[s[i]]);
        }
    }
    return (freq.size() > k) ? 0 : res;
}
```

```python
def max_substring_occurrences(s: str, k: int) -> int:
    freq = {}
    res = 0
    for c in s:
        freq[c] = freq.get(c, 0) + 1
        if len(freq) <= k:
            res = max(res, freq[c])
    return 0 if len(freq) > k else res
```


```python
from collections import deque

def maxCandies(status, candies, keys, containedBoxes, initialBoxes):
    max_candies = 0
    visited = set()
    to_process = deque(initialBoxes)

    while to_process:
        box = to_process.popleft()

        if box in visited:
            continue

        visited.add(box)

        if status[box]:
            max_candies += candies[box]
            for key in keys[box]:
                status[key] = 1
                if key in visited:
                    to_process.append(key)
            for contained in containedBoxes[box]:
                to_process.append(contained)
        else:
            to_process.append(box)

    return max_candies
```

```cpp
#include <vector>
#include <queue>
#include <unordered_set>

int maxCandies(std::vector<int>& status, std::vector<int>& candies, std::vector<std::vector<int>>& keys, std::vector<std::vector<int>>& containedBoxes, std::vector<int>& initialBoxes) {
    int max_candies = 0;
    std::unordered_set<int> visited;
    std::queue<int> to_process;

    for (int box : initialBoxes) {
        to_process.push(box);
    }

    while (!to_process.empty()) {
        int box = to_process.front();
        to_process.pop();

        if (visited.count(box)) {
            continue;
        }

        visited.insert(box);

        if (status[box] == 1) {
            max_candies += candies[box];
            for (int key : keys[box]) {
                status[key] = 1;
                if (visited.count(key)) {
                    to_process.push(key);
                }
            }
            for (int contained : containedBoxes[box]) {
                to_process.push(contained);
            }
        } else {
            to_process.push(box);
        }
    }

    return max_candies;
}
```


```cpp
int maxSum(vector<int>& nums, int k) {
    int n = nums.size();
    priority_queue<int> pq;
    vector<long long> dp(n + 1, 0);
    long long sum = 0;

    for (int i = 0; i < n; ++i) {
        if (i >= k) pq.pop(); // Maintain the maximum size of k
        pq.push(dp[i] - nums[i]);
        dp[i + 1] = max(dp[i], nums[i] + pq.top());
        sum = max(sum, dp[i + 1]);
    }

    return sum;
}
```

```java
public int maxSum(int[] nums, int k) {
    int n = nums.length;
    PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
    long[] dp = new long[n + 1];
    long sum = 0;

    for (int i = 0; i < n; i++) {
        if (i >= k) pq.poll(); // Maintain the maximum size of k
        pq.offer((int)(dp[i] - nums[i]));
        dp[i + 1] = Math.max(dp[i], nums[i] + pq.peek());
        sum = Math.max(sum, dp[i + 1]);
    }

    return (int) sum;
}
```


```python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def isValidSequence(root, arr, index=0):
    if not root or index >= len(arr) or arr[index] != root.val:
        return False
    if not root.left and not root.right:
        return index == len(arr) - 1
    return isValidSequence(root.left, arr, index + 1) or isValidSequence(root.right, arr, index + 1)
```

false false false false true true false false false

```cpp
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

bool isValidSequence(TreeNode* root, vector<int>& arr, int index = 0) {
    if (root == nullptr || index >= arr.size() || arr[index] != root->val) {
        return false;
    }
    if (root->left == nullptr && root->right == nullptr) {
        return index == arr.size() - 1;
    }
    return isValidSequence(root->left, arr, index + 1) || isValidSequence(root->right, arr, index + 1);
}
```


```java
public int maxDiff(int num) {
    int a = -1, b = -1;
    String s = Integer.toString(num);
    for (char c : s.toCharArray()) {
        if (a == -1 && c != '9') {
            a = c - '0';
        }
        if (b == -1 && c > '1') {
            b = c - '0';
        }
        if (a != -1 && b != -1) {
            break;
        }
    }
    int result = 0;
    for (char c : s.toCharArray()) {
        if (c - '0' == a) {
            result = result * 10 + 9;
        } else if (c - '0' == b) {
            result = result * 10 + ((c == s.charAt(0)) ? 1 : 0);
        } else {
            result = result * 10 + c - '0';
        }
    }
    return result - num;
}
```


```java
import java.util.ArrayDeque;
import java.util.Deque;

public int longestSubarray(int[] nums, int limit) {
    Deque<Integer> maxDeque = new ArrayDeque<>();
    Deque<Integer> minDeque = new ArrayDeque<>();
    int left = 0, right = 0, longest = 0;
    while (right < nums.length) {
        while (!maxDeque.isEmpty() && nums[right] > maxDeque.peekLast()) maxDeque.pollLast();
        while (!minDeque.isEmpty() && nums[right] < minDeque.peekLast()) minDeque.pollLast();

        maxDeque.offerLast(nums[right]);
        minDeque.offerLast(nums[right]);

        while (maxDeque.peekFirst() - minDeque.peekFirst() > limit) {
            if (nums[left] == maxDeque.peekFirst()) maxDeque.pollFirst();
            if (nums[left] == minDeque.peekFirst()) minDeque.pollFirst();
            left++;
        }

        longest = Math.max(longest, right - left + 1);
        right++;
    }
    return longest;
}
```

```cpp
#include <deque>
int longestSubarray(vector<int>& nums, int limit) {
    deque<int> max_deque, min_deque;
    int left = 0, right = 0, longest = 0;
    while (right < nums.size()) {
        while (!max_deque.empty() && nums[right] > max_deque.back()) max_deque.pop_back();
        while (!min_deque.empty() && nums[right] < min_deque.back()) min_deque.pop_back();

        max_deque.push_back(nums[right]);
        min_deque.push_back(nums[right]);

        while (max_deque.front() - min_deque.front() > limit) {
            if (max_deque.front() == nums[left]) max_deque.pop_front();
            if (min_deque.front() == nums[left]) min_deque.pop_front();
            left++;
        }

        longest = max(longest, right - left + 1);
        right++;
    }
    return longest;
}
```


```cpp
#include <vector>
#include <queue>
using namespace std;

int kthSmallest(vector<vector<int>>& mat, int k) {
    int m = mat.size(), n = mat[0].size();
    priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> minHeap;
    minHeap.push({mat[0][0], 0, 0});

    vector<vector<bool>> visited(m, vector<bool>(n, false));
    visited[0][0] = true;
    int count = 0;

    while (!minHeap.empty()) {
        auto cur = minHeap.top();
        minHeap.pop();
        int sum = cur[0], row = cur[1], col = cur[2];

        count++;
        if (count == k) {
            return sum;
        }

        if (row + 1 < m && !visited[row + 1][col]) {
            visited[row + 1][col] = true;
            minHeap.push({sum - mat[row][col] + mat[row + 1][col], row + 1, col});
        }

        if (col + 1 < n && !visited[row][col + 1]) {
            visited[row][col + 1] = true;
            minHeap.push({sum - mat[row][col] + mat[row][col + 1], row, col + 1});
        }
    }

    return -1;
}
```

```python
import heapq

def kthSmallest(mat, k):
    m, n = len(mat), len(mat[0])
    minHeap = [(mat[0][0], 0, 0)]

    visited = set([(0, 0)])
    count = 0

    while minHeap:
        cur = heapq.heappop(minHeap)
        sum, row, col = cur

        count += 1
        if count == k:
            return sum

        if row + 1 < m and (row + 1, col) not in visited:
            visited.add((row + 1, col))
            heapq.heappush(minHeap, (sum - mat[row][col] + mat[row + 1][col], row + 1, col))

        if col + 1 < n and (row, col + 1) not in visited:
            visited.add((row, col + 1))
            heapq.heappush(minHeap, (sum - mat[row][col] + mat[row][col + 1], row, col + 1))

    return -1
```


```java
import java.util.ArrayList;
import java.util.List;

public List<String> buildArray(int[] target, int n) {
    List<String> result = new ArrayList<>();
    int current = 1;
    for (int num : target) {
        while (current < num) {
            result.add("Push ");
            result.add("Pop ");
            current++;
        }
        result.add("Push ");
        current++;
    }
    return result;
}
```

Push Push Push Push Push Push Push Push Pop Push Pop Push Push Pop Push Push

Push Pop Push Pop Push Pop Push Push Push Push

Push Push Push Push Push Push Push Push Push Pop Push Pop Push Push Pop Push Pop Push

Push Push Push Push Push Push Push Push Push Pop Push Push

Push Push Push Push Push Push Push Push Pop Push Push Pop Push Pop Push Push Pop Push

Push Push Push Push Push Push Push Push Pop Push Push Pop Push Push Pop Push Pop Push

Push Push Push Push Push Push Push Push Pop Push Pop Push Push Push Pop Push Pop Push

Push Push Push Push Push Push Push Push Push Pop Push Pop Push Pop Push Push Pop Push

```cpp
#include <vector>
#include <string>

std::vector<std::string> buildArray(std::vector<int>& target, int n) {
    std::vector<std::string> result;
    int current = 1;
    for (int num : target) {
        while (current < num) {
            result.push_back("Push ");
            result.push_back("Pop ");
            current++;
        }
        result.push_back("Push ");
        current++;
    }
    return result;
}
```


```cpp
#include <string>
#include <vector>

std::string largestNumber(std::vector<int>& cost, int target) {
    std::vector<std::string> dp(target + 1, "");

    for (int i = 0; i < 9; ++i) {
        for (int j = cost[i]; j <= target; ++j) {
            if (dp[j - cost[i]].size() < j - cost[i] && dp[j - cost[i]].size() + 1 > dp[j].size()) {
                dp[j] = dp[j - cost[i]] + std::to_string(i + 1);
            }
        }
    }

    return dp[target].empty() ? "0" : dp[target];
}
```

```python
def largestNumber(cost, target):
    dp = ["" for _ in range(target + 1)]
    dp[0] = ""

    for i in range(9):
        for j in range(cost[i], target + 1):
            if dp[j - cost[i]] != None and len(dp[j - cost[i]]) < j - cost[i] \
               and (dp[j] == None or len(dp[j - cost[i]]) + 1 > len(dp[j])):
                dp[j] = dp[j - cost[i]] + str(i + 1)

    return dp[target] if dp[target] else "0"
```


```python
def removeLeafNodes(root, target):
    if not root:
        return None
    root.left = removeLeafNodes(root.left, target)
    root.right = removeLeafNodes(root.right, target)
    if not root.left and not root.right and root.val == target:
        return None
    return root
```

startTime = \[1,2,3\], endTime = \[3,2,7\], queryTime = 4

```cpp
TreeNode* removeLeafNodes(TreeNode* root, int target) {
    if (!root) return nullptr;
    root->left = removeLeafNodes(root->left, target);
    root->right = removeLeafNodes(root->right, target);
    if (!root->left && !root->right && root->val == target) {
        return nullptr;
    }
    return root;
}
```


```java
import java.util.List;

public int numPoints(List<List<Integer>> darts, int r) {
    int n = darts.size();
    int result = 1;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            int cnt = 0;
            for (int k = 0; k < n; ++k) {
                int dx = darts.get(i).get(0) - darts.get(k).get(0);
                int dy = darts.get(i).get(1) - darts.get(k).get(1);
                if (Math.sqrt(dx * dx + dy * dy) <= r) cnt++;
            }

            if (cnt > result) result = cnt;
        }
    }
    return result;
}
```

```cpp
#include <vector>
#include <cmath>

int numPoints(std::vector<std::vector<int>>& darts, int r) {
    int n = darts.size();
    int result = 1;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            int cnt = 0;
            for (int k = 0; k < n; ++k) {
                int dx = darts[i][0] - darts[k][0];
                int dy = darts[i][1] - darts[k][1];
                if (sqrt(dx * dx + dy * dy) <= r) cnt++;
            }

            if (cnt > result) result = cnt;
        }
    }
    return result;
}
```


```python
def countOrders(n: int) -> int:
    MOD = 10**9 + 7
    ans = 1
    for i in range(1, n + 1):
        ans = ans * (2 * i - 1) * i % MOD
    return ans
```

```cpp
int countOrders(int n) {
    long long MOD = 1e9 + 7;
    long long ans = 1;
    for (int i = 1; i <= n; ++i) {
        ans = ans * (2 * i - 1) * i % MOD;
    }
    return ans;
}
```


```python
def checkIfPrerequisite(numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
    adj_matrix = [[False] * numCourses for _ in range(numCourses)]
    for pre in prerequisites:
        adj_matrix[pre[0]][pre[1]] = True

    for k in range(numCourses):
        for i in range(numCourses):
            for j in range(numCourses):
                adj_matrix[i][j] = adj_matrix[i][j] or (adj_matrix[i][k] and adj_matrix[k][j])

    return [adj_matrix[query[0]][query[1]] for query in queries]
```

[false]
[false, false, false, true]
[false]
[false]
[false]
[false]
[false]
[true]
[false]
[false]
[false]
[false]
[false]
[false]
[false, true, false, false]
[false]
[false]
[false]
[false]
[false, true, false, true]
[false]
[false]
[false, true, false, false]
[false]
[false, true]
[false]
[false]
[false]
[false, true]
[false]
[false]
[false]
[false, false]
[false]
[false]
[]
[true, true]
[false]
[false]
[false]
[true, true]
[false]
[false]
[true]
[false]
[false]
[false]
[false]
[false]
[false, true, false, true]

```java
import java.util.List;
import java.util.ArrayList;

public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
    boolean[][] adj_matrix = new boolean[numCourses][numCourses];
    for (int[] pre : prerequisites) {
        adj_matrix[pre[0]][pre[1]] = true;
    }

    for (int k = 0; k < numCourses; k++) {
        for (int i = 0; i < numCourses; i++) {
            for (int j = 0; j < numCourses; j++) {
                adj_matrix[i][j] = adj_matrix[i][j] || (adj_matrix[i][k] && adj_matrix[k][j]);
            }
        }
    }

    List<Boolean> answer = new ArrayList<>();
    for (int[] query : queries) {
        answer.add(adj_matrix[query[0]][query[1]]);
    }
    return answer;
}
```


```java
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collections;

public int minSetSize(int[] arr) {
    HashMap<Integer, Integer> count = new HashMap<>();
    for (int value : arr)
        count.put(value, count.getOrDefault(value, 0) + 1);

    ArrayList<Integer> freq = new ArrayList<>(count.values());
    Collections.sort(freq, Collections.reverseOrder());

    int removed = 0, setSize = 0;
    for (int f : freq) {
        removed += f;
        setSize++;
        if (removed * 2 >= arr.length)
            return setSize;
    }

    return 0;
}
```

```python
from collections import Counter

def minSetSize(arr):
    count = Counter(arr)
    freq = list(count.values())
    freq.sort(reverse=True)

    removed, setSize = 0, 0
    for f in freq:
        removed += f
        setSize += 1
        if removed * 2 >= len(arr):
            return setSize

    return 0
```


```python
from math import factorial

def count_combinations(balls, combinations, curr_ball):
    total_combinations = 1
    for i in range(curr_ball):
        total_combinations *= factorial(balls[i] + combinations[i]) / (factorial(balls[i]) * factorial(combinations[i]))

    return total_combinations

def dfs(balls, combinations, curr_ball):
    if curr_ball == len(balls):
        if combinations[-1] == combinations[0]:
            return count_combinations(balls, combinations, curr_ball)
        else:
            return 0

    result = 0
    for i in range(balls[curr_ball] + 1):
        combinations.append(i)
        result += dfs(balls, combinations, curr_ball + 1)
        combinations.pop()

    return result

def get_probability(balls):
    sum_balls = sum(balls)

    total_combinations = 1
    for ball in balls:
        total_combinations *= factorial(ball)

    combinations = []
    return dfs(balls, combinations, 0) / total_combinations
```

```java
import java.util.ArrayList;
import java.util.List;

public double factorial(int num) {
    double result = 1;
    for (int i = 1; i <= num; i++)
        result *= i;
    return result;
}

public double countCombinations(int[] balls, List<Integer> combinations, int currBall) {
    double totalCombinations = 1;
    for (int i = 0; i < currBall; i++)
        totalCombinations *= factorial(balls[i] + combinations.get(i)) / (factorial(balls[i]) * factorial(combinations.get(i)));

    return totalCombinations;
}

public double dfs(int[] balls, List<Integer> combinations, int currBall) {
    if (currBall == balls.length) {
        if (combinations.get(combinations.size() - 1).equals(combinations.get(0)))
            return countCombinations(balls, combinations, currBall);
        else
            return 0;
    }

    double result = 0;
    for (int i = 0; i <= balls[currBall]; i++) {
        combinations.add(i);
        result += dfs(balls, combinations, currBall + 1);
        combinations.remove(combinations.size() - 1);
    }

    return result;
}

public double getProbability(int[] balls) {
    int sumBalls = 0;
    for (int ball : balls)
        sumBalls += ball;

    double totalCombinations = 1;
    for (int ball : balls)
        totalCombinations *= factorial(ball);

    List<Integer> combinations = new ArrayList<>();
    return dfs(balls, combinations, 0) / totalCombinations;
}
```


```cpp
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int maxSumBST(TreeNode* root) {
    int max_sum = 0;
    helper(root, max_sum);
    return max_sum;
}

tuple<int, int, int, bool> helper(TreeNode* node, int& max_sum) {
    if (node == nullptr) {
        return {INT_MAX, INT_MIN, 0, true};
    }

    auto[left_min, left_max, left_sum, is_left_bst] = helper(node->left, max_sum);
    auto[right_min, right_max, right_sum, is_right_bst] = helper(node->right, max_sum);

    if (is_left_bst && is_right_bst && node->val > left_max && node->val < right_min) {
        int sum = node->val + left_sum + right_sum;
        max_sum = max(max_sum, sum);
        return {min(node->val, left_min), max(node->val, right_max), sum, true};
    }

    return {0, 0, 0, false};
}
```

```java
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public int maxSumBST(TreeNode root) {
    int[] maxSum = new int[1];
    helper(root, maxSum);
    return maxSum[0];
}

private int[] helper(TreeNode node, int[] maxSum) {
    if (node == null) {
        return new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE, 0, 1};
    }

    int[] left = helper(node.left, maxSum);
    int[] right = helper(node.right, maxSum);

    if (left[3] != 0 && right[3] != 0 && node.val > left[1] && node.val < right[0]) {
        int sum = node.val + left[2] + right[2];
        maxSum[0] = Math.max(maxSum[0], sum);
        return new int[]{Math.min(node.val, left[0]), Math.max(node.val, right[1]), sum, 1};
    }

    return new int[]{0, 0, 0, 0};
}
```


```java
import java.util.Arrays;

public int maxEvents(int[][] events) {
    Arrays.sort(events, (a, b) -> a[1] - b[1]);

    int count = 0;
    int lastDay = -1;

    for (int[] event : events) {
        if (event[0] > lastDay) {
            count++;
            lastDay = event[1];
        }
    }

    return count;
}
```

```cpp
#include <vector>
#include <algorithm>

int maxEvents(std::vector<std::vector<int>>& events) {
    std::sort(events.begin(), events.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
        return a[1] < b[1];
    });

    int count = 0;
    int lastDay = -1;

    for (const auto& event : events) {
        if (event[0] > lastDay) {
            ++count;
            lastDay = event[1];
        }
    }

    return count;
}
```


```cpp
#include <unordered_map>
#include <queue>
int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
    unordered_map<int, int> count;
    for (int n : arr) {
        count[n]++;
    }
    priority_queue<int, vector<int>, greater<int>> pq;
    for (auto &p : count) {
        pq.push(p.second);
    }
    while (k > 0) {
        k -= pq.top();
        pq.pop();
    }
    return k == 0 ? pq.size() : pq.size() + 1;
}
```

```python
from collections import Counter
import heapq

def findLeastNumOfUniqueInts(arr, k):
    count = Counter(arr)
    pq = list(count.values())
    heapq.heapify(pq)
    while k > 0:
        k -= heapq.heappop(pq)
    return len(pq) if k == 0 else len(pq) + 1
```


```python
def smallerNumbersThanCurrent(nums):
    result = [0] * len(nums)
    for i in range(len(nums)):
        for j in range(len(nums)):
            if nums[j] < nums[i]:
                result[i] += 1
    return result
```

```cpp
#include <vector>
using namespace std;

vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
    vector<int> result(nums.size(), 0);
    for (int i = 0; i < nums.size(); ++i) {
        for (int j = 0; j < nums.size(); ++j) {
            if (nums[j] < nums[i]) {
                ++result[i];
            }
        }
    }
    return result;
}
```


```python
def max_size_slices(slices):
    def max_sum(slices, start, end, n, memo):
        if n == 0:
            return 0
        if end - start + 1 < n * 2:
            return float('-inf')
        if memo[start][n] != -1:
            return memo[start][n]

        pick = max_sum(slices, start + 2, end, n - 1, memo) + slices[start]
        not_pick = max_sum(slices, start + 1, end, n, memo)

        memo[start][n] = max(pick, not_pick)
        return memo[start][n]

    n = len(slices) // 3
    memo1 = [[-1] * (n + 1) for _ in range(len(slices))]
    memo2 = [[-1] * (n + 1) for _ in range(len(slices))]

    return max(max_sum(slices, 0, len(slices) - 1, n, memo1),
               max_sum(slices, 1, len(slices), n, memo2))
```

```cpp
#include <vector>
#include <algorithm>
using namespace std;

int maxSum(vector<int>& slices, int start, int end, int n, vector<vector<int>>& memo) {
    if (n == 0) return 0;
    if (end - start + 1 < n * 2) return INT_MIN;
    if (memo[start][n] != -1) return memo[start][n];

    int pick = maxSum(slices, start + 2, end, n - 1, memo) + slices[start];
    int notPick = maxSum(slices, start + 1, end, n, memo);

    memo[start][n] = max(pick, notPick);
    return memo[start][n];
}

int maxSizeSlices(vector<int>& slices) {
    int n = slices.size() / 3;
    vector<vector<int>> memo1(slices.size(), vector<int>(n + 1, -1));
    vector<vector<int>> memo2(slices.size(), vector<int>(n + 1, -1));

    return max(maxSum(slices, 0, slices.size() - 1, n, memo1),
               maxSum(slices, 1, slices.size(), n, memo2));
}
```


```cpp
int countPrefixAligned(const vector<int>& flips) {
    int count = 0;
    for (int i = 0; i < flips.size(); i++) {
        if (flips[i] == i + 1) {
            count++;
        }
    }
    return count;
}
```

```python
def count_prefix_aligned(flips):
    count = 0
    for i in range(len(flips)):
        if flips[i] == i + 1:
            count += 1
    return count
```


```cpp
int numSubmat(vector<vector<int>>& mat) {
    int m = mat.size(), n = mat[0].size();
    vector<vector<int>> dp(m, vector<int>(n));
    int ans = 0;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (mat[i][j]) {
                dp[i][j] = j == 0 ? 1 : dp[i][j-1] + 1;
                int width = dp[i][j];
                for (int k = i; k >= 0; k--) {
                    width = min(width, dp[k][j]);
                    ans += width;
                }
            }
        }
    }
    return ans;
}
```

```java
public int numSubmat(int[][] mat) {
    int m = mat.length, n = mat[0].length;
    int[][] dp = new int[m][n];
    int ans = 0;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (mat[i][j] == 1) {
                dp[i][j] = j == 0 ? 1 : dp[i][j-1] + 1;
                int width = dp[i][j];
                for (int k = i; k >= 0; k--) {
                    width = Math.min(width, dp[k][j]);
                    ans += width;
                }
            }
        }
    }
    return ans;
}
```


```python
def numWaterBottles(numBottles: int, numExchange: int) -> int:
    totalBottles = numBottles
    while numBottles >= numExchange:
        newBottles = numBottles // numExchange
        totalBottles += newBottles
        numBottles = newBottles + numBottles % numExchange
    return totalBottles
```

```cpp
int numWaterBottles(int numBottles, int numExchange) {
    int totalBottles = numBottles;
    while (numBottles >= numExchange) {
        int newBottles = numBottles / numExchange;
        totalBottles += newBottles;
        numBottles = newBottles + numBottles % numExchange;
    }
    return totalBottles;
}
```


```java
import java.util.*;

class Solution {
    public List<Integer> minSubsequence(int[] nums) {
        List<Integer> result = new ArrayList<Integer>();
        Arrays.sort(nums);
        int totalSum = 0, currentSum = 0;
        for (int num : nums) {
            totalSum += num;
        }
        for (int i = nums.length - 1; i >= 0; i--) {
            currentSum += nums[i];
            result.add(nums[i]);
            if (currentSum > totalSum - currentSum) {
                break;
            }
        }
        return result;
    }
}
```

```cpp
#include <vector>
#include <algorithm>

std::vector<int> minSubsequence(std::vector<int>& nums) {
    std::sort(nums.begin(), nums.end(), std::greater<int>());
    int totalSum = 0, currentSum = 0;
    for (int num : nums) {
        totalSum += num;
    }
    std::vector<int> result;
    for (int num : nums) {
        currentSum += num;
        result.push_back(num);
        if (currentSum > totalSum - currentSum) {
            break;
        }
    }
    return result;
}
```


```python
def num_steps(s: str) -> int:
    steps = 0
    carry = 0

    for i in range(len(s) - 1, 0, -1):
        current = int(s[i]) + carry
        if current == 1:
            steps += 2
            carry = 1
        else:
            steps += carry
            carry = current

    return steps + carry
```

abcabccba cccc abcccbcccb cc aabcabcc abbaccd aabcabc abc aabc abc aaabbc c abca aaccccc abcabc a c abcccb abcabcabc abcccca abccc adefaddaccc ab abccabac abcccbccca b abccabcc abcabcabcabc abacaba ab c b ccccc aacb a adefaddaccc abccba abcc abccca

```java
public int numSteps(String s) {
    int steps = 0, carry = 0;
    for (int i = s.length() - 1; i > 0; --i) {
        int current = s.charAt(i) - '0' + carry;
        if (current == 1) {
            steps += 2;
            carry = 1;
        } else {
            steps += carry;
            carry = current;
        }
    }

    return steps + carry;
}
```


```cpp
int closestToTarget(vector<int>& arr, int target) {
    int min_diff = INT_MAX;
    unordered_set<int> prefix;

    for (int n : arr) {
        unordered_set<int> next_prefix;
        for (int p : prefix) {
            next_prefix.insert(p & n);
        }
        next_prefix.insert(n);

        for (int p : next_prefix) {
            min_diff = min(min_diff, abs(p - target));
        }
        swap(prefix, next_prefix);
    }
    return min_diff;
}
```

```java
public int closestToTarget(int[] arr, int target) {
    int minDiff = Integer.MAX_VALUE;
    Set<Integer> prefix = new HashSet<>();

    for (int n : arr) {
        Set<Integer> nextPrefix = new HashSet<>();
        for (int p : prefix) {
            nextPrefix.add(p & n);
        }
        nextPrefix.add(n);

        for (int p : nextPrefix) {
            minDiff = Math.min(minDiff, Math.abs(p - target));
        }
        prefix = nextPrefix;
    }
    return minDiff;
}
```


```java
public int countOdds(int low, int high) {
    return (high - low) / 2 + ((low % 2 == 1 || high % 2 == 1) ? 1 : 0);
}
```

```cpp
int count_odds(int low, int high) {
    return (high - low) / 2 + ((low % 2 == 1 || high % 2 == 1) ? 1 : 0);
}
```


```java
public int minSwaps(int[][] grid) {
    int n = grid.length;
    int steps = 0;

    for (int i = 0; i < n; ++i) {
        int row = -1;
        for (int j = i; j < n; ++j) {
            if (grid[j][i] == 0) {
                row = j;
                break;
            }
        }
        if (row == -1) {
            return -1;
        }

        while (row > i) {
            int[] temp = grid[row];
            grid[row] = grid[row - 1];
            grid[row - 1] = temp;
            steps++;
            row--;
        }
    }
    return steps;
}
```

```cpp
int minSwaps(vector<vector<int>>& grid) {
    int n = grid.size();
    int steps = 0;

    for (int i = 0; i < n; ++i) {
        int row = -1;
        for (int j = i; j < n; ++j) {
            if (grid[j][i] == 0) {
                row = j;
                break;
            }
        }
        if (row == -1) {
            return -1;
        }

        while (row > i) {
            swap(grid[row], grid[row - 1]);
            steps++;
            row--;
        }
    }
    return steps;
}
```


```java
public boolean canConvertString(String s, String t, int k) {
    if (s.length() != t.length()) return false;
    int[] count = new int[26];
    for (int i = 0; i < s.length(); i++) {
        int diff = (t.charAt(i) - s.charAt(i) + 26) % 26;
        if (diff > 0) {
            count[diff]++;
        }
    }
    for (int i = 1; i < 26; i++) {
        if (count[i] > 0) {
            if (count[i] * 26 - 26 + i > k) {
                return false;
            }
        }
    }
    return true;
}
```

False False False False True False False False False True False False False True False False False True False False False True False False False False False True False False False False True True False False False False False False

```python
def canConvertString(s: str, t: str, k: int) -> bool:
    if len(s) != len(t):
        return False
    count = [0] * 26
    for i in range(len(s)):
        diff = (ord(t[i]) - ord(s[i]) + 26) % 26
        if diff > 0:
            count[diff] += 1
    for i in range(1, 26):
        if count[i] > 0:
            if count[i] * 26 - 26 + i > k:
                return False
    return True
```


```cpp
int maxPower(const std::string& s) {
    int maxPower = 0, currentPower = 1;

    for (int i = 1; i < s.length(); ++i) {
        if (s[i] == s[i-1]) {
            currentPower++;
        } else {
            maxPower = std::max(maxPower, currentPower);
            currentPower = 1;
        }
    }

    return std::max(maxPower, currentPower);
}
```

```python
def max_power(s: str) -> int:
    max_power = current_power = 1

    for i in range(1, len(s)):
        if s[i] == s[i-1]:
            current_power += 1
        else:
            max_power = max(max_power, current_power)
            current_power = 1

    return max(max_power, current_power)
```


```java
public String largestNumber(int[] cost, int target) {
    String[] dp = new String[target + 1];
    dp[0] = "";

    for (int t = 1; t <= target; ++t) {
        for (int i = 1; i <= 9; ++i) {
            if (t >= cost[i - 1] && dp[t - cost[i - 1]] != null) {
                String temp = dp[t - cost[i - 1]] + Integer.toString(i);
                if (dp[t] == null || dp[t].length() <= temp.length()) {
                    dp[t] = temp;
                }
            }
        }
    }

    return dp[target] == null ? "0" : dp[target];
}
```

```cpp
#include <vector>
#include <string>

std::string largestNumber(std::vector<int>& cost, int target) {
    std::vector<std::string> dp(target + 1, "");
    dp[0] = "";

    for (int t = 1; t <= target; ++t) {
        for (int i = 1; i <= 9; ++i) {
            if (t >= cost[i - 1]) {
                std::string temp = dp[t - cost[i - 1]] + char('0' + i);
                if (dp[t].length() <= temp.length()) {
                    dp[t] = temp;
                }
            }
        }
    }

    return dp[target].empty() ? "0" : dp[target];
}
```


```python
def maxNonOverlapping(nums, target):
    prefix_sum = {0: 0}
    sum, count = 0, 0
    for num in nums:
        sum += num
        if sum - target in prefix_sum:
            count = max(count, 1 + prefix_sum[sum - target])
        prefix_sum[sum] = count
    return count
```

```java
public int maxNonOverlapping(int[] nums, int target) {
    Map<Integer, Integer> prefixSum = new HashMap<>();
    int sum = 0, count = 0;
    prefixSum.put(0, 0);
    for (int num : nums) {
        sum += num;
        if (prefixSum.containsKey(sum - target)) {
            count = Math.max(count, 1 + prefixSum.get(sum - target));
        }
        prefixSum.put(sum, count);
    }
    return count;
}
```


```java
public boolean kLengthApart(int[] nums, int k) {
    int last_one = -1;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 1) {
            if (last_one != -1 && i - last_one <= k) {
                return false;
            }
            last_one = i;
        }
    }
    return true;
}
```

true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true
true

```cpp
bool kLengthApart(vector<int>& nums, int k) {
    int last_one = -1;
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] == 1) {
            if (last_one != -1 && i - last_one <= k) {
                return false;
            }
            last_one = i;
        }
    }
    return true;
}
```


```java
public int minOperations(int n) {
    return n * n / 4;
}
```

```python
def min_operations(n):
    return n * n // 4
```


```python
def build_array(target, n):
    result = []
    current = 1
    for num in target:
        while current < num:
            result.append("Push")
            result.append("Pop")
            current += 1
        result.append("Push")
        current += 1
    return result
```

Push Push Push Push Push Push Push Push Push

Push Push Push Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push

Push Push Push Push Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push

Push Pop Push Pop Push Pop Push Pop Push Push Pop Push Pop Push Pop Push Pop Push Push Pop Push Pop Push Pop Push Pop Push Push Pop Push Pop Push Pop Push Pop Push Push Pop Push Pop Push Pop Push Pop Push Push Pop Push Pop Push Pop Push Pop Push

Push Push Push Push Pop Push Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push

Push Push Pop Push Push Pop Push Push Pop Push Push Pop Push Push Pop Push Push Pop Push

Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push Pop Push

```cpp
#include <vector>
#include <string>

std::vector<std::string> buildArray(std::vector<int>& target, int n) {
    std::vector<std::string> result;
    int current = 1;
    for (int num : target) {
        while (current < num) {
            result.push_back("Push");
            result.push_back("Pop");
            current++;
        }
        result.push_back("Push");
        current++;
    }
    return result;
}
```


```cpp
int maxBoxesInWarehouse(vector<int>& boxes, vector<int>& warehouse) {
    int n = warehouse.size();
    for (int i = 1; i < n; i++)
        warehouse[i] = min(warehouse[i], warehouse[i - 1]);
    sort(boxes.rbegin(), boxes.rend());
    int boxIndex = 0;
    int boxesCount = 0;
    for (int i = 0; i < n && boxIndex < boxes.size(); i++) {
        if (boxes[boxIndex] <= warehouse[i]) {
            boxesCount++;
            boxIndex++;
        }
    }
    return boxesCount;
}
```

```java
public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) {
    int n = warehouse.length;
    for (int i = 1; i < n; i++)
        warehouse[i] = Math.min(warehouse[i], warehouse[i - 1]);
    Arrays.sort(boxes);
    int boxIndex = boxes.length - 1;
    int boxesCount = 0;
    for (int i = 0; i < n && boxIndex >= 0; i++) {
        if (boxes[boxIndex] <= warehouse[i]) {
            boxesCount++;
            boxIndex--;
        }
    }
    return boxesCount;
}
```


```python
def findLengthOfShortestSubarray(arr):
    n = len(arr)
    left, right = 0, n - 1
    while left < n - 1 and arr[left] <= arr[left + 1]:
        left += 1
    if left == n - 1:
        return 0
    while right > 0 and arr[right] >= arr[right - 1]:
        right -= 1
    result = min(n - left - 1, right)
    i, j = 0, right
    while i <= left and j < n:
        if arr[i] <= arr[j]:
            result = min(result, j - i - 1)
            i += 1
        else:
            j += 1
    return result
```

```cpp
int findLengthOfShortestSubarray(vector<int>& arr) {
    int n = arr.size(), left = 0, right = n - 1;
    while (left < n - 1 && arr[left] <= arr[left + 1]) left++;
    if (left == n - 1) return 0;
    while (right > 0 && arr[right] >= arr[right - 1]) right--;
    int result = min(n - left - 1, right);
    for (int i = 0, j = right; i <= left && j < n;) {
        if (arr[i] <= arr[j]) {
            result = min(result, j - i - 1);
            i++;
        } else {
            j++;
        }
    }
    return result;
}
```


```java
public int minTime(String colors, int[] neededTime) {
    int res = 0, prev = -1;
    for (int i = 0; i < colors.length() - 1; i++) {
        if (colors.charAt(i) == colors.charAt(i + 1)) {
            if (prev == -1 || neededTime[i] < neededTime[prev]) prev = i;
            if (neededTime[i + 1] < neededTime[prev]) prev = i + 1;
            res += neededTime[prev];
            neededTime[prev] = 1000000;
            prev = -1;
        }
    }
    return res;
}
```

colors =  "abaac ", neededTime = \[1,2,3,4,5\]

```python
def minTime(colors: str, neededTime: List[int]) -> int:
    res, prev = 0, -1
    for i in range(len(colors) - 1):
        if colors[i] == colors[i + 1]:
            if prev == -1 or neededTime[i] < neededTime[prev]:
                prev = i
            if neededTime[i + 1] < neededTime[prev]:
                prev = i + 1
            res += neededTime[prev]
            neededTime[prev] = 1000000
            prev = -1
    return res
```


```java
public int sumOddLengthSubarrays(int[] arr) {
    int sum = 0, n = arr.length;
    for (int i = 0; i < n; i++) {
        int oddSubarrays = ((i + 1) * (n - i) + 1) / 2;
        sum += arr[i] * oddSubarrays;
    }
    return sum;
}
```

```python
def sumOddLengthSubarrays(arr):
    sum = 0
    n = len(arr)
    for i in range(n):
        oddSubarrays = ((i + 1) * (n - i) + 1) // 2
        sum += arr[i] * oddSubarrays
    return sum
```


```python
def maxSumRangeQuery(nums, requests):
    n = len(nums)
    count = [0] * n
    for request in requests:
        count[request[0]] += 1
        if request[1] + 1 < n:
            count[request[1] + 1] -= 1
    for i in range(1, n):
        count[i] += count[i - 1]

    nums.sort()
    count.sort()

    ans = 0
    for i in range(n):
        ans = (ans + nums[i] * count[i]) % 1000000007
    return ans
```

```cpp
#include <algorithm>
#include <vector>
using namespace std;

const int MOD = 1000000007;

int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) {
    int n = nums.size();
    vector<int> count(n, 0);
    for (auto& request : requests) {
        count[request[0]]++;
        if (request[1] + 1 < n)
            count[request[1] + 1]--;
    }
    for (int i = 1; i < n; i++) {
        count[i] += count[i - 1];
    }
    sort(nums.begin(), nums.end());
    sort(count.begin(), count.end());

    long long ans = 0;
    for (int i = 0; i < n; i++) {
        ans = (ans + (long long)nums[i] * count[i]) % MOD;
    }
    return ans;
}
```


```python
def minSubarray(nums, p):
    n, res, need, cur = len(nums), len(nums), 0, 0
    for num in nums:
        need = (need + num) % p
    if need == 0:
        return 0
    last_seen = {0: -1}
    for i, num in enumerate(nums):
        cur = (cur + num) % p
        last_seen[cur] = i
        res = min(res, i - last_seen.get((cur - need + p) % p, -n))
    return res if res < n else -1
```

```java
import java.util.HashMap;

public int minSubarray(int[] nums, int p) {
    int n = nums.length, res = n, need = 0, cur = 0;
    for (int num : nums)
        need = (need + num) % p;
    if (need == 0) return 0;
    HashMap<Integer, Integer> last_seen = new HashMap<>();
    last_seen.put(0, -1);
    for (int i = 0; i < n; i++) {
        cur = (cur + nums[i]) % p;
        last_seen.put(cur, i);
        res = Math.min(res, i - last_seen.getOrDefault((cur - need + p) % p, -n));
    }
    return res < n ? res : -1;
}
```


```cpp
bool isPrintable(vector<vector<int>>& targetGrid) {
    unordered_map<int, vector<int>> color_bounds;
    int m = targetGrid.size(), n = targetGrid[0].size();
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            int color = targetGrid[i][j];
            if (!color_bounds.count(color)) color_bounds[color] = {i, j, i, j};
            else {
                color_bounds[color][0] = min(color_bounds[color][0], i);
                color_bounds[color][1] = min(color_bounds[color][1], j);
                color_bounds[color][2] = max(color_bounds[color][2], i);
                color_bounds[color][3] = max(color_bounds[color][3], j);
            }
        }
    }

    set<int> remaining_colors;
    for (const auto& p : color_bounds) {
        remaining_colors.insert(p.first);
    }
    while (!remaining_colors.empty()) {
        bool progress = false;
        for (auto it = remaining_colors.begin(); it != remaining_colors.end();) {
            int color = *it;
            const auto& bounds = color_bounds[color];
            bool contained = true;
            for (int i = bounds[0]; i <= bounds[2] && contained; ++i) {
                for (int j = bounds[1]; j <= bounds[3]; ++j) {
                    if (targetGrid[i][j] != color && targetGrid[i][j] != -1) {
                        contained = false;
                        break;
                    }
                }
            }
            if (contained) {
                for (int i = bounds[0]; i <= bounds[2]; ++i) {
                    for (int j = bounds[1]; j <= bounds[3]; ++j) {
                        targetGrid[i][j] = -1;
                    }
                }
                it = remaining_colors.erase(it);
                progress = true;
            } else {
                ++it;
            }
        }
        if (!progress) return false;
    }
    return true;
}
```

True False True False True True True True True True True True True True True False True True True True True True True False True False True False True True True True True True True True False

```python
def isPrintable(self, targetGrid: List[List[int]]) -> bool:
    color_bounds = {}
    m, n = len(targetGrid), len(targetGrid[0])

    for i in range(m):
        for j in range(n):
            color = targetGrid[i][j]
            if color not in color_bounds:
                color_bounds[color] = [i, j, i, j]
            else:
                color_bounds[color][0] = min(color_bounds[color][0], i)
                color_bounds[color][1] = min(color_bounds[color][1], j)
                color_bounds[color][2] = max(color_bounds[color][2], i)
                color_bounds[color][3] = max(color_bounds[color][3], j)

    remaining_colors = set(color_bounds.keys())
    while remaining_colors:
        progress = False
        to_remove = set()
        for color in remaining_colors:
            bounds = color_bounds[color]
            contained = all(targetGrid[i][j] == color or targetGrid[i][j] == -1
                        for i in range(bounds[0], bounds[2] + 1)
                        for j in range(bounds[1], bounds[3] + 1))
            if contained:
                for i in range(bounds[0], bounds[2] + 1):
                    for j in range(bounds[1], bounds[3] + 1):
                        targetGrid[i][j] = -1
                to_remove.add(color)
                progress = True

        remaining_colors -= to_remove
        if not progress:
            return False

    return True
```


```python
def connectTwoGroups(cost):
    size1, size2 = len(cost), len(cost[0])
    min_cost = [float('inf')] * size2

    for i in range(size1):
        for j in range(size2):
            min_cost[j] = min(min_cost[j], cost[i][j])

    total_cost = 0
    for i in range(size1):
        total_cost += min(cost[i])

    for j in range(size2):
        total_cost += min_cost[j]

    return total_cost
```

```cpp
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int connectTwoGroups(vector<vector<int>>& cost) {
    int size1 = cost.size(), size2 = cost[0].size();
    vector<int> min_cost(size2, INT_MAX);

    for (int i = 0; i < size1; i++) {
        for (int j = 0; j < size2; j++) {
            min_cost[j] = min(min_cost[j], cost[i][j]);
        }
    }

    int total_cost = 0;
    for (int i = 0; i < size1; i++) {
        total_cost += *min_element(cost[i].begin(), cost[i].end());
    }

    for (int j = 0; j < size2; j++) {
        total_cost += min_cost[j];
    }

    return total_cost;
}
```


```java
class Solution {
    public TreeNode expTree(String s) {
        Stack<TreeNode> nodes = new Stack<>();
        Stack<Character> ops = new Stack<>();
        for (int i = 0; i < s.length(); ++i) {
            if (Character.isDigit(s.charAt(i))) {
                nodes.push(new TreeNode(s.charAt(i)));
            } else if (s.charAt(i) == '(') {
                ops.push(s.charAt(i));
            } else if (s.charAt(i) == ')') {
                while (ops.peek() != '(') {
                    process(nodes, ops);
                }
                ops.pop();
            } else {
                while (!ops.empty() && precedence(ops.peek(), s.charAt(i))) {
                    process(nodes, ops);
                }
                ops.push(s.charAt(i));
            }
        }
        while (!ops.empty()) {
            process(nodes, ops);
        }
        return nodes.peek();
    }

    private boolean precedence(char a, char b) {
        if (a == '(') return false;
        if (b == '(' || b == ')') return true;
        if ((a == '*' || a == '/') && (b == '+' || b == '-')) return true;
        return false;
    }

    private void process(Stack<TreeNode> nodes, Stack<Character> ops) {
        TreeNode right = nodes.pop();
        TreeNode left = nodes.pop();
        TreeNode oper = new TreeNode(ops.pop());
        oper.left = left;
        oper.right = right;
        nodes.push(oper);
    }
}
```

```python
class Solution:
    def expTree(self, s: str) -> 'Node':
        def precedence(a, b):
            if a == '(':
                return False
            if b == '(' or b == ')':
                return True
            if (a in {'*', '/'}) and (b in {'+', '-'}):
                return True
            return False

        def process(nodes, ops):
            right = nodes.pop()
            left = nodes.pop()
            oper = Node(ops.pop())
            oper.left = left
            oper.right = right
            nodes.append(oper)

        nodes = []
        ops = []
        for i in s:
            if i.isdigit():
                nodes.append(Node(i))
            elif i == '(':
                ops.append(i)
            elif i == ')':
                while ops[-1] != '(':
                    process(nodes, ops)
                ops.pop()
            else:
                while ops and precedence(ops[-1], i):
                    process(nodes, ops)
                ops.append(i)
        while ops:
            process(nodes, ops)
        return nodes[0]
```