```cpp
int helper(vector<vector<int>>& grid, vector<vector<vector<int>>>& memo, int r1, int c1, int r2) {
    int c2 = r1 + c1 - r2;
    if (r1 == grid.size() || r2 == grid.size() || c1 == grid.size() || c2 == grid.size() ||
        grid[r1][c1] == -1 || grid[r2][c2] == -1) {
        return INT_MIN;
    } else if (r1 == grid.size() - 1 && c1 == grid.size() - 1) {
        return grid[r1][c1];
    } else if (memo[r1][c1][r2] != INT_MIN) {
        return memo[r1][c1][r2];
    } else {
        memo[r1][c1][r2] = grid[r1][c1] + (r1 != r2 ? grid[r2][c2] : 0);
        int max_cherries = max(max(helper(grid, memo, r1 + 1, c1, r2 + 1), helper(grid, memo, r1, c1 + 1, r2 + 1)),
                               max(helper(grid, memo, r1 + 1, c1, r2), helper(grid, memo, r1, c1 + 1, r2)));
        memo[r1][c1][r2] += max_cherries;
    }
    return memo[r1][c1][r2];
}

int cherryPickup(vector<vector<int>>& grid) {
    int n = grid.size();
    vector<vector<vector<int>>> memo(n, vector<vector<int>>(n, vector<int>(n, INT_MIN)));
    return max(0, helper(grid, memo, 0, 0, 0));
}
```

```java
public int cherryPickup(int[][] grid) {
    int N = grid.length;
    int[][][] dp = new int[N][N][N];
    for (int[][] layer: dp)
        for (int[] row: layer)
            Arrays.fill(row, Integer.MIN_VALUE);

    return Math.max(0, dp(0, 0, 0, grid, dp));
}

public int dp(int r1, int c1, int c2, int[][] grid, int[][][] memo) {
    int r2 = r1 + c1 - c2;
    if (r1 == grid.length || r2 == grid.length || c1 == grid.length || c2 == grid.length ||
            grid[r1][c1] == -1 || grid[r2][c2] == -1) {
        return Integer.MIN_VALUE;
    } else if (r1 == grid.length - 1 && c1 == grid.length - 1) {
        return grid[r1][c1];
    } else if (memo[r1][c1][c2] != Integer.MIN_VALUE) {
        return memo[r1][c1][c2];
    } else {
        memo[r1][c1][c2] = grid[r1][c1] + (r1 != r2 ? grid[r2][c2] : 0);
        int tempMax = Math.max(Math.max(dp(r1+1, c1, c2+1, grid, memo), dp(r1, c1+1, c2+1, grid, memo)),
                        Math.max(dp(r1+1, c1, c2, grid, memo), dp(r1, c1+1, c2, grid, memo)));
        memo[r1][c1][c2] += tempMax;
    }
    return memo[r1][c1][c2];
}
```


```java
import java.util.*;

public int networkDelayTime(int[][] times, int n, int k) {
    Map<Integer, List<int[]>> graph = new HashMap<>();
    for (int[] edge : times) {
        graph.putIfAbsent(edge[0], new ArrayList<>());
        graph.get(edge[0]).add(new int[]{edge[1], edge[2]});
    }

    int[] dist = new int[n+1];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[k] = 0;

    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
    pq.offer(new int[]{k, 0});

    while (!pq.isEmpty()) {
        int[] curr = pq.poll();
        int u = curr[0], currDist = curr[1];

        List<int[]> neighbors = graph.get(u);
        if (neighbors == null) continue;

        for (int[] neighbor : neighbors) {
            int v = neighbor[0], weight = neighbor[1];
            if (currDist + weight < dist[v]) {
                dist[v] = currDist + weight;
                pq.offer(new int[]{v, dist[v]});
            }
        }
    }

    int maxTime = 0;
    for (int i = 1; i <= n; ++i) {
        if (dist[i] == Integer.MAX_VALUE) return -1;
        maxTime = Math.max(maxTime, dist[i]);
    }

    return maxTime;
}
```

```python
import heapq

def networkDelayTime(times, n, k):
    graph = {i: [] for i in range(1, n+1)}
    for u, v, w in times:
        graph[u].append((v, w))

    dist = {u: float('inf') for u in range(1, n+1)}
    dist[k] = 0

    pq = [(0, k)]

    while pq:
        curr_dist, u = heapq.heappop(pq)

        for v, weight in graph[u]:
            new_dist = curr_dist + weight
            if new_dist < dist[v]:
                dist[v] = new_dist
                heapq.heappush(pq, (new_dist, v))

    max_time = max(dist.values())
    return max_time if max_time < float('inf') else -1
```


```python
def minCostClimbingStairs(cost):
    for i in range(2, len(cost)):
        cost[i] += min(cost[i-1], cost[i-2])
    return min(cost[-1], cost[-2])
```

```cpp
int minCostClimbingStairs(vector<int>& cost) {
    int n = cost.size();
    for(int i=2; i<n; i++)
        cost[i] += min(cost[i-1], cost[i-2]);
    return min(cost[n-1], cost[n-2]);
}
```


```java
public int countCornerRectangles(int[][] grid) {
    int count = 0;
    int m = grid.length;
    int n = grid[0].length;

    for (int i = 0; i < m - 1; i++) {
        for (int j = 0; j < n - 1; j++) {
            if (grid[i][j] == 1) {
                for (int k = i + 1; k < m; k++) {
                    for (int l = j + 1; l < n; l++) {
                        if (grid[k][l] == 1 && grid[i][l] == 1 && grid[k][j] == 1) {
                            count++;
                        }
                    }
                }
            }
        }
    }
    return count;
}
```

```python
def countCornerRectangles(grid):
    count = 0
    m = len(grid)
    n = len(grid[0])

    for i in range(m - 1):
        for j in range(n - 1):
            if grid[i][j] == 1:
                for k in range(i + 1, m):
                    for l in range(j + 1, n):
                        if grid[k][l] == 1 and grid[i][l] == 1 and grid[k][j] == 1:
                            count += 1
    return count
```


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

int openLock(vector<string>& deadends, string target) {
    set<string> dead(deadends.begin(), deadends.end());
    set<string> visited;
    queue<string> q;
    string start = "0000";

    if (dead.find(start) != dead.end()) return -1;
    q.push(start);
    visited.insert(start);

    int moves = 0;
    while (!q.empty()) {
        int levelSize = q.size();
        for (int i = 0; i < levelSize; ++i) {
            string cur = q.front();
            q.pop();

            if (cur == target) return moves;

            for (int j = 0; j < 4; ++j) {
                for (int k = -1; k <= 1; k += 2) {
                    string next = cur;
                    next[j] = (next[j] - '0' + k + 10) % 10 + '0';

                    if (visited.find(next) == visited.end() && dead.find(next) == dead.end()) {
                        visited.insert(next);
                        q.push(next);
                    }
                }
            }
        }
        moves++;
    }

    return -1;
}
```

```python
from collections import deque

def openLock(deadends, target):
    dead = set(deadends)
    visited = set()
    q = deque(["0000"])

    if "0000" in dead:
        return -1

    visited.add("0000")
    moves = 0

    while q:
        level_size = len(q)
        for i in range(level_size):
            cur = q.popleft()

            if cur == target:
                return moves

            for j in range(4):
                for k in [-1, 1]:
                    next_val = cur[:j] + str((int(cur[j]) + k + 10) % 10) + cur[j + 1:]

                    if next_val not in visited and next_val not in dead:
                        visited.add(next_val)
                        q.append(next_val)

        moves += 1

    return -1
```


```cpp
int reachNumber(int target) {
    target = abs(target);
    int step = 0, sum = 0;
    while (sum < target) {
        step++;
        sum += step;
    }
    while ((sum - target) % 2 != 0) {
        step++;
        sum += step;
    }
    return step;
}
```

```python
def reachNumber(target: int) -> int:
    target = abs(target)
    step = 0
    sum = 0
    while sum < target:
        step += 1
        sum += step
    while (sum - target) % 2 != 0:
        step += 1
        sum += step
    return step
```


```python
def pyramid_transition(bottom, allowed):
    mapping = {}
    for s in allowed:
        key = s[:2]
        if key not in mapping:
            mapping[key] = []
        mapping[key].append(s[2])
    return pyramid_transition_helper(bottom, "", 0, mapping)

def pyramid_transition_helper(bottom, top, idx, mapping):
    if len(bottom) == 1:
        return True
    if idx == len(bottom) - 1:
        return pyramid_transition_helper(top, "", 0, mapping)
    key = bottom[idx:idx + 2]
    if key not in mapping:
        return False
    for c in mapping[key]:
        if pyramid_transition_helper(bottom, top + c, idx + 1, mapping):
            return True
    return False
```

bottom =  "BCD ", allowed = \[ "BCC ", "CDE ", "CEA ", "FFF "\]

AAAA
["AAB ", "AAC ", "BCD ", "BBE ", "DEF "]

false false false false false false false false false false false false false false false false false false false false false true false false false false false false false false false false false false false true false false false false false false

```java
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public boolean pyramidTransition(String bottom, List<String> allowed) {
    Map<String, List<Character>> mapping = new HashMap<>();
    for (String s : allowed) {
        mapping.computeIfAbsent(s.substring(0, 2), k -> new ArrayList<>()).add(s.charAt(2));
    }
    return pyramidTransitionHelper(bottom, "", 0, mapping);
}

private boolean pyramidTransitionHelper(String bottom, String top, int idx, Map<String, List<Character>> mapping) {
    if (bottom.length() == 1) return true;
    if (idx == bottom.length() - 1) return pyramidTransitionHelper(top, "", 0, mapping);
    String key = bottom.substring(idx, idx + 2);
    if (!mapping.containsKey(key)) return false;
    for (Character c : mapping.get(key)) {
        if (pyramidTransitionHelper(bottom, top + c, idx + 1, mapping)) return true;
    }
    return false;
}
```


```java
import java.util.List;

public String addBoldTag(List<String> words, String s) {
    boolean[] bold = new boolean[s.length()];
    for (String word : words) {
        int pos = s.indexOf(word);
        while (pos != -1) {
            for (int i = pos; i < pos + word.length(); i++) {
                bold[i] = true;
            }
            pos = s.indexOf(word, pos + 1);
        }
    }

    StringBuilder result = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        if (bold[i] && (i == 0 || !bold[i - 1])) result.append("<b>");
        result.append(s.charAt(i));
        if (bold[i] && (i == s.length() - 1 || !bold[i + 1])) result.append("</b>");
    }

    return result.toString();
}
```

words = \[ "ab ", "bc "\], s =  "aabcd "

ghijklmno
abcd
abcdefghijklmnopqrstuvwxyzabcd
qrstuvwxyzabcdefg
mnopqrstuvw
a
defghijklmn
abcdefghijklmnopqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
efghijklmnopqrstuvwxyzabcd
cdefghijkl
wxyzabcdefg
fghijklmnop
klmnopqrstuvwxyzabc
cdefghijk
pqrstuvwxyzabcdef
efghijklmn
ijklmnopqrs
abcdefghijklmnopqrstuvwxyzabcd
abcd
efghijklmno
abcdefghijklmnopqrstuvwxyzabcd
fghijklmnopqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
stuvwxyzabcdefg
abcdefghijklmnopqrstuvwxyzabcd
bcd efghij
abcabcd
abcdefghijklmnopqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
opqrstuvwx
lmnopqrstuvwxyzabcd
cdefghijklmnopqrstuvwxyzabcd
aabcd
abcdefghijklmnopqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
defghijkl
aabcd
tuvwxyzabc
abcdefghijklmnopqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
bcdefghijklmnopqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
uvwxyzabcd
opqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
mnopqrstu
abcde
nopqrstuvwxyzabcd
lmnopqrstuvw
abcdefghi
yzabcdefgh
abcdefghijklmnopqrstuvwxyzabcd
jklmnopqrstuvwxyzabcd
aaa
jklvwxyzabc
ghijklmnopqrstuvwxyzabcd
rstuvwxyza
abcdefghijklmnopqrstuvwxyzabcd
abcdefghijklmnopqrstuvwxyzabcd
ijklmnopqr
pqrstuvwxyz
defghijklmnopqrstuvwxyzabcd
aabbcc
abcdefghijklmnopqrstuvwxyzabcd
ijklmnopqrstuvwxyzabcd
stuvwxyzab
rstuvwxyzabcdef
mnopqrstuvwxyzabcd
pqrstuvwxyza
hijklmnopqrstuvwxyzabcd
tuvwxyzabcdef
a
abcdefghijklmnopqrstuvwxyzabcd

```python
def addBoldTag(words, s):
    bold = [False] * len(s)
    for word in words:
        pos = s.find(word)
        while pos != -1:
            for i in range(pos, pos + len(word)):
                bold[i] = True
            pos = s.find(word, pos + 1)

    result = []
    for i in range(len(s)):
        if bold[i] and (i == 0 or not bold[i - 1]):
            result.append("<b>")
        result.append(s[i])
        if bold[i] and (i == len(s) - 1 or not bold[i + 1]):
            result.append("</b>")

    return "".join(result)
```


```java
import java.util.*;

public int[] anagramMappings(int[] nums1, int[] nums2) {
    HashMap<Integer, Integer> num_map = new HashMap<>();
    for (int i = 0; i < nums2.length; i++) {
        num_map.put(nums2[i], i);
    }
    int[] mapping = new int[nums1.length];
    for (int i = 0; i < nums1.length; i++) {
        mapping[i] = num_map.get(nums1[i]);
    }
    return mapping;
}
```

```python
def anagramMappings(nums1, nums2):
    num_map = {num: i for i, num in enumerate(nums2)}
    mapping = [num_map[num] for num in nums1]
    return mapping
```


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

std::string makeLargestSpecial(std::string s) {
    int count = 0, i = 0;
    std::vector<std::string> subs;

    for (int j = 0; j < s.size(); j++) {
        if (s[j] == '1') count++;
        else count--;

        if (count == 0) {
            subs.push_back('1' + makeLargestSpecial(s.substr(i+1, j-i-1)) + '0');
            i = j + 1;
        }
    }

    std::sort(subs.rbegin(), subs.rend());
    std::string res;
    for (const auto& sub : subs) {
        res += sub;
    }
    return res;
}
```

```python
def makeLargestSpecial(s: str) -> str:
    count, i = 0, 0
    subs = []

    for j in range(len(s)):
        if s[j] == '1':
            count += 1
        else:
            count -= 1

        if count == 0:
            subs.append("1" + makeLargestSpecial(s[i+1:j]) + "0")
            i = j + 1

    subs.sort(reverse=True)
    return "".join(subs)
```


```java
class Solution {
    boolean isPrime(int n) {
        if (n <= 1) return false;
        if (n <= 3) return true;
        if (n % 2 == 0 || n % 3 == 0) return false;
        for (int i = 5; i * i <= n; i += 6)
            if (n % i == 0 || n % (i + 2) == 0) return false;
        return true;
    }

    public int countPrimeSetBits(int left, int right) {
        int count = 0;
        for (int i = left; i <= right; ++i)
            count += isPrime(Integer.bitCount(i)) ? 1 : 0;
        return count;
    }
}
```

```python
def is_prime(n: int) -> bool:
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

def count_prime_set_bits(left: int, right: int) -> int:
    return sum(is_prime(bin(i).count('1')) for i in range(left, right + 1))
```


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

std::vector<int> partitionLabels(std::string s) {
    std::unordered_map<char, int> last;
    for (int i = 0; i < s.size(); i++) {
        last[s[i]] = i;
    }
    std::vector<int> ans;
    int j = 0, anchor = 0;
    for (int i = 0; i < s.size(); i++) {
        j = std::max(j, last[s[i]]);
        if (i == j) {
            ans.push_back(i - anchor + 1);
            anchor = i + 1;
        }
    }
    return ans;
}
```

ababcbacadefegdehijhklij abcdefghijklmnopqrstuvwxyz ababcbacadefegdehijhklij ababcbacadefegdehijhklij aabbcc ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij aaabbbccc ababcbacadefegdehijhklij ababcbacadefegdehijhklij abcde ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij aaabaaa ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij z ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij aaaaa ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij ababcbacadefegdehijhklij

```python
def partition_labels(s):
    last = {c:i for i, c in enumerate(s)}
    ans = []
    j = anchor = 0
    for i, c in enumerate(s):
        j = max(j, last[c])
        if i == j:
            ans.append(i - anchor + 1)
            anchor = i + 1
    return ans
```


```python
def minSwapsCouples(row):
    n = len(row)
    position = [0] * n
    for i in range(n):
        position[row[i]] = i

    swaps = 0
    for i in range(0, n, 2):
        partner = row[i] + 1 if row[i] % 2 == 0 else row[i] - 1
        if row[i + 1] != partner:
            row[position[partner]], row[i + 1] = row[i + 1], row[position[partner]]
            position[row[i + 1]], position[partner] = position[partner], position[row[i + 1]]
            swaps += 1
    return swaps
```

```cpp
int minSwapsCouples(vector<int>& row) {
    int n = row.size();
    vector<int> position(n);
    for (int i = 0; i < n; ++i)
        position[row[i]] = i;

    int swaps = 0;
    for (int i = 0; i < n; i += 2) {
        int partner = row[i] % 2 == 0 ? row[i] + 1 : row[i] - 1;
        if (row[i + 1] != partner) {
            swap(row[position[partner]], row[i + 1]);
            swap(position[row[i + 1]], position[partner]);
            swaps++;
        }
    }
    return swaps;
}
```


```python
def orderOfLargestPlusSign(n, mines):
    grid = [[1] * n for _ in range(n)]
    for mine in mines:
        grid[mine[0]][mine[1]] = 0

    left, right, up, down = [list(grid) for _ in range(4)]

    for i in range(n):
        for j in range(n):
            if grid[i][j]:
                left[i][j] = 1 + (left[i][j - 1] if j > 0 else 0)
                up[i][j] = 1 + (up[i - 1][j] if i > 0 else 0)

    ans = 0
    for i in range(n - 1, -1, -1):
        for j in range(n - 1, -1, -1):
            if grid[i][j]:
                right[i][j] = 1 + (right[i][j + 1] if j < n - 1 else 0)
                down[i][j] = 1 + (down[i + 1][j] if i < n - 1 else 0)
                ans = max(ans, min([left[i][j], right[i][j], up[i][j], down[i][j]]))

    return ans
```

```cpp
int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {
    vector<vector<int>> grid(n, vector<int>(n, 1));
    for (const auto& mine : mines)
        grid[mine[0]][mine[1]] = 0;

    vector<vector<int>> left(grid), right(grid), up(grid), down(grid);
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (grid[i][j]) {
                left[i][j] = j > 0 ? left[i][j - 1] + 1 : 1;
                up[i][j] = i > 0 ? up[i - 1][j] + 1 : 1;
            }
            if (grid[n - i - 1][n - j - 1]) {
                right[n - i - 1][n - j - 1] = j > 0 ? right[n - i - 1][n - j] + 1 : 1;
                down[n - i - 1][n - j - 1] = i > 0 ? down[n - i][n - j - 1] + 1 : 1;
            }
        }
    }

    int ans = 0;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            ans = max(ans, min({left[i][j], right[i][j], up[i][j], down[i][j]}));
    return ans;
}
```


```python
def max_chunks_to_sorted(arr):
    max_val, chunks = 0, 0
    for i, value in enumerate(arr):
        max_val = max(max_val, value)
        if max_val == i:
            chunks += 1
    return chunks
```

```cpp
int maxChunksToSorted(vector<int>& arr) {
    int max_val = 0, chunks = 0;
    for (int i = 0; i < arr.size(); ++i) {
        max_val = max(max_val, arr[i]);
        if (max_val == i) {
            chunks++;
        }
    }
    return chunks;
}
```


```python
from collections import Counter

def numRabbits(answers):
    count = Counter(answers)
    rabbits = 0
    for ans, cnt in count.items():
        rabbits += (ans + cnt)//(ans + 1) * (ans + 1)
    return rabbits
```

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

int numRabbits(vector<int>& answers) {
    unordered_map<int, int> count;
    int rabbits = 0;
    for (int ans : answers) {
        count[ans]++;
    }
    for (auto& [ans, cnt] : count) {
        rabbits += (ans + cnt) / (ans + 1) * (ans + 1);
    }
    return rabbits;
}
```


```python
def isBipartite(graph: List[List[int]]) -> bool:
    def dfs(node: int, color: int) -> bool:
        if colors[node]:
            return colors[node] == color

        colors[node] = color
        for neighbor in graph[node]:
            if not dfs(neighbor, 3 - color):
                return False

        return True

    n = len(graph)
    colors = [0] * n

    for i in range(n):
        if not colors[i] and not dfs(i, 1):
            return False

    return True
```

false false false false false false false false true false false true false false false false true false true false false false false false false true

```java
import java.util.Arrays;

class Solution {
    public boolean isBipartite(int[][] graph) {
        int n = graph.length;
        int[] colors = new int[n];
        Arrays.fill(colors, 0);

        for (int i = 0; i < n; ++i) {
            if (colors[i] == 0 && !dfs(i, 1, colors, graph)) {
                return false;
            }
        }

        return true;
    }

    private boolean dfs(int node, int color, int[] colors, int[][] graph) {
        if (colors[node] != 0) {
            return colors[node] == color;
        }

        colors[node] = color;
        for (int neighbor : graph[node]) {
            if (!dfs(neighbor, 3 - color, colors, graph)) {
                return false;
            }
        }

        return true;
    }
}
```


```java
import java.util.HashMap;
public int numRabbits(int[] answers) {
    HashMap<Integer, Integer> count = new HashMap<>();
    int res = 0;
    for (int a : answers) {
        count.put(a, count.getOrDefault(a, 0) + 1);
        if (count.get(a) == 1) {
            res += (a + 1);
        } else if (count.get(a) > a + 1) {
            count.put(a, 1);
            res += (a + 1);
        }
    }
    return res;
}
```

```cpp
#include <unordered_map>
int numRabbits(vector<int>& answers) {
    unordered_map<int, int> count;
    int res = 0;
    for (int a : answers) {
        ++count[a];
        if (count[a] == 1) {
            res += (a + 1);
        } else if (count[a] > a + 1) {
            count[a] = 1;
            res += (a + 1);
        }
    }
    return res;
}
```


```cpp
bool isPossibleToSplit(const vector<int>& nums) {
    int n = nums.size();
    int total_sum = accumulate(nums.begin(), nums.end(), 0);

    if (total_sum % n != 0) return false;

    int target_sum = total_sum * (n / 2) / n;
    vector<vector<bool>> dp(n / 2 + 1, vector<bool>(target_sum + 1, false));
    dp[0][0] = true;

    for (int num : nums) {
        for (int count = n / 2; count >= 1; --count) {
            for (int sum = target_sum; sum >= num; --sum) {
                dp[count][sum] = dp[count][sum] || dp[count - 1][sum - num];
            }
        }
        if (dp[n / 2][target_sum]) return true;
    }

    return false;
}
```

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

```python
def isPossibleToSplit(nums):
    n = len(nums)
    total_sum = sum(nums)

    if total_sum % n != 0:
        return False

    target_sum = total_sum * (n // 2) // n
    dp = [[False] * (target_sum + 1) for _ in range(n // 2 + 1)]
    dp[0][0] = True

    for num in nums:
        for count in range(n // 2, 0, -1):
            for sum_ in range(target_sum, num - 1, -1):
                dp[count][sum_] = dp[count][sum_] or dp[count - 1][sum_ - num]

        if dp[n // 2][target_sum]:
            return True

    return False
```


```java
public int maxIncreaseKeepingSkyline(int[][] grid) {
    int n = grid.length;
    int[] row_max = new int[n];
    int[] col_max = new int[n];

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            row_max[i] = Math.max(row_max[i], grid[i][j]);
            col_max[j] = Math.max(col_max[j], grid[i][j]);
        }
    }

    int total_sum = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            total_sum += Math.min(row_max[i], col_max[j]) - grid[i][j];
        }
    }

    return total_sum;
}
```

```cpp
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
    int n = grid.size();
    vector<int> row_max(n, 0);
    vector<int> col_max(n, 0);

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            row_max[i] = max(row_max[i], grid[i][j]);
            col_max[j] = max(col_max[j], grid[i][j]);
        }
    }

    int total_sum = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            total_sum += min(row_max[i], col_max[j]) - grid[i][j];
        }
    }

    return total_sum;
}
```


```python
def maxProfitAssignment(difficulty, profit, worker):
    n = len(difficulty)
    jobs = sorted(zip(difficulty, profit))
    worker.sort()

    max_profit = 0
    total_profit = 0
    job_idx = 0

    for w in worker:
        while job_idx < n and w >= jobs[job_idx][0]:
            max_profit = max(max_profit, jobs[job_idx][1])
            job_idx += 1
        total_profit += max_profit

    return total_profit
```

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

int maxProfitAssignment(std::vector<int>& difficulty, std::vector<int>& profit, std::vector<int>& worker) {
    int n = difficulty.size();
    std::vector<std::pair<int, int>> jobs(n);

    for (int i = 0; i < n; ++i) {
        jobs[i] = {difficulty[i], profit[i]};
    }

    std::sort(jobs.begin(), jobs.end());
    std::sort(worker.begin(), worker.end());

    int max_profit = 0;
    int total_profit = 0;
    int job_idx = 0;

    for (int w : worker) {
        while (job_idx < n && w >= jobs[job_idx].first) {
            max_profit = std::max(max_profit, jobs[job_idx].second);
            job_idx++;
        }
        total_profit += max_profit;
    }

    return total_profit;
}
```


```java
public int maxAreaOfIsland(int[][] grid) {
    int ans = 0;
    for (int i = 0; i < grid.length; ++i)
        for (int j = 0; j < grid[i].length; ++j)
            if (grid[i][j] == 0) {
                grid[i][j] = 1;
                ans = Math.max(ans, dfs(grid, i, j));
                grid[i][j] = 0;
            }
    return ans;
}

private int dfs(int[][] grid, int x, int y) {
    if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == 0) {
        return 0;
    }
    grid[x][y] = 0;
    return dfs(grid, x - 1, y) + dfs(grid, x + 1, y) + dfs(grid, x, y - 1) + dfs(grid, x, y + 1) + 1;
}
```

```python
def maxAreaOfIsland(grid):
    def dfs(x, y):
        if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]) or grid[x][y] == 0:
            return 0
        grid[x][y] = 0
        return dfs(x - 1, y) + dfs(x + 1, y) + dfs(x, y - 1) + dfs(x, y + 1) + 1

    ans = 0
    for i, row in enumerate(grid):
        for j, cell in enumerate(row):
            if cell == 0:
                grid[i][j] = 1
                ans = max(ans, dfs(i, j))
                grid[i][j] = 0
    return ans
```


```python
def minimal_length_encoding(words):
    word_set = set(words)

    for word in words:
        for i in range(1, len(word)):
            word_set.discard(word[i:])

    return sum(len(word) + 1 for word in word_set)
```

strs = \[ "tars ", "rats ", "arts ", "star "\]

abcde bcdae cbade dceab edcba ebcda adebc

abcdef fabcde edcbaf bcafed fecbad edcbfa

```java
import java.util.HashSet;
import java.util.Set;

public int minimalLengthEncoding(String[] words) {
    Set<String> wordSet = new HashSet<>();
    for (String word : words) {
        wordSet.add(word);
    }

    for (String word : words) {
        for (int i = 1; i < word.length(); i++) {
            wordSet.remove(word.substring(i));
        }
    }

    int len = 0;
    for (String word : wordSet) {
        len += word.length() + 1;
    }
    return len;
}
```


```cpp
int numMagicSquaresInside(vector<vector<int>>& grid) {
    int count = 0;
    for (int i = 0; i < grid.size() - 2; ++i) {
        for (int j = 0; j < grid[0].size() - 2; ++j) {
            if (grid[i][j] <= 9 && grid[i + 1][j + 1] == 5 && isMagic(grid, i, j)) {
                count++;
            }
        }
    }
    return count;
}

bool isMagic(vector<vector<int>>& grid, int x, int y) {
    vector<int> temp(16, 0);
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            int num = grid[x + i][y + j];
            temp[num]++;
            if (num > 9 || temp[num] > 1) {
                return false;
            }
        }
    }
    int sum = grid[x][y] + grid[x][y+1] + grid[x][y+2];
    for (int i = 0; i < 3; ++i) {
        int rowSum = 0, colSum = 0;
        for (int j = 0; j < 3; ++j) {
            rowSum += grid[x + i][y + j];
            colSum += grid[x + j][y + i];
        }
        if (rowSum != sum || colSum != sum)
            return false;
    }
    if (grid[x][y] + grid[x + 1][y + 1] + grid[x + 2][y + 2] != sum)
        return false;
    if (grid[x][y + 2] + grid[x + 1][y + 1] + grid[x + 2][y] != sum)
        return false;

    return true;
}
```

```java
public int numMagicSquaresInside(int[][] grid) {
    int count = 0;
    for (int i = 0; i < grid.length - 2; ++i) {
        for (int j = 0; j < grid[0].length - 2; ++j) {
            if (grid[i][j] <= 9 && grid[i + 1][j + 1] == 5 && isMagic(grid, i, j)) {
                count++;
            }
        }
    }
    return count;
}

private boolean isMagic(int[][] grid, int x, int y) {
    int[] temp = new int[16];
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            int num = grid[x + i][y + j];
            temp[num]++;
            if (num > 9 || temp[num] > 1) {
                return false;
            }
        }
    }
    int sum = grid[x][y] + grid[x][y+1] + grid[x][y+2];
    for (int i = 0; i < 3; ++i) {
        int rowSum = 0, colSum = 0;
        for (int j = 0; j < 3; ++j) {
            rowSum += grid[x + i][y + j];
            colSum += grid[x + j][y + i];
        }
        if (rowSum != sum || colSum != sum)
            return false;
    }
    if (grid[x][y] + grid[x + 1][y + 1] + grid[x + 2][y + 2] != sum)
        return false;
    if (grid[x][y + 2] + grid[x + 1][y + 1] + grid[x + 2][y] != sum)
        return false;

    return true;
}
```


```cpp
int longestMountain(vector<int>& arr) {
    int n = arr.size(), res = 0, up = 0, down = 0;

    for (int i = 1; i < n; ++i) {
        if (down && arr[i - 1] < arr[i] || arr[i - 1] == arr[i]) {
            up = down = 0;
        }

        up += arr[i - 1] < arr[i];
        down += arr[i - 1] > arr[i];

        if (up && down) {
            res = max(res, up + down + 1);
        }
    }
    return res;
}
```

```python
def longestMountain(arr):
    n = len(arr)
    res = up = down = 0

    for i in range(1, n):
        if (down and arr[i - 1] < arr[i]) or arr[i - 1] == arr[i]:
            up = down = 0

        up += arr[i - 1] < arr[i]
        down += arr[i - 1] > arr[i]

        if up and down:
            res = max(res, up + down + 1)

    return res
```


```java
import java.util.Map;
import java.util.TreeMap;

public boolean isPossibleDivide(int[] hand, int groupSize) {
    Map<Integer, Integer> cardCount = new TreeMap<>();
    for (int card : hand) {
        cardCount.put(card, cardCount.getOrDefault(card, 0) + 1);
    }

    for (int card : cardCount.keySet()) {
        int count = cardCount.get(card);
        if (count > 0) {
            for (int i = 1; i < groupSize; ++i) {
                int tmp = cardCount.getOrDefault(card + i, 0) - count;
                if (tmp < 0) {
                    return false;
                }
                cardCount.put(card + i, tmp);
            }
        }
    }

    return true;
}
```

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

```python
from collections import Counter

def is_possible_divide(hand, group_size):
    card_count = Counter(hand)

    for card in sorted(card_count):
        if card_count[card] > 0:
            count = card_count[card]
            for i in range(1, group_size):
                if card_count[card + i] < count:
                    return False
                card_count[card + i] -= count

    return True
```


```cpp
int maxDistToClosest(vector<int>& seats) {
    int n = seats.size();
    int maxDist = 0, lastPerson = -1;

    for (int i = 0; i < n; ++i) {
        if (seats[i] == 1) {
            if (lastPerson == -1)
                maxDist = i;
            else
                maxDist = max(maxDist, (i - lastPerson) / 2);
            lastPerson = i;
        }
    }
    maxDist = max(maxDist, n - 1 - lastPerson);
    return maxDist;
}
```

```python
def maxDistToClosest(seats):
    n = len(seats)
    maxDist = 0
    lastPerson = -1

    for i in range(n):
        if seats[i] == 1:
            if lastPerson == -1:
                maxDist = i
            else:
                maxDist = max(maxDist, (i - lastPerson) // 2)
            lastPerson = i

    maxDist = max(maxDist, n - 1 - lastPerson)
    return maxDist
```


```java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public int rectangleArea(int[][] rectangles) {
    final int mod = 1000000007;
    int n = rectangles.length;
    Set<Integer> X = new HashSet<>();
    Set<Integer> Y = new HashSet<>();
    for (int[] rect : rectangles) {
        X.add(rect[0]);
        X.add(rect[2]);
        Y.add(rect[1]);
        Y.add(rect[3]);
    }
    Integer[] sortedX = X.toArray(new Integer[0]);
    Integer[] sortedY = Y.toArray(new Integer[0]);
    Arrays.sort(sortedX);
    Arrays.sort(sortedY);

...
```

```python
def rectangleArea(rectangles):
    mod = 10**9 + 7
    n = len(rectangles)
    X, Y = set(), set()
    for rect in rectangles:
        X.add(rect[0])
        X.add(rect[2])
        Y.add(rect[1])
        Y.add(rect[3])
    sorted_x = sorted(X)
    sorted_y = sorted(Y)
    cnt = [[0 for _ in range(len(Y) - 1)] for _ in range(len(X) - 1)]

    for rect in rectangles:
        x1_idx = sorted_x.index(rect[0])
        x2_idx = sorted_x.index(rect[2]) - 1
        y1_idx = sorted_y.index(rect[1])
        y2_idx = sorted_y.index(rect[3]) - 1
        for i in range(x1_idx, x2_idx + 1):
            for j in range(y1_idx, y2_idx + 1):
                cnt[i][j] = 1

    total_area = 0
    for i in range(len(X) - 1):
        for j in range(len(Y) - 1):
            if cnt[i][j]:
                total_area += (sorted_x[i + 1] - sorted_x[i]) * (sorted_y[j + 1] - sorted_y[j])
                total_area %= mod

    return total_area
```


```java
public int numFriendRequests(int[] ages) {
    int[] count = new int[121];
    int total_requests = 0;

    for (int age : ages) count[age]++;

    for (int a = 1; a <= 120; a++) {
        for (int b = 1; b <= 120; b++) {
            if (a * 0.5 + 7 >= b) continue;
            if (a < b) continue;
            if (a < b * 2) {
                total_requests += count[a] * count[b];
                if (a == b) total_requests -= count[a];
            }
        }
    }

    return total_requests;
}
```

```cpp
int numFriendRequests(vector<int>& ages) {
    vector<int> count(121, 0);
    int total_requests = 0;

    for (int age : ages) count[age]++;

    for (int a = 1; a <= 120; a++) {
        for (int b = 1; b <= 120; b++) {
            if (a * 0.5 + 7 >= b) continue;
            if (a < b) continue;
            if (a < b * 2) {
                total_requests += count[a] * count[b];
                if (a == b) total_requests -= count[a];
            }
        }
    }

    return total_requests;
}
```


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

vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) {
    for (auto &row : image) {
        reverse(row.begin(), row.end());
        for (int &pixel : row) {
            pixel = 1 - pixel;
        }
    }
    return image;
}
```

```python
def flipAndInvertImage(image):
    for row in image:
        row.reverse()
        for j in range(len(row)):
            row[j] = 1 - row[j]
    return image
```


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

class Solution:
    def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
        def find_deepest(node):
            if not node:
                return None, 0
            left, left_height = find_deepest(node.left)
            right, right_height = find_deepest(node.right)
            if left_height == right_height:
                return node, left_height + 1
            return (left, left_height + 1) if left_height > right_height else (right, right_height + 1)

        return find_deepest(root)[0]
```

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

class Solution {
    public TreeNode subtreeWithAllDeepest(TreeNode root) {
        return findDeepest(root).node;
    }

    private NodeHeight findDeepest(TreeNode node) {
        if (node == null) return new NodeHeight(null, 0);
        NodeHeight left = findDeepest(node.left);
        NodeHeight right = findDeepest(node.right);
        if (left.height == right.height) {
            return new NodeHeight(node, left.height + 1);
        }
        return left.height > right.height ? new NodeHeight(left.node, left.height + 1) : new NodeHeight(right.node, right.height + 1);
    }

    private class NodeHeight {
        TreeNode node;
        int height;

        NodeHeight(TreeNode node, int height) {
            this.node = node;
            this.height = height;
        }
    }
}
```


```python
def push_dominoes(dominoes: str) -> str:
    prev, cur = None, dominoes
    while prev != cur:
        prev = cur
        cur_lst = list(prev)
        for i in range(len(cur)):
            if prev[i] == 'L' and i > 0 and prev[i - 1] == '.':
                cur_lst[i - 1] = 'L'
            elif prev[i] == 'R' and i < len(cur) - 1 and prev[i + 1] == '.':
                cur_lst[i + 1] = 'R'
        cur = ''.join(cur_lst)
    return cur
```

```java
public String pushDominoes(String dominoes) {
    int n = dominoes.length();
    String prev;
    String cur = dominoes;
    do {
        prev = cur;
        StringBuilder sb = new StringBuilder(prev);
        for (int i = 0; i < n; ++i) {
            if (prev.charAt(i) == 'L' && i > 0 && prev.charAt(i - 1) == '.')
                sb.setCharAt(i - 1, 'L');
            else if (prev.charAt(i) == 'R' && i < n - 1 && prev.charAt(i + 1) == '.')
                sb.setCharAt(i + 1, 'R');
        }
        cur = sb.toString();
    } while (!prev.equals(cur));
    return cur;
}
```


```java
public int longestMountain(int[] arr) {
    int n = arr.length;
    int maxLength = 0;
    int i = 1;
    while (i < n - 1) {
        if (arr[i - 1] < arr[i] && arr[i] > arr[i + 1]) {
            int left = i - 1;
            int right = i + 1;
            while (left > 0 && arr[left - 1] < arr[left]) {
                left--;
            }
            while (right < n - 1 && arr[right] > arr[right + 1]) {
                right++;
            }
            maxLength = Math.max(maxLength, right - left + 1);
            i = right;
        } else {
            i++;
        }
    }
    return maxLength;
}
```

```cpp
#include <vector>
int longestMountain(std::vector<int>& arr) {
    int n = arr.size();
    int max_length = 0;
    int i = 1;
    while (i < n - 1) {
        if (arr[i - 1] < arr[i] && arr[i] > arr[i + 1]) {
            int left = i - 1;
            int right = i + 1;
            while (left > 0 && arr[left - 1] < arr[left]) {
                left--;
            }
            while (right < n - 1 && arr[right] > arr[right + 1]) {
                right++;
            }
            max_length = std::max(max_length, right - left + 1);
            i = right;
        } else {
            i++;
        }
    }
    return max_length;
}
```


```java
import java.util.*;

class Solution {
    public int shortestPathLength(int[][] graph) {
        int n = graph.length;
        Queue<int[]> q = new LinkedList<>();

        for(int i = 0; i < n; i++) {
            q.add(new int[]{i, 1 << i});
        }
        int steps = -1;
        boolean[][] visited = new boolean[n][1 << n];

        while(!q.isEmpty()) {
            steps++;
            int size = q.size();

            for(int k = 0; k < size; k++) {
                int[] curr = q.poll();
                int currNode = curr[0];
                int currVisits = curr[1];

                if(Integer.bitCount(currVisits) == n) return steps;

                for(int nextNode: graph[currNode]) {
                    int nextVisits = currVisits | (1 << nextNode);

                    if(!visited[nextNode][nextVisits]) {
                        visited[nextNode][nextVisits] = true;
                        q.add(new int[]{nextNode, nextVisits});
                    }
                }
            }
        }

        return -1;
    }
}
```

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

int shortestPathLength(vector<vector<int>>& graph) {
    int n = graph.size();
    queue<pair<int, bitset<12>>> q;

    for(int i = 0; i < n; i++) {
        q.push({i, 1 << i});
    }
    int steps = -1;
    vector<vector<bool>> visited(n, vector<bool>(1 << n));

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

        for(int k = 0; k < size; k++) {
            int currNode = q.front().first;
            bitset<12> currVisits = q.front().second;
            q.pop();

            if(currVisits.count() == n) return steps;

            for(int nextNode: graph[currNode]) {
                bitset<12> nextVisits = currVisits;
                nextVisits.set(nextNode);

                if(!visited[nextNode][nextVisits.to_ulong()]) {
                    visited[nextNode][nextVisits.to_ulong()] = true;
                    q.push({nextNode, nextVisits});
                }
            }
        }
    }

    return -1;
}
```


```python
def peakIndexInMountainArray(arr):
    low, high = 0, len(arr) - 1
    while low < high:
        mid = low + (high - low) // 2
        if arr[mid] < arr[mid + 1]:
            low = mid + 1
        else:
            high = mid
    return low
```

```cpp
int peakIndexInMountainArray(vector<int>& arr) {
    int low = 0, high = arr.size() - 1;
    while (low < high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] < arr[mid + 1])
            low = mid + 1;
        else
            high = mid;
    }
    return low;
}
```


```java
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

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

public List<Integer> findNodesAtDistanceK(TreeNode root, int targetVal, int k) {
    if (k < 0) return new ArrayList<>();
    Map<TreeNode, TreeNode> parentMap = new HashMap<>();
    Set<TreeNode> visited = new HashSet<>();
    TreeNode targetNode = initializeParentMap(root, null, targetVal, parentMap);

    List<Integer> result = new ArrayList<>();
    findNodesAtDistanceKHelper(targetNode, k, visited, parentMap, result);
    return result;
}

private TreeNode initializeParentMap(TreeNode node, TreeNode parent, int targetVal, Map<TreeNode, TreeNode> parentMap) {
    if (node == null) return null;
    if (node.val == targetVal) return node;
    parentMap.put(node, parent);
    TreeNode left = initializeParentMap(node.left, node, targetVal, parentMap);
    TreeNode right = initializeParentMap(node.right, node, targetVal, parentMap);
    return left != null ? left : right;
}

private void findNodesAtDistanceKHelper(TreeNode node, int k, Set<TreeNode> visited, Map<TreeNode, TreeNode> parentMap, List<Integer> result) {
    if (node == null || visited.contains(node)) return;
    visited.add(node);
    if (k == 0) {
        result.add(node.val);
        return;
    }

    findNodesAtDistanceKHelper(node.left, k-1, visited, parentMap, result);
    findNodesAtDistanceKHelper(node.right, k-1, visited, parentMap, result);
    findNodesAtDistanceKHelper(parentMap.get(node), k-1, visited, parentMap, result);
}
```

words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\]

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

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

vector<int> findNodesAtDistanceK(TreeNode* root, int targetVal, int k) {
    if (k < 0) return {};
    unordered_map<TreeNode*, TreeNode*> parentMap;
    unordered_set<TreeNode*> visited;
    TreeNode* targetNode = nullptr;
    initializeParentMap(root, nullptr, targetVal, parentMap, targetNode);

    vector<int> result;
    findNodesAtDistanceKHelper(targetNode, k, visited, parentMap, result);
    return result;
}

void initializeParentMap(TreeNode* node, TreeNode* parent, int targetVal, unordered_map<TreeNode*, TreeNode*> &parentMap, TreeNode* &targetNode) {
    if (!node || targetNode) return;
    if (node->val == targetVal) targetNode = node;
    parentMap[node] = parent;
    initializeParentMap(node->left, node, targetVal, parentMap, targetNode);
    initializeParentMap(node->right, node, targetVal, parentMap, targetNode);
}

void findNodesAtDistanceKHelper(TreeNode* node, int k, unordered_set<TreeNode*> &visited, unordered_map<TreeNode*, TreeNode*> &parentMap, vector<int> &result) {
    if (!node || visited.count(node)) return;
    visited.insert(node);
    if (k == 0) {
        result.push_back(node->val);
        return;
    }

    findNodesAtDistanceKHelper(node->left, k-1, visited, parentMap, result);
    findNodesAtDistanceKHelper(node->right, k-1, visited, parentMap, result);
    findNodesAtDistanceKHelper(parentMap[node], k-1, visited, parentMap, result);
}
```


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

public int maxDepth(TreeNode node) {
    if (node == null)
        return 0;
    else
        return Math.max(maxDepth(node.left), maxDepth(node.right)) + 1;
}

public TreeNode subtreeWithAllDeepest(TreeNode root) {
    if (root == null)
        return null;

    int leftDepth = maxDepth(root.left);
    int rightDepth = maxDepth(root.right);

    if (leftDepth == rightDepth)
        return root;

    if (leftDepth > rightDepth)
        return subtreeWithAllDeepest(root.left);
    else
        return subtreeWithAllDeepest(root.right);
}
```

```cpp
class TreeNode {
public:
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int v): val(v), left(NULL), right(NULL) {}
};

int maxDepth(TreeNode* node)
{
    if (node == NULL)
        return 0;
    else
        return max(maxDepth(node->left), maxDepth(node->right)) + 1;
}

TreeNode* subtreeWithAllDeepest(TreeNode* root)
{
    if (root == NULL)
        return NULL;

    int leftDepth = maxDepth(root->left);
    int rightDepth = maxDepth(root->right);

    if (leftDepth == rightDepth)
        return root;

    if (leftDepth > rightDepth)
        return subtreeWithAllDeepest(root->left);
    else
        return subtreeWithAllDeepest(root->right);
}
```


```java
import java.util.HashMap;
import java.util.Map;

public int lenLongestFibSubseq(int[] arr) {
    int n = arr.length;
    Map<Integer, Integer> index = new HashMap<>();
    for (int i = 0; i < n; ++i)
        index.put(arr[i], i);

    Map<Integer, Integer> longest = new HashMap<>();
    int ans = 0;

    for (int k = 0; k < n; ++k)
        for (int j = 0; j < k; ++j) {
            int i = index.getOrDefault(arr[k] - arr[j], -1);
            if (i >= 0 && i < j) {
                longest.put(j * n + k, longest.getOrDefault(i * n + j, 1) + 1);
                ans = Math.max(ans, longest.get(j * n + k) + 1);
            }
        }

    return ans >= 3 ? ans : 0;
}
```

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

int lenLongestFibSubseq(std::vector<int>& arr) {
    int n = arr.size();
    std::unordered_map<int, int> index;
    for (int i = 0; i < n; ++i)
        index[arr[i]] = i;

    std::unordered_map<int, int> longest;
    int ans = 0;

    for (int k = 0; k < n; ++k)
        for (int j = 0; j < k; ++j) {
            int i = index.find(arr[k] - arr[j]) == index.end() ? -1 : index[arr[k] - arr[j]];
            if (i >= 0 && i < j) {
                longest[j * n + k] = longest.find(i * n + j) == longest.end() ? 2 : longest[i * n + j] + 1;
                ans = std::max(ans, longest[j * n + k] + 1);
            }
        }

    return ans >= 3 ? ans : 0;
}
```


```python
def num_rescue_boats(people, limit):
    people.sort()
    left, right = 0, len(people) - 1
    boats = 0
    while left <= right:
        if people[left] + people[right] <= limit:
            left += 1
        right -= 1
        boats += 1
    return boats
```

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

int numRescueBoats(std::vector<int>& people, int limit) {
    std::sort(people.begin(), people.end());
    int left = 0, right = people.size() - 1;
    int boats = 0;
    while (left <= right) {
        if (people[left] + people[right] <= limit) {
            left++;
        }
        right--;
        boats++;
    }
    return boats;
}
```


```python
def sum_of_widths(nums):
    MOD = 10**9 + 7
    nums.sort()
    c, res = 1, 0
    n = len(nums)

    for i in range(n):
        res = (res + (nums[i] - nums[n - i - 1]) * c) % MOD
        c = c * 2 % MOD

    return res
```

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

const int MOD = 1e9 + 7;

int sumOfWidths(std::vector<int>& nums) {
    int n = nums.size();
    std::sort(nums.begin(), nums.end());
    long long res = 0, c = 1;

    for (int i = 0; i < n; i++, c = c * 2 % MOD)
        res = (res + (nums[i] - nums[n - i - 1]) * c) % MOD;

    return res;
}
```


```java
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;

public int numSpecialEquivalentGroups(String[] words) {
    Set<String> groups = new HashSet<>();

    for (String word : words) {
        StringBuilder evens = new StringBuilder();
        StringBuilder odds = new StringBuilder();

        for (int i = 0; i < word.length(); ++i) {
            if (i % 2 == 0) evens.append(word.charAt(i));
            else odds.append(word.charAt(i));
        }

        char[] evenArr = evens.toString().toCharArray();
        Arrays.sort(evenArr);
        char[] oddArr = odds.toString().toCharArray();
        Arrays.sort(oddArr);

        groups.add(new String(evenArr) + new String(oddArr));
    }

    return groups.size();
}
```

emails = \[ "test.email+alex@leetcode.com ", "test.e.mail+bob.cathy@leetcode.com ", "testemail+david@lee.tcode.com "\]

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

int numSpecialEquivalentGroups(std::vector<std::string>& words) {
    std::unordered_set<std::string> groups;

    for (std::string word : words) {
        std::string evens, odds;

        for (size_t i = 0; i < word.size(); ++i) {
            if (i % 2 == 0) evens += word[i];
            else odds += word[i];
        }

        std::sort(evens.begin(), evens.end());
        std::sort(odds.begin(), odds.end());

        groups.insert(evens + odds);
    }

    return groups.size();
}
```


```java
public boolean isMonotonic(int[] nums) {
    boolean increasing = true, decreasing = true;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] > nums[i - 1]) decreasing = false;
        if (nums[i] < nums[i - 1]) increasing = false;
    }
    return increasing || decreasing;
}
```

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 isMonotonic(vector<int>& nums) {
    bool increasing = true, decreasing = true;
    for (int i = 1; i < nums.size(); i++) {
        if (nums[i] > nums[i - 1]) decreasing = false;
        if (nums[i] < nums[i - 1]) increasing = false;
    }
    return increasing || decreasing;
}
```


```python
from bisect import bisect_right

def num_digits_less_than_n(digits: List[int], n: int) -> int:
    ans = 0
    factor = 1
    n_str = str(n)
    for i in range(len(n_str) - 1, -1, -1):
        ans += bisect_right(digits, int(n_str[i])) * factor
        factor *= len(digits)
    return ans
```

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

int num_digits_less_than_n(vector<int>& digits, int n) {
    int ans = 0, factor = 1;
    string n_str = to_string(n);
    for (int i = n_str.size() - 1; i >= 0; --i) {
        ans += (upper_bound(digits.begin(), digits.end(), n_str[i] - '0') - digits.begin()) * factor;
        factor *= digits.size();
    }
    return ans;
}
```


```python
def move_even_odd(nums):
    even_index = 0
    odd_index = len(nums) - 1

    while even_index < odd_index:
        if nums[even_index] % 2 == 0:
            even_index += 1
        else:
            nums[even_index], nums[odd_index] = nums[odd_index], nums[even_index]
            odd_index -= 1

    return nums
```

```java
public void moveEvenOdd(int[] nums) {
    int evenIndex = 0;
    int oddIndex = nums.length - 1;

    while (evenIndex < oddIndex) {
        if (nums[evenIndex] % 2 == 0) {
            evenIndex++;
        } else {
            int temp = nums[evenIndex];
            nums[evenIndex] = nums[oddIndex];
            nums[oddIndex] = temp;
            oddIndex--;
        }
    }
}
```


```python
def minDifference(nums, k):
    if len(nums) <= 1: return 0
    nums.sort()
    min_diff = nums[-1] - nums[0]
    for i in range(1, len(nums)):
        high = max(nums[i-1] + k, nums[-1] - k)
        low = min(nums[i] - k, nums[0] + k)
        min_diff = min(min_diff, high - low)
    return min_diff
```

```cpp
int minDifference(vector<int>& nums, int k) {
    if(nums.size() <= 1) return 0;
    sort(nums.begin(), nums.end());
    int min_diff = nums.back() - nums.front();
    for(int i=1; i<nums.size(); i++) {
        int high = max(nums[i-1] + k, nums.back() - k);
        int low = min(nums[i] - k, nums.front() + k);
        min_diff = min(min_diff, high - low);
    }
    return min_diff;
}
```


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

bool hasGroupsSizeX(vector<int>& deck) {
    unordered_map<int, int> counts;
    for (int card : deck) {
        counts[card]++;
    }
    int gcd_result = 0;
    for (auto& count : counts) {
        gcd_result = gcd(gcd_result, count.second);
    }
    return gcd_result > 1;
}
```

False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False False

```python
from collections import Counter
from math import gcd
from functools import reduce

def hasGroupsSizeX(deck):
    counts = Counter(deck)
    gcd_result = reduce(gcd, counts.values())
    return gcd_result > 1
```


```java
public boolean canReorderDoubled(int[] arr) {
    Map<Integer, Integer> count = new TreeMap<>();
    for (int a : arr) {
        count.put(a, count.getOrDefault(a, 0) + 1);
    }

    for (int a : count.keySet()) {
        if (count.get(a) > 0) {
            int target = a < 0 ? a / 2 : a * 2;
            if (count.getOrDefault(target, 0) < count.get(a)) return false;
            count.put(target, count.get(target) - count.get(a));
        }
    }

    return true;
}
```

false false false false false false false false false false false true false false false false false false false false true false false false false false false false false false false false true true false true true false false false false false false false

```cpp
bool canReorderDoubled(vector<int>& arr) {
    map<int, int> count;
    for (int a : arr) {
        count[a]++;
    }

    for (const auto& [a, c] : count) {
        if (c > 0) {
            int target = a < 0 ? a / 2 : a * 2;
            if (count[target] < c) return false;
            count[target] -= c;
        }
    }

    return true;
}
```


```java
public int[] sortArrayByParityII(int[] nums) {
    int j = 1;
    for (int i = 0; i < nums.length; i += 2) {
        if (nums[i] % 2 != 0) {
            while (nums[j] % 2 != 0) {
                j += 2;
            }
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }
    return nums;
}
```

```cpp
vector<int> sortArrayByParityII(vector<int>& nums) {
    int j = 1;
    for (int i = 0; i < nums.size(); i += 2) {
        if (nums[i] % 2) {
            while (nums[j] % 2) {
                j += 2;
            }
            swap(nums[i], nums[j]);
        }
    }
    return nums;
}
```


```python
def threeSumMulti(arr, target):
    MOD = 1000000007
    ans = 0

    arr.sort()
    n = len(arr)

    for i in range(n - 2):
        j, k = i + 1, n - 1
        while j < k:
            s = arr[i] + arr[j] + arr[k]
            if s > target:
                k -= 1
            elif s < target:
                j += 1
            else:
                if arr[j] != arr[k]:
                    left_count = right_count = 1

                    while j < n - 1 and arr[j] == arr[j + 1]:
                        left_count += 1
                        j += 1

                    while k > 0 and arr[k] == arr[k - 1]:
                        right_count += 1
                        k -= 1

                    ans += left_count * right_count
                    ans %= MOD
                    j += 1
                    k -= 1
                else:
                    ans += (k - j + 1) * (k - j) // 2
                    ans %= MOD
                    break

    return ans
```

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

int threeSumMulti(std::vector<int>& arr, int target) {
    const int MOD = 1000000007;
    long long ans = 0;

    sort(arr.begin(), arr.end());
    int n = arr.size();

    for (int i = 0; i < n - 2; ++i) {
        int j = i + 1, k = n - 1;
        while (j < k) {
            int sum = arr[i] + arr[j] + arr[k];
            if (sum > target) {
                k--;
            } else if (sum < target) {
                j++;
            } else {
                if (arr[j] != arr[k]) {
                    int left_count = 1, right_count = 1;

                    while (arr[j] == arr[j + 1]){
                        left_count++;
                        j++;
                    }
                    while (arr[k] == arr[k - 1]){
                        right_count++;
                        k--;
                    }

                    ans += left_count * right_count;
                    ans %= MOD;
                    j++, k--;
                } else {
                    ans += (long long)(k - j + 1) * (k - j) / 2;
                    ans %= MOD;
                    break;
                }
            }
        }
    }

    return ans;
}
```


```java
import java.util.*;

class Solution {
    public int minMalwareSpread(int[][] graph, int[] initial) {
        int n = graph.length, res = 0, minSize = Integer.MAX_VALUE;
        int[] color = new int[n];
        Arrays.fill(color, -1);
        int colors = 0;

        for (int i = 0; i < n; ++i) {
            if (color[i] == -1) {
                Queue<Integer> q = new LinkedList<>();
                q.offer(i);
                color[i] = colors;

                while (!q.isEmpty()) {
                    int t = q.poll();
                    for (int j = 0; j < n; ++j) {
                        if (graph[t][j] == 1 && color[j] == -1) {
                            q.offer(j);
                            color[j] = colors;
                        }
                    }
                }
                ++colors;
            }
        }

        int[] area = new int[colors], count = new int[colors];
        Set<Integer> initiallyInfected = new HashSet<>();
        for (int i : initial) {
            initiallyInfected.add(i);
        }
        for (int i = 0; i < n; ++i) {
            ++area[color[i]];
            if (initiallyInfected.contains(i)) {
                ++count[color[i]];
            }
        }

        for (int i : initial) {
            if (count[color[i]] == 1) {
                if (area[color[i]] < minSize) {
                    minSize = area[color[i]];
                    res = i;
                } else if (area[color[i]] == minSize && i < res) {
                    res = i;
                }
            }
        }

        return res;
    }
}
```

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

int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
    int n = graph.size(), res = 0, minSize = INT_MAX;
    vector<int> color(n, -1);
    int colors = 0;

    for (int i = 0; i < n; ++i) {
        if (color[i] == -1) {
            queue<int> q;
            q.push(i);
            color[i] = colors;

            while (!q.empty()) {
                int t = q.front(); q.pop();
                for (int j = 0; j < n; ++j) {
                    if (graph[t][j] == 1 && color[j] == -1) {
                        q.push(j);
                        color[j] = colors;
                    }
                }
            }
            ++colors;
        }
    }

    vector<int> area(colors, 0), count(colors, 0);
    set<int> initiallyInfected(initial.begin(), initial.end());
    for (int i = 0; i < n; ++i) {
        ++area[color[i]];
        if (initiallyInfected.count(i)) {
            ++count[color[i]];
        }
    }

    for (int i : initial) {
        if (count[color[i]] == 1) {
            if (area[color[i]] < minSize) {
                minSize = area[color[i]];
                res = i;
            } else if (area[color[i]] == minSize && i < res) {
                res = i;
            }
        }
    }

    return res;
}
```


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

public List<Integer> powerfulIntegers(int x, int y, int bound) {
    int max_i = x == 1 ? 0 : (int) (Math.log(bound) / Math.log(x));
    int max_j = y == 1 ? 0 : (int) (Math.log(bound) / Math.log(y));
    HashSet<Integer> resultSet = new HashSet<>();

    for (int i = 0; i <= max_i; i++) {
        for (int j = 0; j <= max_j; j++) {
            int powerfulNum = (int) (Math.pow(x, i) + Math.pow(y, j));
            if (powerfulNum <= bound) {
                resultSet.add(powerfulNum);
            }
        }
    }

    return new ArrayList<>(resultSet);
}
```

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

std::vector<int> powerfulIntegers(int x, int y, int bound) {
    int max_i = x == 1 ? 0 : std::ceil(std::log(bound) / std::log(x));
    int max_j = y == 1 ? 0 : std::ceil(std::log(bound) / std::log(y));
    std::set<int> result_set;

    for (int i = 0; i <= max_i; i++) {
        for (int j = 0; j <= max_j; j++) {
            int powerful_num = std::pow(x, i) + std::pow(y, j);
            if (powerful_num <= bound) {
                result_set.insert(powerful_num);
            }
        }
    }

    return std::vector<int>(result_set.begin(), result_set.end());
}
```


```python
def subarraysDivByK(nums, k):
    prefix_sums_mod_k = [0] * k
    prefix_sums_mod_k[0] = 1
    running_sum = 0
    count = 0

    for num in nums:
        running_sum += num
        mod = (running_sum % k + k) % k
        count += prefix_sums_mod_k[mod]
        prefix_sums_mod_k[mod] += 1

    return count
```

```cpp
int subarraysDivByK(vector<int>& nums, int k) {
    vector<int> prefixSumsModK(k, 0);
    prefixSumsModK[0] = 1;
    int runningSum = 0;
    int count = 0;

    for (int i = 0; i < nums.size(); ++i) {
        runningSum += nums[i];
        int mod = (runningSum % k + k) % k;
        count += prefixSumsModK[mod]++;
    }

    return count;
}
```


```python
def min_moves_unique(nums):
    nums.sort()
    moves = 0
    for i in range(1, len(nums)):
        if nums[i] <= nums[i - 1]:
            diff = nums[i - 1] - nums[i] + 1
            moves += diff
            nums[i] += diff
    return moves
```

```java
import java.util.Arrays;

public int minMovesUnique(int[] nums) {
    Arrays.sort(nums);
    int moves = 0;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] <= nums[i - 1]) {
            moves += nums[i - 1] - nums[i] + 1;
            nums[i] = nums[i - 1] + 1;
        }
    }
    return moves;
}
```


```java
import java.util.Stack;

public boolean validateStackSequences(int[] pushed, int[] popped) {
    Stack<Integer> stack = new Stack<>();
    int popIndex = 0;

    for (int pushValue : pushed) {
        stack.push(pushValue);
        while (!stack.isEmpty() && stack.peek() == popped[popIndex]) {
            stack.pop();
            popIndex++;
        }
    }

    return stack.isEmpty();
}
```

false false false false false false false false false false false false false false false false false false false false false false false false false true false false false true false false false false false false false false false false

```cpp
#include <vector>
#include <stack>

bool validateStackSequences(std::vector<int>& pushed, std::vector<int>& popped) {
    std::stack<int> stack;
    int popIndex = 0;

    for (int pushValue : pushed) {
        stack.push(pushValue);
        while (!stack.empty() && stack.top() == popped[popIndex]) {
            stack.pop();
            popIndex++;
        }
    }

    return stack.empty();
}
```


```java
import java.util.*;

public int[] deckRevealedIncreasing(int[] deck) {
    int n = deck.length;
    Queue<Integer> index = new LinkedList<>();
    for (int i = 0; i < n; i++)
        index.add(i);

    int[] ans = new int[n];
    Arrays.sort(deck);
    for (int card : deck) {
        ans[index.poll()] = card;
        if (!index.isEmpty()) {
            index.add(index.poll());
        }
    }
    return ans;
}
```

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

std::vector<int> deckRevealedIncreasing(std::vector<int>& deck) {
    int n = deck.size();
    std::deque<int> index;
    for (int i = 0; i < n; ++i)
        index.push_back(i);

    std::vector<int> ans(n);
    std::sort(deck.begin(), deck.end());

    for (int card : deck) {
        ans[index.front()] = card;
        index.pop_front();
        if (!index.empty()) {
            index.push_back(index.front());
            index.pop_front();
        }
    }

    return ans;
}
```


```python
from collections import defaultdict

def largestComponentSize(nums):
    def primes(n):
        for i in range(2, int(n**0.5) + 1):
            if n % i == 0:
                return i
        return n

    def dfs(node, visited, graph):
        if node in visited:
            return 0
        visited.add(node)
        size = 1
        for neighbor in graph[node]:
            size += dfs(neighbor, visited, graph)
        return size

    graph = defaultdict(set)
    visited = set()

    for num in nums:
        prime = primes(num)
        graph[prime].add(num)
        if num != prime:
            graph[num].add(prime)

    count = 0
    for num in nums:
        count = max(count, dfs(num, visited, graph))

    return count
```

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

using namespace std;

int primes(int n) {
    for (int i = 2; i * i <= n; ++i) {
        if (n % i == 0) return i;
    }
    return n;
}

int largestComponentSize(vector<int>& nums) {
    int count = 0;
    unordered_map<int, unordered_set<int>> graph;
    unordered_set<int> visited;
    for (int num : nums) {
        int prime = primes(num);
        graph[prime].insert(num);
        if (num != prime) graph[num].insert(prime);
    }

    function<int(int)> dfs = [&](int node) {
        if (!visited.insert(node).second) return 0;
        int res = 1;
        for (int neighbor : graph[node]) {
            res += dfs(neighbor);
        }
        return res;
    };

    for (int num : nums) {
        count = max(count, dfs(num));
    }
    return count;
}
```


```java
import java.util.Arrays;
import java.util.HashMap;

public boolean canReorderArray(int[] arr) {
    HashMap<Integer, Integer> count = new HashMap<>();
    for (int n : arr) {
        count.put(n, count.getOrDefault(n, 0) + 1);
    }
    Arrays.sort(arr);
    for (int x : arr) {
        if (count.get(x) == 0) {
            continue;
        }
        if (count.getOrDefault(2 * x, 0) > 0) {
            count.put(x, count.get(x) - 1);
            count.put(2 * x, count.get(2 * x) - 1);
        } else {
            return false;
        }
    }
    return true;
}
```

false false false false true false false false false true false false false false false false false false false false false false false false false false false true false false false false true false false false false false false false false false false false

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

bool canReorderArray(std::vector<int>& arr) {
    std::unordered_map<int, int> count;
    for (int n : arr) {
        count[n]++;
    }
    sort(arr.begin(), arr.end());
    for (int x : arr) {
        if (count[x] == 0) {
            continue;
        }
        if (count[2 * x] > 0) {
            count[x]--;
            count[2 * x]--;
        } else {
            return false;
        }
    }
    return true;
}
```


```cpp
int minKBitFlips(vector<int>& nums, int k) {
    int n = nums.size();
    vector<int> flipped(n, 0);
    int flips = 0, ans = 0;
    for (int i = 0; i < n; ++i) {
        if (i >= k) flips = (flips - flipped[i - k]) % 2;
        if ((flips + nums[i]) % 2 == 0) {
            if (i + k > n) return -1;
            flipped[i] = 1;
            flips = (flips + 1) % 2;
            ans++;
        }
    }
    return ans;
}
```

```python
def min_k_bit_flips(nums, k):
    n = len(nums)
    flipped = [0] * n
    flips = ans = 0
    for i in range(n):
        if i >= k:
            flips -= flipped[i - k]
        if (flips + nums[i]) % 2 == 0:
            if i + k > n:
                return -1
            flipped[i] = 1
            flips += 1
            ans += 1
    return ans
```


```python
from collections import Counter

def numSquarefulPerms(nums):
    def is_square(n):
        return int(n ** 0.5) ** 2 == n

    def dfs(idx):
        if idx == len(nums):
            return 1

        count = 0
        for key in counter.keys():
            if counter[key] and (idx == 0 or is_square(nums[idx - 1] + key)):
                counter[key] -= 1
                nums[idx] = key
                count += dfs(idx + 1)
                counter[key] += 1

        return count

    key_set, counter = set(nums), Counter(nums)
    return dfs(0)
```

```java
import java.util.HashMap;
import java.util.Map;

public int numSquarefulPerms(int[] nums) {
    Map<Integer, Integer> counter = new HashMap<>();
    for (int num : nums)
        counter.put(num, counter.getOrDefault(num, 0) + 1);

    return dfs(nums, 0, counter);
}

private boolean isSquare(int n) {
    int root = (int) Math.sqrt(n);
    return root * root == n;
}

private int dfs(int[] nums, int idx, Map<Integer, Integer> counter) {
    if (idx == nums.length)
        return 1;

    int count = 0;
    for (int key : counter.keySet()) {
        if (counter.get(key) != 0 && (idx == 0 || isSquare(nums[idx - 1] + key))) {
            counter.put(key, counter.get(key) - 1);
            nums[idx] = key;
            count += dfs(nums, idx + 1, counter);
            counter.put(key, counter.get(key) + 1);
        }
    }

    return count;
}
```


```python
def findJudge(n, trust):
    trust_counts = [0] * (n + 1)
    for a, b in trust:
        trust_counts[a] -= 1
        trust_counts[b] += 1
    for i in range(1, n + 1):
        if trust_counts[i] == n - 1:
            return i
    return -1
```

```java
public int findJudge(int n, int[][] trust) {
    int[] trustCounts = new int[n + 1];
    for (int[] t : trust) {
        trustCounts[t[0]]--;
        trustCounts[t[1]]++;
    }
    for (int i = 1; i <= n; i++) {
        if (trustCounts[i] == n - 1)
            return i;
    }
    return -1;
}
```


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

int regionsBySlashes(std::vector<std::string>& grid) {
    int n = grid.size();
    std::vector<std::vector<int>> graph(n * 3, std::vector<int>(n * 3, 0));

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (grid[i][j] == '/') {
                graph[i * 3][j * 3 + 2] = graph[i * 3 + 1][j * 3 + 1] = graph[i * 3 + 2][j * 3] = 1;
            }
            if (grid[i][j] == '\\') {
                graph[i * 3][j * 3] = graph[i * 3 + 1][j * 3 + 1] = graph[i * 3 + 2][j * 3 + 2] = 1;
            }
        }
    }

    int regions = 0;
    for (int i = 0; i < n * 3; ++i) {
        for (int j = 0; j < n * 3; ++j) {
            if (!graph[i][j]) {
                regions++;
                dfs(graph, i, j);
            }
        }
    }

    return regions;
}

void dfs(std::vector<std::vector<int>>& graph, int i, int j) {
    int n = graph.size();
    if (i < 0 || j < 0 || i >= n || j >= n || graph[i][j]) return;

    graph[i][j] = 1;
    dfs(graph, i - 1, j);
    dfs(graph, i + 1, j);
    dfs(graph, i, j - 1);
    dfs(graph, i, j + 1);
}
```

```python
def regionsBySlashes(grid):
    n = len(grid)
    graph = [[0] * (n * 3) for _ in range(n * 3)]

    for i in range(n):
        for j in range(n):
            if grid[i][j] == '/':
                graph[i * 3][j * 3 + 2] = graph[i * 3 + 1][j * 3 + 1] = graph[i * 3 + 2][j * 3] = 1
            if grid[i][j] == '\\':
                graph[i * 3][j * 3] = graph[i * 3 + 1][j * 3 + 1] = graph[i * 3 + 2][j * 3 + 2] = 1

    regions = 0
    for i in range(n * 3):
        for j in range(n * 3):
            if not graph[i][j]:
                regions += 1
                dfs(graph, i, j)

    return regions

def dfs(graph, i, j):
    n = len(graph)
    if i < 0 or j < 0 or i >= n or j >= n or graph[i][j]:
        return

    graph[i][j] = 1
    dfs(graph, i - 1, j)
    dfs(graph, i + 1, j)
    dfs(graph, i, j - 1)
    dfs(graph, i, j + 1)
```


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

int maxWidthRamp(std::vector<int>& nums) {
    std::vector<int> indices(nums.size());
    for (int i = 0; i < nums.size(); ++i) {
        indices[i] = i;
    }

    std::sort(indices.begin(), indices.end(), [&](int i, int j) {
        return nums[i] == nums[j] ? i < j : nums[i] < nums[j];
    });

    int maxWidth = 0;
    int minIndex = std::numeric_limits<int>::max();
    for (int index : indices) {
        maxWidth = std::max(maxWidth, index - minIndex);
        minIndex = std::min(minIndex, index);
    }

    return maxWidth;
}
```

```python
def maxWidthRamp(nums):
    indices = sorted(range(len(nums)), key=lambda i: (nums[i], i))

    maxWidth = 0
    minIndex = float('inf')
    for index in indices:
        maxWidth = max(maxWidth, index - minIndex)
        minIndex = min(minIndex, index)

    return maxWidth
```


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

public List<Integer> pancakeSort(int[] arr) {
    List<Integer> flips = new ArrayList<>();
    for (int size = arr.length; size > 1; --size) {
        int maxIdx = getMaxIdx(arr, size);
        flips.add(maxIdx + 1);
        flips.add(size);
        reverse(arr, 0, maxIdx);
        reverse(arr, 0, size - 1);
    }
    return flips;
}

private int getMaxIdx(int[] arr, int size) {
    int maxIdx = 0;
    for (int i = 1; i < size; ++i) {
        if (arr[i] > arr[maxIdx]) {
            maxIdx = i;
        }
    }
    return maxIdx;
}

private void reverse(int[] arr, int start, int end) {
    while (start < end) {
        int temp = arr[start];
        arr[start++] = arr[end];
        arr[end--] = temp;
    }
}
```

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

vector<int> pancakeSort(vector<int>& arr) {
    vector<int> flips;
    for (int size = arr.size(); size > 1; --size) {
        int maxIdx = max_element(arr.begin(), arr.begin() + size) - arr.begin();
        flips.push_back(maxIdx + 1);
        flips.push_back(size);
        reverse(arr.begin(), arr.begin() + maxIdx + 1);
        reverse(arr.begin(), arr.begin() + size);
    }
    return flips;
}
```


```cpp
int smallestRepunitDivByK(int k) {
    if (k % 2 == 0 || k % 5 == 0) return -1;
    int n = 0;
    for (int i = 1; i <= k; i++) {
        n = (n * 10 + 1) % k;
        if (n == 0) return i;
    }
    return -1;
}
```

```python
def smallestRepunitDivByK(k: int) -> int:
    if k % 2 == 0 or k % 5 == 0:
        return -1
    n = 0
    for i in range(1, k + 1):
        n = (n * 10 + 1) % k
        if n == 0:
            return i
    return -1
```


```java
import java.util.Arrays;

public int largestPerimeter(int[] nums) {
    Arrays.sort(nums);

    for (int i = nums.length - 1; i >= 2; --i) {
        if (nums[i] < nums[i - 1] + nums[i - 2]) {
            return nums[i] + nums[i - 1] + nums[i - 2];
        }
    }

    return 0;
}
```

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

int largestPerimeter(std::vector<int>& nums) {
    std::sort(nums.begin(), nums.end(), std::greater<int>());

    for (size_t i = 0; i < nums.size() - 2; ++i) {
        if (nums[i] < nums[i + 1] + nums[i + 2]) {
            return nums[i] + nums[i + 1] + nums[i + 2];
        }
    }

    return 0;
}
```


```python
def sortedSquares(nums):
    return sorted([x ** 2 for x in nums])
```

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

vector<int> sortedSquares(vector<int>& nums) {
    for(int i = 0; i < nums.size(); i++) {
        nums[i] *= nums[i];
    }
    sort(nums.begin(), nums.end());
    return nums;
}
```


```python
def maxTurbulenceSize(arr):
    n = len(arr)
    result = 1
    i = 0

    while i < n - 1:
        if arr[i] == arr[i + 1]:
            i += 1
            continue

        j = i + 1
        while j < n - 1 and ((arr[j] > arr[j + 1]) != (arr[j - 1] > arr[j])):
            j += 1

        result = max(result, j - i + 1)
        i = j

    return result
```

```cpp
int maxTurbulenceSize(vector<int>& arr) {
    int n = arr.size();
    int result = 1;
    int i = 0;

    while (i < n - 1) {
        if (arr[i] == arr[i + 1]) {
            i++;
            continue;
        }

        int j = i + 1;
        while (j < n - 1 && ((arr[j] > arr[j + 1]) != (arr[j - 1] > arr[j])))
            j++;

        result = max(result, j - i + 1);
        i = j;
    }

    return result;
}
```


```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) {}
};

int maxAncestorDiff(TreeNode* root) {
    return helper(root, root->val, root->val);
}

int helper(TreeNode* node, int mn, int mx) {
    if (node == nullptr) {
        return mx - mn;
    }

    mx = max(mx, node->val);
    mn = min(mn, node->val);

    int left_diff = helper(node->left, mn, mx);
    int right_diff = helper(node->right, mn, mx);

    return max(left_diff, right_diff);
}
```

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10, None, 11]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10, None, 11, None, 12, None, 13, None, 14, None, 15]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10, None, 11, None, 12]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10, None, 11, None, 12, None, 13]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10, None, 11, None, 12, None, 13, None, 14, None, 15, None, 16, None, 17]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10, None, 11, None, 12, None, 13, None, 14, None, 15, None, 16]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8, None, 9, None, 10, None, 11, None, 12, None, 13, None, 14]

[1, None, 2, None, 0, 3, None, 4, None, 5, None, 6, None, 7, None, 8]

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

def maxAncestorDiff(root: TreeNode) -> int:
    def helper(node, mn, mx):
        if node is None:
            return mx - mn

        mx = max(mx, node.val)
        mn = min(mn, node.val)

        left_diff = helper(node.left, mn, mx)
        right_diff = helper(node.right, mn, mx)

        return max(left_diff, right_diff)

    return helper(root, root.val, root.val)
```


```python
def interval_intersection(firstList, secondList):
    result = []
    i, j = 0, 0

    while i < len(firstList) and j < len(secondList):
        start = max(firstList[i][0], secondList[j][0])
        end = min(firstList[i][1], secondList[j][1])

        if start <= end:
            result.append([start, end])

        if firstList[i][1] < secondList[j][1]:
            i += 1
        else:
            j += 1

    return result
```

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

vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
    vector<vector<int>> result;
    int i = 0, j = 0;

    while (i < firstList.size() && j < secondList.size()) {
        int start = max(firstList[i][0], secondList[j][0]);
        int end = min(firstList[i][1], secondList[j][1]);

        if (start <= end) {
            result.push_back({start, end});
        }

        if (firstList[i][1] < secondList[j][1]) {
            i++;
        } else {
            j++;
        }
    }

    return result;
}
```


```python
def good_subarrays(nums, k):
    count = 0
    for i in range(len(nums)):
        frequency = {}
        for j in range(i, len(nums)):
            frequency[nums[j]] = frequency.get(nums[j], 0) + 1
            if len(frequency) > k:
                break
            if len(frequency) == k:
                count += 1
    return count
```

```cpp
#include <unordered_map>

int good_subarrays(vector<int>& nums, int k) {
    int count = 0;
    for (int i = 0; i < nums.size(); i++) {
        unordered_map<int, int> frequency;
        for (int j = i; j < nums.size(); j++) {
            frequency[nums[j]]++;
            if (frequency.size() > k) break;
            if (frequency.size() == k) count++;
        }
    }
    return count;
}
```


```python
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
    if root is None or val > root.val:
        newNode = TreeNode(val)
        newNode.left = root
        return newNode
    root.right = self.insertIntoMaxTree(root.right, val)
    return root
```

```cpp
TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
    if (!root || val > root->val) {
        TreeNode *newNode = new TreeNode(val);
        newNode->left = root;
        return newNode;
    }
    root->right = insertIntoMaxTree(root->right, val);
    return root;
}
```


```java
import java.util.*;

public int[] gridIllumination(int n, int[][] lamps, int[][] queries) {
    Set<Integer> lampCols = new HashSet<>();
    Set<Integer> lampRows = new HashSet<>();
    Set<Integer> lampLeftDiag = new HashSet<>();
    Set<Integer> lampRightDiag = new HashSet<>();

    for (int[] lamp : lamps) {
        lampRows.add(lamp[0]);
        lampCols.add(lamp[1]);
        lampLeftDiag.add(lamp[0] - lamp[1]);
        lampRightDiag.add(lamp[0] + lamp[1]);
    }

    int[] ans = new int[queries.length];

    for (int j = 0; j < queries.length; j++) {
        int row = queries[j][0];
        int col = queries[j][1];
        if (lampRows.contains(row) || lampCols.contains(col) || lampLeftDiag.contains(row - col) || lampRightDiag.contains(row + col)) {
            ans[j] = 1;
        } else {
            ans[j] = 0;
        }
        for (int i = -1; i <= 1; i++) {
            for (int k = -1; k <= 1; k++) {
                int newRow = row + i;
                int newCol = col + k;
                lampRows.remove(newRow);
                lampCols.remove(newCol);
                lampLeftDiag.remove(newRow - newCol);
                lampRightDiag.remove(newRow + newCol);
            }
        }
    }
    return ans;
}
```

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

vector<int> gridIllumination(int n, vector<vector<int>>& lamps, vector<vector<int>>& queries) {
    unordered_set<int> lampCols, lampRows, lampLeftDiag, lampRightDiag;
    vector<int> ans;

    for (auto& lamp : lamps) {
        int row = lamp[0];
        int col = lamp[1];
        lampRows.insert(row);
        lampCols.insert(col);
        lampLeftDiag.insert(row - col);
        lampRightDiag.insert(row + col);
    }

    for (auto& query : queries) {
        int row = query[0];
        int col = query[1];
        if (lampRows.count(row) || lampCols.count(col) || lampLeftDiag.count(row - col) || lampRightDiag.count(row + col)) {
            ans.push_back(1);
        } else {
            ans.push_back(0);
        }
        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                int newRow = row + i;
                int newCol = col + j;
                lampRows.erase(newRow);
                lampCols.erase(newCol);
                lampLeftDiag.erase(newRow - newCol);
                lampRightDiag.erase(newRow + newCol);
            }
        }
    }
    return ans;
}
```


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

std::vector<char> commonChars(std::vector<std::string>& words) {
    std::unordered_map<char, int> merged;
    for (const auto& word : words) {
        std::unordered_map<char, int> word_map;
        for (char c : word) {
            ++word_map[c];
        }
        if (merged.empty()) {
            merged = word_map;
        }
        else {
            for (auto& entry : merged) {
                entry.second = std::min(entry.second, word_map[entry.first]);
            }
        }
    }

    std::vector<char> result;
    for (const auto& entry : merged) {
        for (int i = 0; i < entry.second; ++i) {
            result.push_back(entry.first);
        }
    }
    return result;
}
```

```python
from collections import Counter

def commonChars(words):
    merged = Counter()
    for word in words:
        word_count = Counter(word)
        if not merged:
            merged = word_count
        else:
            for char in merged:
                merged[char] = min(merged[char], word_count[char])

    result = []
    for char, count in merged.items():
        result.extend([char] * count)
    return result
```


```java
import java.util.Arrays;

public int heightChecker(int[] heights) {
    int[] expected = heights.clone();
    Arrays.sort(expected);

    int count = 0;
    for (int i = 0; i < heights.length; ++i) {
        if (heights[i] != expected[i]) {
            ++count;
        }
    }

    return count;
}
```

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

int heightChecker(std::vector<int>& heights) {
    std::vector<int> expected = heights;
    std::sort(expected.begin(), expected.end());

    int count = 0;
    for (int i = 0; i < heights.size(); ++i) {
        if (heights[i] != expected[i]) {
            ++count;
        }
    }

    return count;
}
```


```java
public int[] prevPermOpt1(int[] arr) {
    int n = arr.length;
    for (int i = n - 2; i >= 0; i--) {
        if (arr[i] > arr[i + 1]) {
            int j = i + 1;
            while (j < n && arr[j] < arr[i]) j++;
            int temp = arr[i];
            arr[i] = arr[j - 1];
            arr[j - 1] = temp;
            break;
        }
    }
    return arr;
}
```

```python
def prevPermOpt1(arr):
    n = len(arr)
    for i in range(n - 2, -1, -1):
        if arr[i] > arr[i + 1]:
            j = i + 1
            while j < n and arr[j] < arr[i]:
                j += 1
            arr[i], arr[j - 1] = arr[j - 1], arr[i]
            break
    return arr
```


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

bool dfs(int node, const std::unordered_map<int, std::vector<int>>& graph, std::vector<int>& visited, int destination) {
    if (graph.find(node) == graph.end()) return node == destination;
    if (visited[node] != 0) return visited[node] == 2;

    visited[node] = 1;
    for (int neighbor : graph.at(node)) {
        if (!dfs(neighbor, graph, visited, destination)) return false;
    }

    visited[node] = 2;
    return true;
}

bool leadsToDestination(int n, const std::vector<std::vector<int>>& edges, int source, int destination) {
    std::unordered_map<int, std::vector<int>> graph;
    for (const auto& edge : edges) {
        graph[edge[0]].push_back(edge[1]);
    }

    std::vector<int> visited(n, 0);
    return dfs(source, graph, visited, destination);
}
```

false true false false false true true false true false false false false false false false false false false false true false true false false false false true true false false false false false false false false false true false true false false false false false false false false true true true false false true

```java
import java.util.*;

public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {
    Map<Integer, List<Integer>> graph = new HashMap<>();
    for (int[] edge : edges) {
        graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
    }

    int[] visited = new int[n];
    return dfs(source, graph, visited, destination);
}

private boolean dfs(int node, Map<Integer, List<Integer>> graph, int[] visited, int destination) {
    if (!graph.containsKey(node)) return node == destination;
    if (visited[node] != 0) return visited[node] == 2;

    visited[node] = 1;
    for (int neighbor : graph.get(node)) {
        if (!dfs(neighbor, graph, visited, destination)) return false;
    }

    visited[node] = 2;
    return true;
}
```


```python
def findKthPositive(nums, k):
    left, right = 0, len(nums)
    while left < right:
        mid = left + (right - left) // 2
        if nums[mid] - mid - 1 < k:
            left = mid + 1
        else:
            right = mid
    return left + k
```

```cpp
int findKthPositive(vector<int>& nums, int k) {
    int left = 0, right = nums.size();
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] - mid - 1 < k) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left + k;
}
```


```java
public int maxScoreSightseeingPair(int[] values) {
    int max_score = 0, max_score_left = values[0] + 0;
    for (int j = 1; j < values.length; ++j) {
        max_score = Math.max(max_score, max_score_left + values[j] - j);
        max_score_left = Math.max(max_score_left, values[j] + j);
    }
    return max_score;
}
```

```cpp
int maxScoreSightseeingPair(vector<int>& values) {
    int max_score = 0, max_score_left = values[0] + 0;
    for (int j = 1; j < values.size(); ++j) {
        max_score = max(max_score, max_score_left + values[j] - j);
        max_score_left = max(max_score_left, values[j] + j);
    }
    return max_score;
}
```


```python
def fixedPoint(arr: List[int]) -> int:
    left, right = 0, len(arr) - 1
    while left < right:
        middle = left + (right - left) // 2
        if arr[middle] < middle:
            left = middle + 1
        else:
            right = middle
    return left if arr[left] == left else -1
```

```cpp
int fixedPoint(vector<int>& arr) {
    int left = 0, right = arr.size() - 1;
    while (left < right) {
        int middle = left + (right - left) / 2;
        if (arr[middle] < middle) {
            left = middle + 1;
        } else {
            right = middle;
        }
    }
    return arr[left] == left ? left : -1;
}
```


```java
import java.util.*;

class Solution {
    public int manhattanDistance(int[] worker, int[] bike) {
        return Math.abs(worker[0] - bike[0]) + Math.abs(worker[1] - bike[1]);
    }

    private void dfs(int[][] workers, int[][] bikes, boolean[] used, int index, int dist, int[] minDist) {
        if (index == workers.length) {
            minDist[0] = Math.min(minDist[0], dist);
            return;
        }

        if (dist >= minDist[0]) {
            return;
        }

        for (int i = 0; i < bikes.length; i++) {
            if (used[i]) {
                continue;
            }
            used[i] = true;
            int curDist = manhattanDistance(workers[index], bikes[i]);
            dfs(workers, bikes, used, index+1, dist + curDist, minDist);
            used[i] = false;
        }
    }

    public int assignBikes(int[][] workers, int[][] bikes) {
        int[] minDist = new int[]{Integer.MAX_VALUE};
        boolean[] used = new boolean[bikes.length];
        dfs(workers, bikes, used, 0, 0, minDist);
        return minDist[0];
    }
}
```

```python
from typing import List

def manhattan_distance(worker: List[int], bike: List[int]) -> int:
    return abs(worker[0] - bike[0]) + abs(worker[1] - bike[1])

def dfs(workers: List[List[int]], bikes: List[List[int]], used: List[bool], index: int, dist: int, min_dist: List[int]) -> None:
    if index == len(workers):
        min_dist[0] = min(min_dist[0], dist)
        return

    if dist >= min_dist[0]:
        return

    for i in range(len(bikes)):
        if used[i]:
            continue
        used[i] = True
        cur_dist = manhattan_distance(workers[index], bikes[i])
        dfs(workers, bikes, used, index + 1, dist + cur_dist, min_dist)
        used[i] = False

def assign_bikes(workers: List[List[int]], bikes: List[List[int]]) -> int:
    min_dist = [float('inf')]
    used = [False] * len(bikes)
    dfs(workers, bikes, used, 0, 0, min_dist)
    return min_dist[0]
```


```cpp
int countDigit(int d, int low, int high) {
    int count = 0;
    for (int i = low; i <= high; ++i) {
        int num = i;
        while (num) {
            if (num % 10 == d) {
                count++;
            }
            num /= 10;
        }
    }
    return count;
}
```

```python
def count_digit(d, low, high):
    count = 0
    for i in range(low, high + 1):
        num = i
        while num > 0:
            if num % 10 == d:
                count += 1
            num //= 10
    return count
```


```java
import java.util.Stack;

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

public int[] nextGreaterNodes(ListNode head) {
    Stack<Integer> greater = new Stack<>();
    ListNode current = head;
    int size = 0;

    while (current != null) {
        size++;
        current = current.next;
    }

    int[] answer = new int[size];
    int index = 0;

    current = head;

    while (current != null) {
        while (!greater.empty() && answer[greater.peek()] < current.val) {
            answer[greater.pop()] = current.val;
        }
        answer[index] = current.val;
        greater.push(index++);
        current = current.next;
    }

    while (!greater.empty()) {
        answer[greater.pop()] = 0;
    }
    return answer;
}
```

```cpp
#include <stack>
#include <vector>

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

std::vector<int> nextGreaterNodes(ListNode* head) {
    std::vector<int> result;
    std::stack<int> greater;
    while (head) {
        while (!greater.empty() && greater.top() < head->val) {
            greater.top() = head->val;
            greater.pop();
        }
        result.push_back(head->val);
        greater.push(0);
        head = head->next;
    }
    return result;
}
```


```java
import java.util.*;

public class Solution {
    public int[] addNegabinary(int[] arr1, int[] arr2) {
        LinkedList<Integer> res = new LinkedList<>();
        int i = arr1.length - 1, j = arr2.length - 1, carry = 0;
        while (i >= 0 || j >= 0 || carry < 0 || carry > 0) {
            if (i >= 0) carry += arr1[i--];
            if (j >= 0) carry += arr2[j--];
            res.addFirst(carry & 1);
            carry = -(carry >> 1);
        }
        while (res.size() > 1 && res.peekFirst() == 0) res.pollFirst();
        return res.stream().mapToInt(Integer::intValue).toArray();
    }
}
```

```python
from collections import deque

def addNegabinary(arr1, arr2):
    res = deque()
    carry, i, j = 0, len(arr1) - 1, len(arr2) - 1
    while i >= 0 or j >= 0 or carry:
        if i >= 0: carry += arr1[i]; i -= 1
        if j >= 0: carry += arr2[j]; j -= 1
        res.appendleft(carry & 1)
        carry = -(carry >> 1)
    while len(res) > 1 and res[0] == 0: res.popleft()
    return list(res)
```


```java
public int numSubmatrixSumTarget(int[][] matrix, int target) {
    int rows = matrix.length, cols = matrix[0].length;
    for (int row = 0; row < rows; ++row)
        for (int col = 1; col < cols; ++col)
            matrix[row][col] += matrix[row][col-1];

    int count = 0;
    Map<Integer, Integer> counter = new HashMap<>();
    for (int col1 = 0; col1 < cols; ++col1) {
        for (int col2 = col1; col2 < cols; ++col2) {
            counter.clear();
            counter.put(0, 1);
            int cur_sum = 0;
            for (int row = 0; row < rows; ++row) {
                cur_sum += matrix[row][col2] - (col1 > 0 ? matrix[row][col1-1] : 0);
                count += counter.getOrDefault(cur_sum - target, 0);
                counter.put(cur_sum, counter.getOrDefault(cur_sum, 0) + 1);
            }
        }
    }
    return count;
}
```

```cpp
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
    int rows = matrix.size(), cols = matrix[0].size();
    for (int row = 0; row < rows; ++row)
        for (int col = 1; col < cols; ++col)
            matrix[row][col] += matrix[row][col-1];

    int count = 0;
    unordered_map<int, int> counter;
    for (int col1 = 0; col1 < cols; ++col1) {
        for (int col2 = col1; col2 < cols; ++col2) {
            counter.clear();
            counter[0] = 1;
            int cur_sum = 0;
            for (int row = 0; row < rows; ++row) {
                cur_sum += matrix[row][col2] - (col1 > 0 ? matrix[row][col1-1] : 0);
                count += counter[cur_sum - target];
                ++counter[cur_sum];
            }
        }
    }
    return count;
}
```