```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sufficientSubset(TreeNode root, int limit) {
        if(root == null) return null;
        if(root.left == null && root.right == null) {
            if(root.val < limit) return null;
            return root;
        }
        root.left = sufficientSubset(root.left, limit - root.val);
        root.right = sufficientSubset(root.right, limit - root.val);
        if(root.left == null && root.right == null) return null;

        return root;
    }
}
```

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
        if not root:
            return None
        if not root.left and not root.right:
            if root.val < limit:
                return None
            return root
        root.left = self.sufficientSubset(root.left, limit - root.val)
        root.right = self.sufficientSubset(root.right, limit - root.val)
        if not root.left and not root.right:
            return None

        return root
```


```cpp
int sumOfDigits(vector<int>& nums) {
    int minVal = *min_element(nums.begin(), nums.end());
    int digitSum = 0;
    while (minVal > 0) {
        digitSum += minVal % 10;
        minVal /= 10;
    }
    return digitSum % 2 == 0 ? 1 : 0;
}
```

```python
def sum_of_digits(nums):
    min_val = min(nums)
    digit_sum = sum(int(digit) for digit in str(min_val))
    return 1 if digit_sum % 2 == 0 else 0
```


```python
from typing import List

def largestValsFromLabels(values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:
    items = list(zip(values, labels))
    items.sort(key=lambda x: x[0], reverse=True)

    label_count = {}
    ans = 0

    for value, label in items:
        if label not in label_count:
            label_count[label] = 0
        if label_count[label] < useLimit:
            ans += value
            label_count[label] += 1
            numWanted -= 1
            if numWanted == 0:
                break

    return ans
```

```java
import java.util.*;

public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {
    int n = values.length;
    int[][] items = new int[n][2];
    for (int i = 0; i < n; ++i) {
        items[i][0] = values[i];
        items[i][1] = labels[i];
    }

    Arrays.sort(items, (a, b) -> Integer.compare(b[0], a[0]));

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

    for (int[] item : items) {
        labelCount.putIfAbsent(item[1], 0);
        if (labelCount.get(item[1]) < useLimit) {
            ans += item[0];
            labelCount.put(item[1], labelCount.get(item[1]) + 1);
            if (--numWanted == 0) break;
        }
    }

    return ans;
}
```


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

using namespace std;

int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
    int n = grid.size();
    if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;

    vector<vector<int>> dir = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
    queue<pair<int, int>> q;
    q.push({0, 0});
    grid[0][0] = 1;

    int pathLength = 1;

    while (!q.empty()) {
        int qlen = q.size();
        for (int i = 0; i < qlen; i++) {
            int x = q.front().first;
            int y = q.front().second;
            q.pop();

            if (x == n - 1 && y == n - 1) return pathLength;

            for (vector<int>& d : dir) {
                int newX = x + d[0];
                int newY = y + d[1];

                if (newX >= 0 && newX < n && newY >= 0 && newY < n && grid[newX][newY] == 0) {
                    q.push({newX, newY});
                    grid[newX][newY] = 1;
                }
            }
        }
        pathLength++;
    }

    return -1;
}
```

```python
from collections import deque

def shortestPathBinaryMatrix(grid):
    n = len(grid)
    if grid[0][0] or grid[n - 1][n - 1]: return -1

    dir = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
    q = deque([(0, 0)])
    grid[0][0] = 1

    pathLength = 1

    while q:
        qlen = len(q)
        for _ in range(qlen):
            x, y = q.popleft()

            if x == n - 1 and y == n - 1: return pathLength

            for d in dir:
                newX, newY = x + d[0], y + d[1]

                if 0 <= newX < n and 0 <= newY < n and grid[newX][newY] == 0:
                    q.append((newX, newY))
                    grid[newX][newY] = 1
        pathLength += 1

    return -1
```


```java
import java.util.Arrays;
import java.util.List;

public int earliestAcq(int[][] logs, int n) {
    int[] parents = new int[n];
    for (int i = 0; i < n; i++) {
        parents[i] = i;
    }

    Arrays.sort(logs, (log1, log2) -> log1[0] - log2[0]);

    int groupCount = n;
    for (int[] log : logs) {
        int rootX = find(log[1], parents);
        int rootY = find(log[2], parents);
        if (rootX != rootY) {
            parents[rootX] = rootY;
            groupCount--;
        }
        if (groupCount == 1) {
            return log[0];
        }
    }
    return -1;
}

private int find(int x, int[] parents) {
    return x == parents[x] ? x : (parents[x] = find(parents[x], parents));
}
```

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

int parent(int x, std::vector<int>& parents) {
    return x == parents[x] ? x : parents[x] = parent(parents[x], parents);
}

int earliestAcq(std::vector<std::vector<int>>& logs, int n) {
    std::vector<int> parents(n);
    for (int i = 0; i < n; ++i) parents[i] = i;

    std::sort(logs.begin(), logs.end());

    int groupCount = n;
    for (const auto& log : logs) {
        int rootX = parent(log[1], parents);
        int rootY = parent(log[2], parents);
        if (rootX != rootY) {
            parents[rootX] = rootY;
            groupCount--;
        }
        if (groupCount == 1) {
            return log[0];
        }
    }
    return -1;
}
```


```cpp
int maxScore(vector<vector<int>>& grid) {
    int m = grid.size(), n = grid[0].size();

    for (int i = 1; i < n; i++) {
        grid[0][i] = min(grid[0][i], grid[0][i - 1]);
    }

    for (int i = 1; i < m; i++) {
        grid[i][0] = min(grid[i][0], grid[i - 1][0]);

        for (int j = 1; j < n; j++) {
            grid[i][j] = max(min(grid[i - 1][j], grid[i][j]), min(grid[i][j - 1], grid[i][j]));
        }
    }

    return grid[m - 1][n - 1];
}
```

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

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

    for (int i = 1; i < m; ++i) {
        grid[i][0] = Math.min(grid[i][0], grid[i - 1][0]);

        for (int j = 1; j < n; ++j) {
            grid[i][j] = Math.max(Math.min(grid[i - 1][j], grid[i][j]),
                                  Math.min(grid[i][j - 1], grid[i][j]));
        }
    }

    return grid[m - 1][n - 1];
}
```


```java
public int[] distributeCandies(int candies, int num_people) {
    int[] result = new int[num_people];
    int i = 0, count = 1;

    while (candies > 0) {
        result[i % num_people] += Math.min(candies, count);
        candies -= count;
        count++;
        i++;
    }

    return result;
}
```

```cpp
#include <vector>

std::vector<int> distributeCandies(int candies, int num_people) {
    std::vector<int> result(num_people, 0);
    int i = 0, count = 1;

    while (candies > 0) {
        result[i % num_people] += std::min(candies, count);
        candies -= count;
        count++;
        i++;
    }

    return result;
}
```


```python
def max_uncrossed_lines(nums1, nums2):
    m, n = len(nums1), len(nums2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if nums1[i - 1] == nums2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

    return dp[m][n]
```

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

int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
    int m = nums1.size();
    int n = nums2.size();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (nums1[i - 1] == nums2[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    return dp[m][n];
}
```


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

string defangIPaddr(string address) {
    string defanged = "";
    for (char c : address) {
        if (c == '.')
            defanged += "[.]";
        else
            defanged += c;
    }
    return defanged;
}
```

```java
public String defangIPaddr(String address) {
    StringBuilder defanged = new StringBuilder();
    for (char c : address.toCharArray()) {
        if (c == '.')
            defanged.append("[.]");
        else
            defanged.append(c);
    }
    return defanged.toString();
}
```


```java
public int[] corpFlightBookings(int[][] bookings, int n) {
    int[] seats = new int[n];
    for (int[] booking : bookings) {
        seats[booking[0] - 1] += booking[2];
        if (booking[1] < n) {
            seats[booking[1]] -= booking[2];
        }
    }
    for (int i = 1; i < n; ++i) {
        seats[i] += seats[i - 1];
    }
    return seats;
}
```

```python
def corpFlightBookings(bookings, n):
    seats = [0] * n
    for booking in bookings:
        seats[booking[0] - 1] += booking[2]
        if booking[1] < n:
            seats[booking[1]] -= booking[2]
    for i in range(1, n):
        seats[i] += seats[i - 1]
    return seats
```


```cpp
bool isRobotBounded(string instructions) {
    int x = 0, y = 0, dir = 0;
    vector<vector<int>> moves {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    for (char c : instructions) {
        if (c == 'G') {
            x += moves[dir][0];
            y += moves[dir][1];
        } else if (c == 'L') {
            dir = (dir + 3) % 4;
        } else {
            dir = (dir + 1) % 4;
        }
    }

    return (x == 0 && y == 0) || dir != 0;
}
```

1234567890 algorithmchallenges aeiouAEIOU helloworld thisisanemptystring quickbrownfoxjumpsoverthelazydog ! leetcodeisacommunityforcoders

True True True True True True True True True

```python
def is_robot_bounded(instructions: str) -> bool:
    x, y, dir = 0, 0, 0
    moves = [(0, 1), (1, 0), (0, -1), (-1, 0)]

    for c in instructions:
        if c == 'G':
            x += moves[dir][0]
            y += moves[dir][1]
        elif c == 'L':
            dir = (dir + 3) % 4
        else:
            dir = (dir + 1) % 4

    return (x == 0 and y == 0) or dir != 0
```


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

int maxSumAfterPartitioning(vector<int>& arr, int k) {
    int n = arr.size();
    vector<int> dp(n + 1, 0);
    for (int i = 1; i <= n; ++i) {
        int current_max = 0;
        for (int j = 1; j <= k && i - j >= 0; ++j) {
            current_max = max(current_max, arr[i - j]);
            dp[i] = max(dp[i], dp[i - j] + current_max * j);
        }
    }
    return dp[n];
}
```

```java
public int maxSumAfterPartitioning(int[] arr, int k) {
    int n = arr.length;
    int[] dp = new int[n + 1];
    for (int i = 1; i <= n; ++i) {
        int current_max = 0;
        for (int j = 1; j <= k && i - j >= 0; ++j) {
            current_max = Math.max(current_max, arr[i - j]);
            dp[i] = Math.max(dp[i], dp[i - j] + current_max * j);
        }
    }
    return dp[n];
}
```


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

int longestWellPerformingInterval(std::vector<int> &hours) {
    int sum = 0;
    int longest = 0;
    std::unordered_map<int, int> first_sum_index;

    for (int i = 0; i < hours.size(); ++i) {
        sum += (hours[i] > 8) ? 1 : -1;
        if (sum > 0) {
            longest = i + 1;
        } else {
            if (first_sum_index.find(sum - 1) != first_sum_index.end()) {
                longest = std::max(longest, i - first_sum_index[sum - 1]);
            }
            if (first_sum_index.find(sum) == first_sum_index.end()) {
                first_sum_index[sum] = i;
            }
        }
    }
    return longest;
}
```

```python
def longestWellPerformingInterval(hours):
    sum = 0
    longest = 0
    first_sum_index = {}

    for i, hour in enumerate(hours):
        sum += 1 if hour > 8 else -1
        if sum > 0:
            longest = i + 1
        else:
            if sum - 1 in first_sum_index:
                longest = max(longest, i - first_sum_index[sum - 1])
            if sum not in first_sum_index:
                first_sum_index[sum] = i

    return longest
```


```cpp
int lastStoneWeight(vector<int>& stones) {
    priority_queue<int> pq(stones.begin(), stones.end());
    while (pq.size() > 1) {
        int x = pq.top(); pq.pop();
        int y = pq.top(); pq.pop();
        if (x != y) {
            pq.push(y - x);
        }
    }
    return pq.empty() ? 0 : pq.top();
}
```

```java
public int lastStoneWeight(int[] stones) {
    PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
    for (int stone : stones) {
        pq.add(stone);
    }
    while (pq.size() > 1) {
        int x = pq.poll();
        int y = pq.poll();
        if (x != y) {
            pq.add(y - x);
        }
    }
    return pq.isEmpty() ? 0 : pq.peek();
}
```


```java
public int maxAbsValExpr(int[] arr1, int[] arr2) {
    int result = 0;
    int[] max_sum = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};

    for (int i = 0; i < arr1.length; ++i) {
        max_sum[0] = Math.max(max_sum[0], arr1[i] + arr2[i] + i);
        max_sum[1] = Math.max(max_sum[1], arr1[i] - arr2[i] + i);
        max_sum[2] = Math.max(max_sum[2], -arr1[i] + arr2[i] + i);
        max_sum[3] = Math.max(max_sum[3], -arr1[i] - arr2[i] + i);
    }

    for (int i = 0; i < arr1.length; ++i) {
        result = Math.max(result, max_sum[0] - arr1[i] - arr2[i] - i);
        result = Math.max(result, max_sum[1] - arr1[i] + arr2[i] - i);
        result = Math.max(result, max_sum[2] + arr1[i] - arr2[i] - i);
        result = Math.max(result, max_sum[3] + arr1[i] + arr2[i] - i);
    }

    return result;
}
```

```python
def maxAbsValExpr(arr1, arr2):
    result = 0
    max_sum = [float('-inf')] * 4

    for i in range(len(arr1)):
        max_sum[0] = max(max_sum[0], arr1[i] + arr2[i] + i)
        max_sum[1] = max(max_sum[1], arr1[i] - arr2[i] + i)
        max_sum[2] = max(max_sum[2], -arr1[i] + arr2[i] + i)
        max_sum[3] = max(max_sum[3], -arr1[i] - arr2[i] + i)

    for i in range(len(arr1)):
        result = max(result, max_sum[0] - arr1[i] - arr2[i] - i)
        result = max(result, max_sum[1] - arr1[i] + arr2[i] - i)
        result = max(result, max_sum[2] + arr1[i] - arr2[i] - i)
        result = max(result, max_sum[3] + arr1[i] + arr2[i] - i)

    return result
```


```python
def is_armstrong(n: int) -> bool:
    power_sum = 0
    original = n
    k = len(str(n))
    while n > 0:
        digit = n % 10
        power_sum += digit ** k
        n //= 10
    return power_sum == original
```

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

```java
public boolean isArmstrong(int n) {
    int power_sum = 0;
    int original = n;
    int k = String.valueOf(n).length();
    while (n > 0) {
        int digit = n % 10;
        power_sum += Math.pow(digit, k);
        n /= 10;
    }
    return power_sum == original;
}
```


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

int find(std::vector<int>& parent, int x) {
    if (parent[x] != x) {
        parent[x] = find(parent, parent[x]);
    }
    return parent[x];
}

int minimumCost(int n, std::vector<std::vector<int>>& connections) {
    std::sort(connections.begin(), connections.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
        return a[2] < b[2];
    });

    std::vector<int> parent(n + 1);
    for (int i = 1; i <= n; ++i) {
        parent[i] = i;
    }

    int cost = 0;
    int edges = 0;
    for (const auto& connection : connections) {
        int root_x = find(parent, connection[0]);
        int root_y = find(parent, connection[1]);

        if (root_x != root_y) {
            parent[root_y] = root_x;
            cost += connection[2];
            edges += 1;
        }

        if (edges == n - 1) {
            break;
        }
    }

    return edges == n - 1 ? cost : -1;
}
```

```python
def find(parent, x):
    if parent[x] != x:
        parent[x] = find(parent, parent[x])
    return parent[x]

def minimumCost(n, connections):
    connections.sort(key=lambda x: x[2])

    parent = list(range(n + 1))

    cost = 0
    edges = 0
    for c in connections:
        root_x = find(parent, c[0])
        root_y = find(parent, c[1])

        if root_x != root_y:
            parent[root_y] = root_x
            cost += c[2]
            edges += 1

        if edges == n - 1:
            break

    return cost if edges == n - 1 else -1
```


```cpp
int minimumSemesters(int n, vector<vector<int>>& relations) {
    vector<int> in_degree(n + 1, 0);
    vector<vector<int>> graph(n + 1);

    for (auto& relation : relations) {
        graph[relation[0]].push_back(relation[1]);
        in_degree[relation[1]]++;
    }

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

    int semesters = 0;
    while (!q.empty()) {
        int size = q.size();
        semesters++;
        while (size--) {
            int course = q.front();
            q.pop();
            n--;

            for (int next : graph[course]) {
                if (--in_degree[next] == 0) {
                    q.push(next);
                }
            }
        }
    }

    return n == 0 ? semesters : -1;
}
```

```java
public int minimumSemesters(int n, int[][] relations) {
    int[] in_degree = new int[n + 1];
    List<List<Integer>> graph = new ArrayList<>();

    for (int i = 0; i <= n; i++) {
        graph.add(new ArrayList<>());
    }

    for (int[] relation : relations) {
        graph.get(relation[0]).add(relation[1]);
        in_degree[relation[1]]++;
    }

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

    int semesters = 0;
    while (!q.isEmpty()) {
        int size = q.size();
        semesters++;
        for (int i = 0; i < size; i++) {
            int course = q.poll();
            n--;

            for (int next : graph.get(course)) {
                if (--in_degree[next] == 0) {
                    q.offer(next);
                }
            }
        }
    }

    return n == 0 ? semesters : -1;
}
```


```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 <algorithm>
#include <vector>

int heightChecker(std::vector<int>& heights) {
    std::vector<int> expected = heights;
    std::sort(expected.begin(), expected.end());
    int count = 0;
    for (size_t i = 0; i < heights.size(); i++) {
        if (heights[i] != expected[i]) {
            count++;
        }
    }
    return count;
}
```


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

std::vector<int> prevPermOpt1(std::vector<int>& arr) {
    int n = arr.size();
    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++;
            std::swap(arr[i], arr[j - 1]);
            return arr;
        }
    }
    return arr;
}
```

```python
def prev_perm_opt1(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]
            return arr
    return arr
```


```cpp
int longestCommonSubsequence(string text1, string text2) {
    int m = text1.size();
    int n = text2.size();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1));
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (text1[i - 1] == text2[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    return dp[m][n];
}
```

```java
public int longestCommonSubsequence(String text1, String text2) {
    int m = text1.length();
    int n = text2.length();
    int[][] dp = new int[m + 1][n + 1];
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    return dp[m][n];
}
```


```cpp
int movesToMakeZigzag(std::vector<int>& nums) {
    int evenMoves = 0, oddMoves = 0;
    for (int i = 0; i < nums.size(); i++) {
        int left = i > 0 ? nums[i - 1] : 1001;
        int right = i < nums.size() - 1 ? nums[i + 1] : 1001;
        int minValue = std::min(left, right);
        if (nums[i] >= minValue) {
            if (i % 2 == 0) {
                evenMoves += nums[i] - minValue + 1;
            } else {
                oddMoves += nums[i] - minValue + 1;
            }
        }
    }
    return std::min(evenMoves, oddMoves);
}
```

```java
public int movesToMakeZigzag(int[] nums) {
    int evenMoves = 0, oddMoves = 0;
    for (int i = 0; i < nums.length; i++) {
        int left = i > 0 ? nums[i - 1] : 1001;
        int right = i < nums.length - 1 ? nums[i + 1] : 1001;
        int minValue = Math.min(left, right);
        if (nums[i] >= minValue) {
            if (i % 2 == 0) {
                evenMoves += nums[i] - minValue + 1;
            } else {
                oddMoves += nums[i] - minValue + 1;
            }
        }
    }
    return Math.min(evenMoves, oddMoves);
}
```


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

def btree_game_winning_move(root: TreeNode, n: int, x: int) -> bool:
    def count_nodes(node: TreeNode) -> int:
        if not node:
            return 0
        return count_nodes(node.left) + count_nodes(node.right) + 1

    def find_node(node: TreeNode, x: int) -> TreeNode:
        if not node:
            return None
        if node.val == x:
            return node
        left_search = find_node(node.left, x)
        if left_search:
            return left_search
        return find_node(node.right, x)

    x_node = find_node(root, x)
    left_nodes = count_nodes(x_node.left)
    right_nodes = count_nodes(x_node.right)
    parent_nodes = n - left_nodes - right_nodes - 1

    return max(max(left_nodes, right_nodes), parent_nodes) > n // 2
```

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

```cpp
#include <algorithm>
#include <cstdlib>
#include <bits/stdc++.h>
using namespace std;

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

int countNodes(TreeNode* node) {
    if (!node) return 0;
    return countNodes(node->left) + countNodes(node->right) + 1;
}

bool btreeGameWinningMove(TreeNode* root, int n, int x) {
    TreeNode* xNode = findNode(root, x);
    int leftNodes = countNodes(xNode->left);
    int rightNodes = countNodes(xNode->right);
    int parentNodes = n - leftNodes - rightNodes - 1;

    return max(max(leftNodes, rightNodes), parentNodes) > n / 2;
}

TreeNode* findNode(TreeNode* node, int x) {
    if (!node) return nullptr;
    if (node->val == x) return node;
    TreeNode* leftSearch = findNode(node->left, x);
    if (leftSearch) return leftSearch;
    return findNode(node->right, x);
}
```


```python
from collections import defaultdict

def maxEqualRowsAfterFlips(matrix):
    count = defaultdict(int)
    for row in matrix:
        row_str = "".join(str(row[0] ^ val) for val in row)
        count[row_str] += 1
    return max(count.values())
```

text =  "ghiabcdefhelloadamhelloabcdefghi "

iiiii
ghiaaaaaaaaa
aabcbbccaa
yyyyy
aaabbbccc
aabccbbcca
aaaaabbbb
aabn```
ghiaaabababababab
mmmmm
merchant
aabcccbb
jjjjj
antaprezatepzapreanta
aaaa
ttttt
ghiaabcabcabc
hhhhh
xxxxx
ghiabcdeffghhiij
bbbbb
kkkkk
azaazaza
ddddd
bbbbaaaa
ghiggggeeeegg
aabcbccbaa
ppppp
ggggg
ooooo
rrrrr
ghiabcdefhelloadamhelloabcdefghi
uuuuu
nnnnn
aabcccbbca
ccbbbaaaa
eeeee
ghi123456123456
lllll
ccccaaaa
aabcbccc
aabcbb
aabcbbcca
abcdabcdabcd
ccccc
ghihello worldhello world
fffff
wwwww
zzzzz
zzzzzzzzz
ghiaabbcc
aabcccccbb
vvvvv
aaabcccbba
aabccbb
ghiabcdefhelloadamhelloabcdefghi
xyxyxyxyxy
aabc
sssss
qqqqq

```cpp
int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
    unordered_map<string, int> count;
    for (auto& row : matrix) {
        string row_str;
        if (row[0] == 1) {
            for (int val : row)
                row_str += '0' + 1 - val;
        } else {
            for (int val : row)
                row_str += '0' + val;
        }
        count[row_str]++;
    }
    int res = 0;
    for (auto& [key, value] : count)
        res = max(res, value);
    return res;
}
```


```java
public int minSwaps(int[] data) {
    int ones = 0;
    for (int d : data) {
        ones += d;
    }
    int cur_ones = 0, max_ones = 0;
    for (int i = 0; i < data.length; i++) {
        cur_ones += data[i];
        if (i >= ones) {
            cur_ones -= data[i - ones];
        }
        max_ones = Math.max(max_ones, cur_ones);
    }
    return ones - max_ones;
}
```

```cpp
int minSwaps(vector<int>& data) {
    int ones = 0;
    for (int d : data) {
        ones += d;
    }
    int cur_ones = 0, max_ones = 0;
    for (int i = 0; i < data.size(); i++) {
        cur_ones += data[i];
        if (i >= ones) {
            cur_ones -= data[i - ones];
        }
        max_ones = max(max_ones, cur_ones);
    }
    return ones - max_ones;
}
```


```java
import java.util.*;

class Solution {
    public List<String> mostVisitedPattern(String[] username, int[] timestamp, String[] website) {
        int n = username.length;
        List<String[]> visitingOrder = new ArrayList<>();
        HashMap<String, List<Tuple<Integer, Integer>>> userVisits = new HashMap<>();

        for (int i = 0; i < n; i++) {
            userVisits.putIfAbsent(username[i], new ArrayList<>());
            userVisits.get(username[i]).add(new Tuple<>(timestamp[i], i));
        }

        for (Map.Entry<String, List<Tuple<Integer, Integer>>> entry : userVisits.entrySet()) {
            Collections.sort(entry.getValue(), (a, b) -> a.x - b.x);
            int m = entry.getValue().size();
            for (int i = 0; i < m; i++) {
                for (int j = i + 1; j < m; j++) {
                    for (int k = j + 1; k < m; k++) {
                        visitingOrder.add(new String[] {website[entry.getValue().get(i).y], website[entry.getValue().get(j).y], website[entry.getValue().get(k).y]});
                    }
                }
            }
        }

        Collections.sort(visitingOrder, (a, b) -> {
           for (int i = 0; i < 3; i++) {
               int cmp = a[i].compareTo(b[i]);
               if (cmp != 0) {
                   return cmp;
               }
           }
           return 0;
        });

        List<String> ans = Arrays.asList(visitingOrder.get(0));
        int maxScore = 0, score = 1;

        for (int i = 1; i < visitingOrder.size(); i++) {
            if (Arrays.equals(visitingOrder.get(i), visitingOrder.get(i - 1))) {
                score++;
            } else {
                score = 1;
            }

            if (score > maxScore) {
                maxScore = score;
                ans = Arrays.asList(visitingOrder.get(i));
            }
        }

        return ans;
    }

    private static class Tuple<X, Y> {
        X x;
        Y y;

        Tuple(X x, Y y) {
            this.x = x;
            this.y = y;
        }
    }
}
```

username = \[ "joe ", "joe ", "joe ", "james ", "james ", "james ", "james ", "mary ", "mary ", "mary "\], timestamp = \[1,2,3,4,5,6,7,8,9,10\], website = \[ "home ", "about ", "career ", "home ", "cart ", "maps ", "home ", "home ", "about ", "career "\]

["same", "same", "same"]
[1,2,3]
["pattern", "pattern", "pattern"]

["joe ", "joe ", "joe ", "james ", "james ", "james ", "james ", "mary ", "mary ", "mary "]
[1,2,3,4,5,6,7,8,9,10]
["home ", "home ", "home ", "about ", "about ", "cart ", "career ", "career ", "maps ", "home "]

["user", "user", "user", "other"]
[1,2,3,4]
["page", "page", "different", "page"]

[ "joe ", "joe ", "joe ", "james ", "james ", "james ", "james ", "mary ", "mary ", "mary "]
[1,2,3,4,5,6,7,8,9,10]
[ "home ", "about ", "career ", "home ", "cart ", "maps ", "home ", "home ", "about ", "career "]

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

class Solution:
    def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]:
        n = len(username)
        visits = defaultdict(list)

        # user_visits: {user: [(timestamp, website),...]}
        for i in range(n):
            visits[username[i]].append((timestamp[i], website[i]))

        for user in visits:
            visits[user].sort()

        patterns = defaultdict(int)

        for user in visits:
            websites = [web for _, web in visits[user]]
            patterns_set = set(combinations(websites, 3))

            for pattern in patterns_set:
                patterns[pattern] += 1

        patterns = sorted(patterns.items(), key=lambda x: (-x[1], x[0]))

        return list(patterns[0][0])
```


```cpp
bool canConvert(std::string str1, std::string str2) {
    if (str1 == str2) return true;
    std::unordered_map<char, char> conversion;
    for (int i = 0; i < str1.length(); ++i) {
        if (conversion.count(str1[i]) && conversion[str1[i]] != str2[i]) return false;
        conversion[str1[i]] = str2[i];
    }
    return std::unordered_set<char>(str2.begin(), str2.end()).size() < 26;
}
```

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

```python
def canConvert(str1, str2):
    if str1 == str2: return True;
    conversion = {}
    for c1, c2 in zip(str1, str2):
        if c1 in conversion and conversion[c1] != c2: return False
        conversion[c1] = c2
    return len(set(str2)) < 26
```


```java
public int dayOfYear(String date) {
    int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int year = Integer.parseInt(date.substring(0, 4));
    int month = Integer.parseInt(date.substring(5, 7));
    int day = Integer.parseInt(date.substring(8, 10));

    if (isLeapYear(year)) {
        daysInMonth[1] = 29;
    }

    int result = 0;
    for (int i = 0; i < month - 1; ++i) {
        result += daysInMonth[i];
    }

    return result + day;
}

public boolean isLeapYear(int year) {
    return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
```

```python
def is_leap_year(year: int) -> bool:
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

def day_of_year(date: str) -> int:
    days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    year, month, day = int(date[:4]), int(date[5:7]), int(date[8:])

    if is_leap_year(year):
        days_in_month[1] = 29

    return sum(days_in_month[:month-1]) + day
```


```java
public int numRollsToTarget(int n, int k, int target) {
    int MOD = 1000000007;
    int[][] dp = new int[n + 1][target + 1];
    dp[0][0] = 1;
    for (int i = 1; i <= n; i++) {
        for (int j = i; j <= target; j++) {
            for (int d = 1; d <= k && j - d >= 0; d++) {
                dp[i][j] = (dp[i][j] + dp[i - 1][j - d]) % MOD;
            }
        }
    }
    return dp[n][target];
}
```

```cpp
int numRollsToTarget(int n, int k, int target) {
    const int MOD = 1e9 + 7;
    vector<vector<int>> dp(n + 1, vector<int>(target + 1, 0));
    dp[0][0] = 1;
    for (int i = 1; i <= n; ++i) {
        for (int j = i; j <= target; ++j) {
            for (int d = 1; d <= k && j - d >= 0; ++d) {
                dp[i][j] = (dp[i][j] + dp[i - 1][j - d]) % MOD;
            }
        }
    }
    return dp[n][target];
}
```


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

def maxLevelSum(root):
    if not root: return 0

    q = [root]
    level, max_sum, result_level = 0, float('-inf'), 0

    while q:
        qlen, sum = len(q), 0
        level += 1

        for i in range(qlen):
            temp = q.pop(0)
            sum += temp.val

            if temp.left: q.append(temp.left)
            if temp.right: q.append(temp.right)

        if sum > max_sum:
            max_sum = sum
            result_level = level

    return result_level
```

```cpp
#include <queue>

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

int maxLevelSum(TreeNode* root) {
    if (!root) return 0;

    std::queue<TreeNode*> q;
    q.push(root);
    int level = 0, max_sum = INT_MIN, result_level;

    while (!q.empty()) {
        int count = q.size();
        int sum = 0;
        level++;

        while (count--) {
            TreeNode* temp = q.front(); q.pop();
            sum += temp->val;

            if (temp->left) q.push(temp->left);
            if (temp->right) q.push(temp->right);
        }

        if (sum > max_sum) {
            max_sum = sum;
            result_level = level;
        }
    }

    return result_level;
}
```


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

int maxDistance(std::vector<std::vector<int>>& grid) {
    int distance = -1;
    std::queue<std::pair<int, int>> waterCells;
    int n = grid.size();

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (grid[i][j] == 1) {
                waterCells.push({i, j});
            }
        }
    }

    if (waterCells.size() == 0 || waterCells.size() == n * n) {
        return distance;
    }

    std::vector<std::vector<int>> directions{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    while (!waterCells.empty()) {
        int size = waterCells.size();
        while (size--) {
            auto [x, y] = waterCells.front();
            waterCells.pop();

            for (const auto& dir : directions) {
                int newX = x + dir[0], newY = y + dir[1];
                if (newX >= 0 && newX < n && newY >= 0 && newY < n && grid[newX][newY] == 0) {
                    grid[newX][newY] = 1;
                    waterCells.push({newX, newY});
                }
            }
        }
        distance++;
    }

    return distance - 1;
}
```

```python
from collections import deque

def maxDistance(grid):
    distance = -1
    water_cells = deque()
    n = len(grid)

    for i in range(n):
        for j in range(n):
            if grid[i][j] == 1:
                water_cells.append((i, j))

    if not water_cells or len(water_cells) == n * n:
        return distance

    directions = ((0, 1), (0, -1), (1, 0), (-1, 0))

    while water_cells:
        size = len(water_cells)
        for _ in range(size):
            x, y = water_cells.popleft()
            for dx, dy in directions:
                newX, newY = x + dx, y + dy
                if 0 <= newX < n and 0 <= newY < n and grid[newX][newY] == 0:
                    grid[newX][newY] = 1
                    water_cells.append((newX, newY))
        distance += 1

    return distance - 1
```


```cpp
int calculateTime(std::string keyboard, std::string word) {
    int time = 0;
    int prev_index = 0;
    std::unordered_map<char, int> char_to_index;

    for (int i = 0; i < keyboard.length(); i++) {
        char_to_index[keyboard[i]] = i;
    }

    for (char c : word) {
        time += std::abs(char_to_index[c] - prev_index);
        prev_index = char_to_index[c];
    }

    return time;
}
```

keyboard =  "abcdefghijklmnopqrstuvwxyz ", word =  "cba "

```java
public int calculateTime(String keyboard, String word) {
    int time = 0;
    int prevIndex = 0;
    Map<Character, Integer> charToIndex = new HashMap<>();

    for (int i = 0; i < keyboard.length(); i++) {
        charToIndex.put(keyboard.charAt(i), i);
    }

    for (char c : word.toCharArray()) {
        time += Math.abs(charToIndex.get(c) - prevIndex);
        prevIndex = charToIndex.get(c);
    }

    return time;
}
```


```python
import heapq

def connectSticks(sticks):
    heapq.heapify(sticks)
    cost = 0
    while len(sticks) > 1:
        first = heapq.heappop(sticks)
        second = heapq.heappop(sticks)
        cost += first + second
        heapq.heappush(sticks, first + second)
    return cost
```

```java
import java.util.PriorityQueue;

public int connectSticks(int[] sticks) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();

    for (int stick : sticks) {
        minHeap.offer(stick);
    }

    int cost = 0;
    while (minHeap.size() > 1) {
        int first = minHeap.poll();
        int second = minHeap.poll();
        cost += first + second;
        minHeap.offer(first + second);
    }
    return cost;
}
```


```cpp
#include <iostream>
#include <vector>

std::string shortest_common_supersequence(std::string str1, std::string str2) {
    int m = str1.length();
    int n = str2.length();
    std::vector<std::vector<int>> dp(m + 1, std::vector<int>(n + 1));

    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0) {
                dp[i][j] = j;
            }
            else if (j == 0) {
                dp[i][j] = i;
            }
            else if (str1[i - 1] == str2[j - 1]) {
                dp[i][j] = 1 + dp[i - 1][j - 1];
            }
            else {
                dp[i][j] = 1 + std::min(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }

    int i = m, j = n;
    std::string result;

    while (i > 0 && j > 0) {
        if (str1[i - 1] == str2[j - 1]) {
            result.push_back(str1[i - 1]);
            i--;
            j--;
        }
        else if (dp[i - 1][j] > dp[i][j - 1]) {
            j--;
            result.push_back(str2[j]);
        }
        else {
            i--;
            result.push_back(str1[i]);
        }
    }

    while (i > 0) {
        result.push_back(str1[i - 1]);
        i--;
    }

    while (j > 0) {
        result.push_back(str2[j - 1]);
        j--;
    }

    std::reverse(result.begin(), result.end());
    return result;
}
```

queries = \[ "cbd "\], words = \[ "zaaaz "\]

["aaabbb"]
["aab", "bba", "baa", "aaa", "bbb"]

bzczdzaezaz
bca
aabbbabaaaaabbbaaabbb
xyyxykxxmxyz
zaaazcbd
zaaaz cbd
defghiabc
zzzz
deghab
abcdfabcffabcde
eeeeeeeeeeeeeee
xxyxxkxxmxzz

```python
def shortest_common_supersequence(str1, str2):
    m, n = len(str1), len(str2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(m + 1):
        for j in range(n + 1):
            if i == 0:
                dp[i][j] = j
            elif j == 0:
                dp[i][j] = i
            elif str1[i - 1] == str2[j - 1]:
                dp[i][j] = 1 + dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1])

    i, j = m, n
    result = []

    while i > 0 and j > 0:
        if str1[i - 1] == str2[j - 1]:
            result.append(str1[i - 1])
            i -= 1
            j -= 1
        elif dp[i - 1][j] > dp[i][j - 1]:
            j -= 1
            result.append(str2[j])
        else:
            i -= 1
            result.append(str1[i])

    while i > 0:
        i -= 1
        result.append(str1[i])

    while j > 0:
        j -= 1
        result.append(str2[j])

    return "".join(result[::-1])
```


```java
public int numPrimeArrangements(int n) {
    boolean[] isPrime = new boolean[n + 1];
    Arrays.fill(isPrime, true);
    isPrime[0] = false;
    isPrime[1] = false;
    for (int i = 2; i * i <= n; i++) {
        if (isPrime[i]) {
            for (int j = i * i; j <= n; j += i) {
                isPrime[j] = false;
            }
        }
    }

    int primeCount = 0;
    for (int i = 2; i <= n; i++) {
        if (isPrime[i]) primeCount++;
    }
    int compositeCount = n - primeCount;

    long res = 1;
    int MOD = 1000000007;
    for (int i = 1; i <= primeCount; i++) {
        res = res * i % MOD;
    }
    for (int i = 1; i <= compositeCount; i++) {
        res = res * i % MOD;
    }
    return (int) res;
}
```

```python
def numPrimeArrangements(n: int) -> int:
    def is_prime(num):
        if num < 2:
            return False
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                return False
        return True

    prime_count = sum(1 for i in range(2, n + 1) if is_prime(i))
    composite_count = n - prime_count

    MOD = 10**9 + 7
    res = 1
    for i in range(1, prime_count + 1):
        res = res * i % MOD
    for i in range(1, composite_count + 1):
        res = res * i % MOD

    return res
```


```java
import java.util.*;

public List<Integer> findNumOfValidWords(String[] words, String[] puzzles) {
    List<Integer> result = new ArrayList<>();
    for (String puzzle : puzzles) {
        int count = 0;
        Set<Character> puzzleSet = new HashSet<>();
        for (char c : puzzle.toCharArray()) {
            puzzleSet.add(c);
        }
        for (String word : words) {
            if (word.indexOf(puzzle.charAt(0)) >= 0) {
                if (word.chars().allMatch(c -> puzzleSet.contains((char) c))) {
                    count++;
                }
            }
        }
        result.add(count);
    }
    return result;
}
```

words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\]

["bee ", "bee ", "bee ", "bee ", "bee ", "bee ", "bee ", "bee ", "bee ", "bee ", "bee ", "bee "]
["beexz ", "beexz ", "beexz ", "beexz ", "beexz "]

["able", "ale", "apple", "bale", "kale"]
[]

["ace ", "ace ", "ace ", "ace ", "ace ", "ace ", "ace ", "ace ", "ace ", "ace ", "ace ", "ace "]
["acegkz ", "acegz ", "acegz ", "acegz ", "acegz "]

["beg ", "beg ", "beg ", "beg ", "beg ", "beg ", "beg ", "beg ", "beg ", "beg ", "beg ", "beg "]
["begyz ", "begyz ", "begyz ", "begyz ", "begyz "]

["app ", "ape ", "ape ", "ape ", "ape ", "ape ", "ape ", "ape ", "ape ", "ape ", "ape ", "ape "]
["appez ", "appez ", "appez ", "appez ", "appez "]

["bew ", "bew ", "bew ", "bew ", "bew ", "bew ", "bew ", "bew ", "bew ", "bew ", "bew ", "bew "]
["bewxz ", "bewxz ", "bewxz ", "bewxz ", "bewxz "]

["bet ", "bet ", "bet ", "bet ", "bet ", "bet ", "bet ", "bet ", "bet ", "bet ", "bet ", "bet "]
["betyz ", "betyz ", "betyz ", "betyz ", "betyz "]

["bad ", "bad ", "bad ", "bad ", "bad ", "bad ", "bad ", "bad ", "bad ", "bad ", "bad ", "bad "]
["badfz ", "badfz ", "badfz ", "badfz ", "badfz "]

["batt ", "att ", "tan ", "nat ", "tac ", "act ", "cat ", "bat ", "tac ", "act ", "cat "]
["battyz ", "tacz ", "nattyz ", "battz ", "attz "]

["ade ", "ade ", "ade ", "ade ", "ade ", "ade ", "ade ", "ade ", "ade ", "ade ", "ade ", "ade "]
["adehz ", "adehz ", "adehz ", "adehz ", "adehz "]

["xyz", "yzz", "zzz"]
["abcde", "vwxyz"]

["bed ", "bed ", "bed ", "bed ", "bed ", "bed ", "bed ", "bed ", "bed ", "bed ", "bed ", "bed "]
["bedvz ", "bedvz ", "bedvz ", "bedvz ", "bedvz "]

[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "]
[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "]

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

std::vector<int> findNumOfValidWords(std::vector<std::string>& words, std::vector<std::string>& puzzles) {
    std::vector<int> result;
    for (const std::string& puzzle : puzzles) {
        int count = 0;
        std::unordered_set<char> puzzleSet(puzzle.begin(), puzzle.end());
        for (const std::string& word : words) {
            if (word.find(puzzle[0]) != std::string::npos) {
                if (std::all_of(word.begin(), word.end(), [&](char c) { return puzzleSet.count(c) > 0; })) {
                    count++;
                }
            }
        }
        result.push_back(count);
    }
    return result;
}
```


```python
from collections import defaultdict

def beforeAndAfterPuzzles(phrases):
    first_word_map = defaultdict(set)
    result = set()

    for phrase in phrases:
        first_word = phrase.split(' ')[0]
        first_word_map[first_word].add(phrase)

    for phrase in phrases:
        last_word = phrase.split(' ')[-1]
        if last_word in first_word_map:
            for cur_phrase in first_word_map[last_word]:
                if phrase != cur_phrase:
                    result.add(phrase + cur_phrase[cur_phrase.index(' '):])

    return sorted(list(result))
```

phrases = \[ "writing code ", "code rocks "\]

data structure
structures and algorithms

consecutive spaces not allowed
not allowed to use

[apple pie chart]
[]
[]
[spring framework development]
[hello world of coding]
[]
[empty phrase with nothing]
[single word power]
[blue sky diving]

```java
import java.util.*;

public List<String> beforeAndAfterPuzzles(String[] phrases) {
    Map<String, Set<String>> firstWordMap = new HashMap<>();
    Set<String> result = new TreeSet<>();

    for (String phrase : phrases) {
        String firstWord = phrase.substring(0, phrase.indexOf(' '));
        firstWordMap.putIfAbsent(firstWord, new HashSet<>());
        firstWordMap.get(firstWord).add(phrase);
    }

    for (String phrase : phrases) {
        String lastWord = phrase.substring(phrase.lastIndexOf(' ') + 1);
        if (firstWordMap.containsKey(lastWord)) {
            for (String curPhrase : firstWordMap.get(lastWord)) {
                if (!phrase.equals(curPhrase)) {
                    result.add(phrase + curPhrase.substring(curPhrase.indexOf(' ')));
                }
            }
        }
    }

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


```python
def shortestDistance(colors, queries):
    result = []
    positions = [[] for _ in range(3)]

    for i, color in enumerate(colors):
        positions[color - 1].append(i)

    for query in queries:
        index_positions = positions[query[1] - 1]

        if not index_positions:
            result.append(-1)
        else:
            dist = float('inf')

            for pos in index_positions:
                dist = min(dist, abs(pos - query[0]))

            result.append(dist)

    return result
```

```cpp
#include<vector>

std::vector<int> shortestDistance(std::vector<int>& colors, std::vector<std::vector<int>>& queries) {
    std::vector<int> result;
    std::vector<std::vector<int>> positions(3);

    for(int i = 0; i < colors.size(); i++) {
        positions[colors[i] - 1].push_back(i);
    }

    for(auto &query : queries) {
        auto &index_positions = positions[query[1] - 1];

        if (index_positions.empty()) {
            result.push_back(-1);
        } else {
            int dist = INT_MAX;

            for (auto pos : index_positions) {
                dist = std::min(dist, std::abs(pos - query[0]));
            }

            result.push_back(dist);
        }
    }

    return result;
}
```


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

public boolean carPooling(int[][] trips, int capacity) {
    Map<Integer, Integer> stops = new TreeMap<>();
    for (int[] t : trips) {
        stops.put(t[1], stops.getOrDefault(t[1], 0) + t[0]);
        stops.put(t[2], stops.getOrDefault(t[2], 0) - t[0]);
    }
    for (int passengers : stops.values()) {
        capacity -= passengers;
        if (capacity < 0) {
            return false;
        }
    }
    return true;
}
```

distance = \[1,2,3,4\], start = 0, destination = 1

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

bool carPooling(std::vector<std::vector<int>>& trips, int capacity) {
    std::vector<int> stops(1001, 0);
    for (const std::vector<int>& t : trips) {
        stops[t[1]] += t[0];
        stops[t[2]] -= t[0];
    }
    for (int i = 0; i < stops.size(); ++i) {
        capacity -= stops[i];
        if (capacity < 0) {
            return false;
        }
    }
    return true;
}
```


```java
import java.time.LocalDate;

public String dayOfTheWeek(int day, int month, int year) {
    LocalDate date = LocalDate.of(year, month, day);
    int dayOfWeekIndex = date.getDayOfWeek().getValue() % 7;
    String[] days = {"Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "};
    return days[dayOfWeekIndex];
}
```

Monday Thursday Sunday Thursday Friday Friday Wednesday Friday Tuesday Sunday Friday Monday Thursday Saturday Friday Thursday Thursday Friday Tuesday Wednesday Sunday Thursday Friday Wednesday Saturday Wednesday Sunday Friday Sunday Thursday Saturday Sunday Wednesday Saturday Thursday Thursday Wednesday Saturday Friday Saturday Thursday Sunday Sunday Wednesday Wednesday Wednesday Friday

```python
def day_of_the_week(day, month, year):
    from datetime import date
    days = ["Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "]
    return days[date(year, month, day).weekday()]
```


```cpp
int maxNumberOfBalloons(string text) {
    int letter_count[5] = {0};
    for (char c : text) {
        if (c == 'b') letter_count[0]++;
        if (c == 'a') letter_count[1]++;
        if (c == 'l') letter_count[2]++;
        if (c == 'o') letter_count[3]++;
        if (c == 'n') letter_count[4]++;
    }
    letter_count[2] /= 2;
    letter_count[3] /= 2;
    return *min_element(letter_count, letter_count + 5);
}
```

aobnaloonl balon bballoonalo lbnaoolon lnbaoolona bnanooloa loonbalxballpoon baloonalob loonbalxballpoon aloonballnol leetcode abloonoln baloonblon aabbccddeeffg lnoloonbalo bloonbanol nlaebolko lbaloonaol nlobaoloon balloonballoon bloobonolna aloonblon nnnllllaaaaoo aloonballon allobnaloona baloonalnob baloonnolba nlaebolko baloonblona baloonbalon lboonbalon nbaooloal lnbaloonalo llloooonn ballbaloon ballnolbao balloonloonballoon ballnoloon bbaallloooonn lloonbaloon bloonballon alonobloona baloonballoon blloon aloonbloon ballnaloona bloonbalo nlaebolko aloonalobnal baloonoolnb blooobnolna

```python
def max_number_of_balloons(text: str) -> int:
    letter_count = [0] * 5
    for c in text:
        if c == 'b': letter_count[0] += 1
        if c == 'a': letter_count[1] += 1
        if c == 'l': letter_count[2] += 1
        if c == 'o': letter_count[3] += 1
        if c == 'n': letter_count[4] += 1
    letter_count[2] //= 2
    letter_count[3] //= 2
    return min(letter_count)
```


```python
def reverseParentheses(s: str) -> str:
    stack = []
    for i, c in enumerate(s):
        if c == '(':
            stack.append(i)
        elif c == ')':
            start, end = stack.pop(), i
            # reversal of the substring
            s = s[:start] + s[start+1:end][::-1] + s[end+1:]
    return ''.join(c for c in s if c.isalpha())
```

```java
import java.util.Stack;

public String reverseParentheses(String s) {
    Stack<Integer> stack = new Stack<>();
    StringBuilder result = new StringBuilder(s);
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '(') {
            stack.push(i);
        } else if (s.charAt(i) == ')') {
            int start = stack.pop();
            int end = i;
            result.replace(start, end + 1, new StringBuilder(s.substring(start + 1, end)).reverse().toString());
            s = result.toString();
            i -= 2;
        }
    }
    for (int i = 0; i < result.length(); i++) {
        if (result.charAt(i) == '(' || result.charAt(i) == ')') {
            result.deleteCharAt(i);
            i--;
        }
    }
    return result.toString();
}
```


```java
public int kConcatenationMaxSum(int[] arr, int k) {
    long mod = (long) 1e9 + 7, n = arr.length;
    long sum = 0, maxSum = 0, tempSum = 0, maxLeft = 0, maxRight = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
        tempSum += arr[i];
        maxSum = Math.max(maxSum, tempSum);
        tempSum = Math.max(0, tempSum);
        maxLeft = Math.max(maxLeft, sum);
    }

    long temp = sum;
    for (int i = n - 1; i >= 0; i--) {
        temp -= arr[i];
        maxRight = Math.max(maxRight, temp);
    }

    long ans = Math.max(maxSum, maxLeft + maxRight + sum * (k - 2));
    return (int) (ans % mod);
}
```

```python
def kConcatenationMaxSum(arr, k):
    mod = 10**9 + 7
    n = len(arr)
    max_sum, max_left, max_right = 0, 0, 0
    total_sum = sum(arr)
    temp_sum = 0

    for i in range(n):
        temp_sum += arr[i]
        max_sum = max(max_sum, temp_sum)
        temp_sum = max(0, temp_sum)
        max_left = max(max_left, temp_sum)

    temp = total_sum
    for i in range(n - 1, -1, -1):
        temp -= arr[i]
        max_right = max(max_right, temp)

    ans = max(max_sum, max_left + max_right + total_sum * (k - 2), 0)
    return ans % mod
```


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

public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
    List<List<Integer>> result = new ArrayList<>();
    Map<Integer, List<Integer>> graph = new HashMap<>();
    for (List<Integer> connection : connections) {
        graph.putIfAbsent(connection.get(0), new ArrayList<>());
        graph.putIfAbsent(connection.get(1), new ArrayList<>());
        graph.get(connection.get(0)).add(connection.get(1));
        graph.get(connection.get(1)).add(connection.get(0));
    }
    int[] rank = new int[n];
    for (int i = 0; i < n; i++) {
        rank[i] = -1;
    }
    dfs(0, -1, 0, rank, graph, result);
    return result;
}

private void dfs(int node, int parent, int depth, int[] rank, Map<Integer, List<Integer>> graph, List<List<Integer>> result) {
    rank[node] = depth;
    for (int neighbor : graph.get(node)) {
        if (neighbor == parent) {
            continue;
        }
        if (rank[neighbor] == -1) {
            dfs(neighbor, node, depth + 1, rank, graph, result);
        }
        rank[node] = Math.min(rank[node], rank[neighbor]);
        if (rank[neighbor] == depth + 1) {
            result.add(List.of(node, neighbor));
        }
    }
}
```

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

using namespace std;

void dfs(int node, int parent, int depth, vector<int>& rank, unordered_map<int, vector<int>>& graph, vector<vector<int>>& result) {
    rank[node] = depth;
    for (const int& neighbor : graph[node]) {
        if (neighbor == parent) {
            continue;
        }
        if (rank[neighbor] == -1) {
            dfs(neighbor, node, depth + 1, rank, graph, result);
        }
        rank[node] = min(rank[node], rank[neighbor]);
        if (rank[neighbor] == depth + 1) {
            result.push_back({node, neighbor});
        }
    }
}

vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
    vector<vector<int>> result;
    unordered_map<int, vector<int>> graph;
    for (const vector<int>& connection : connections) {
        graph[connection[0]].push_back(connection[1]);
        graph[connection[1]].push_back(connection[0]);
    }
    vector<int> rank(n, -1);
    dfs(0, -1, 0, rank, graph, result);
    return result;
}
```


```python
def minHeightShelves(books, shelfWidth):
    n = len(books)
    dp = [1000000] * (n + 1)
    dp[0] = 0

    for i in range(1, n + 1):
        width = 0
        height = 0
        j = i
        while j >= 1:
            width += books[j - 1][0]
            height = max(height, books[j - 1][1])

            if width <= shelfWidth:
                dp[i] = min(dp[i], dp[j - 1] + height)
            j -= 1

    return dp[n]
```

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

int minHeightShelves(std::vector<std::vector<int>>& books, int shelfWidth) {
    int n = books.size();
    std::vector<int> dp(n + 1, 1000000);
    dp[0] = 0;

    for (int i = 1; i <= n; ++i) {
        int width = 0, height = 0;
        for (int j = i; j >= 1; --j) {
            width += books[j - 1][0];
            height = std::max(height, books[j - 1][1]);

            if (width <= shelfWidth)
                dp[i] = std::min(dp[i], dp[j - 1] + height);
        }
    }

    return dp[n];
}
```


```java
public int smallestCommonElement(int[][] mat) {
    HashMap<Integer, Integer> counts = new HashMap<>();
    for (int[] row : mat) {
        for (int num : row) {
            counts.put(num, counts.getOrDefault(num, 0) + 1);
            if (counts.get(num) == mat.length) {
                return num;
            }
        }
    }
    return -1;
}
```

```cpp
int smallestCommonElement(vector<vector<int>>& mat) {
    unordered_map<int, int> counts;
    for (const auto& row : mat) {
        for (int num : row) {
            ++counts[num];
            if (counts[num] == mat.size()) {
                return num;
            }
        }
    }
    return -1;
}
```


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

int minBuildTime(std::vector<int>& blocks, int split) {
    std::priority_queue<int, std::vector<int>, greater<int>> pq(blocks.begin(), blocks.end());

    while (pq.size() > 1) {
        int a = pq.top();
        pq.pop();
        int b = pq.top();
        pq.pop();
        pq.push(b + split);
    }

    return pq.top();
}
```

```java
import java.util.PriorityQueue;

public int minBuildTime(int[] blocks, int split) {
    PriorityQueue<Integer> pq = new PriorityQueue<>();

    for (int block : blocks) {
        pq.add(block);
    }

    while (pq.size() > 1) {
        int a = pq.poll();
        int b = pq.poll();
        pq.add(b + split);
    }

    return pq.poll();
}
```


```python
from typing import List

def minimumAbsDifference(arr: List[int]) -> List[List[int]]:
    arr.sort()
    min_diff = min(arr[i] - arr[i - 1] for i in range(1, len(arr)))

    result = []
    for i in range(1, len(arr)):
        if arr[i] - arr[i - 1] == min_diff:
            result.append([arr[i - 1], arr[i]])

    return result
```

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

public List<List<Integer>> minimumAbsDifference(int[] arr) {
    Arrays.sort(arr);
    int minDiff = Integer.MAX_VALUE;
    for (int i = 1; i < arr.length; i++) {
        minDiff = Math.min(minDiff, arr[i] - arr[i - 1]);
    }

    List<List<Integer>> result = new ArrayList<>();
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] - arr[i - 1] == minDiff) {
            result.add(Arrays.asList(arr[i - 1], arr[i]));
        }
    }

    return result;
}
```


```python
import math

def nthUglyNumber(n, a, b, c):
    left, right = 1, int(2e9)
    lcm_ab, lcm_ac, lcm_bc = a * b // math.gcd(a, b), a * c // math.gcd(a, c), b * c // math.gcd(b, c)
    lcm_abc = a * lcm_bc // math.gcd(a, lcm_bc)

    while left < right:
        mid = left + (right - left) // 2
        count = mid // a + mid // b + mid // c - mid // lcm_ab - mid // lcm_ac - mid // lcm_bc + mid // lcm_abc
        if count < n:
            left = mid + 1
        else:
            right = mid
    return left
```

```cpp
#include <algorithm>

int nthUglyNumber(int n, int a, int b, int c) {
    long long left = 1, right = 2 * 1e9, gcd_ab = std::__gcd(a, b), gcd_ac = std::__gcd(a, c), gcd_bc = std::__gcd(b, c);
    long long lcm_ab = a / gcd_ab * b, lcm_ac = a / gcd_ac * c, lcm_bc = b / gcd_bc * c, lcm_abc = a / gcd_ab * lcm_bc;

    while (left < right) {
        long long mid = left + (right - left) / 2;
        long long count = mid / a + mid / b + mid / c - mid / lcm_ab - mid / lcm_ac - mid / lcm_bc + mid / lcm_abc;
        if (count < n) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}
```


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

class Solution {
public:
    string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
        int n = s.size();
        vector<int> p(n, 0);
        for (int i = 0; i < n; ++i) {
            p[i] = i;
        }

        // find the parent for each index
        function<int(int)> find = [&](int x) {
            if (p[x] != x) {
                p[x] = find(p[x]);
            }
            return p[x];
        };

        // union-find and create the connected groups
        for (const auto& pair : pairs) {
            int root1 = find(pair[0]);
            int root2 = find(pair[1]);
            if (root1 != root2) {
                p[root2] = root1;
            }
        }

        vector<string> groups(n);
        for (int i = 0; i < n; ++i) {
            groups[find(i)].push_back(s[i]);
        }

        // Sort each group
        for (string& group : groups) {
            sort(group.begin(), group.end(), greater<char>());
        }

        // Build the result string
        string res;
        for (int i = 0; i < n; ++i) {
            char smallest_char = groups[find(i)].back();
            res += smallest_char;
            groups[find(i)].pop_back();
        }

        return res;
    }
};
```

  "bacd "
Explaination:
Swap s\[0\] and s\[3\], s =  "bcad "
Swap s\[1\] and s\[2\], s =  "bacd "

abc aabbcc abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcxyz a abc abcde abc abc ab abc abc aa abcd aaz abc abc abcde abcdefghij abcdefghijklmnopqrstuvwxyz bacd a a abcd abcd abc bacd abcd abc a abcdefghij abc ab abcd eert abcd ab abc ab abc mno a abcdefghijklmnopqrstuvwxyz abcde abcde abcdefghij abcd abcd bacd abcde abcd abcdefghij abcd abcd abcdefghij abc abcd

```python
from collections import defaultdict

class Solution:
    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
        n = len(s)

        # Initialize the parents array
        p = list(range(n))

        # Helper function to find the parent of an index
        def find(x):
            if p[x] != x:
                p[x] = find(p[x])
            return p[x]

        # Union-find, grouping connected indices together
        for pair in pairs:
            root1 = find(pair[0])
            root2 = find(pair[1])
            if root1 != root2:
                p[root2] = root1

        # Group all the characters together according to their representatives (parent)
        groups = defaultdict(list)
        for i in range(n):
            root = find(i)
            groups[root].append(s[i])

        # Sort each group
        for group in groups.values():
            group.sort(reverse=True)

        # Build the result string
        res = []
        for i in range(n):
            root = find(i)
            res.append(groups[root].pop())

        return "".join(res)
```


```java
import java.util.*;

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

public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
    List<TreeNode> forest = new ArrayList<>();
    Set<Integer> toDelete = new HashSet<>();
    for (int val : to_delete) {
        toDelete.add(val);
    }
    helper(root, true, toDelete, forest);
    return forest;
}

private TreeNode helper(TreeNode node, boolean isRoot, Set<Integer> toDelete, List<TreeNode> forest) {
    if (node == null) return null;
    boolean deleted = toDelete.contains(node.val);
    if (isRoot && !deleted) forest.add(node);
    node.left = helper(node.left, deleted, toDelete, forest);
    node.right = helper(node.right, deleted, toDelete, forest);
    return deleted ? null : node;
}
```

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

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

std::vector<TreeNode*> delNodes(TreeNode* root, std::vector<int>& to_delete) {
    std::vector<TreeNode*> forest;
    std::set<int> toDelete(to_delete.begin(), to_delete.end());
    helper(root, true, toDelete, forest);
    return forest;
}

TreeNode* helper(TreeNode* node, bool isRoot, std::set<int>& toDelete, std::vector<TreeNode*>& forest) {
    if (!node) return nullptr;
    bool deleted = toDelete.count(node->val);
    if (isRoot && !deleted) forest.push_back(node);
    node->left = helper(node->left, deleted, toDelete, forest);
    node->right = helper(node->right, deleted, toDelete, forest);
    return deleted ? nullptr : node;
}
```


```python
def removeDuplicates(s: str, k: int) -> str:
    stack = []
    for c in s:
        if not stack or stack[-1][0] != c:
            stack.append((c, 1))
        elif stack[-1][1] + 1 != k:
            stack[-1] = (c, stack[-1][1] + 1)
        else:
            stack.pop()
    return ''.join(c * count for c, count in stack)
```

cc aa bbaa cc aaabbb aabbcc bbaa aabbcc cc bbaa aabbcc aabbcc bbaa bbaa azxxzy bbaa cc aabbcc aabbcc abc bbaa cc a bbaa abcd aabbcc aabbcc cc bcc bbaa cc aa aabbcc aabbcc aabbcc c aabbcc cc bbaa ps abcd cc cc cc aabbcc cc bbaa bbaa xyzxyzxyz

```java
public String removeDuplicates(String s, int k) {
    Stack<int[]> stack = new Stack<>();
    for (char c : s.toCharArray()) {
        if (stack.isEmpty() || stack.peek()[0] != c) {
            stack.push(new int[]{c, 1});
        } else if (++stack.peek()[1] == k) {
            stack.pop();
        }
    }
    StringBuilder result = new StringBuilder();
    while (!stack.isEmpty()) {
        int[] elem = stack.pop();
        for (int i = 0; i < elem[1]; i++) {
            result.append((char) elem[0]);
        }
    }
    return result.reverse().toString();
}
```


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

vector<int> arraysIntersection(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3) {
    int i = 0, j = 0, k = 0;
    vector<int> result;
    while (i < arr1.size() && j < arr2.size() && k < arr3.size()) {
        if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
            result.push_back(arr1[i]);
            i++; j++; k++;
        } else {
            if (arr1[i] <= arr2[j] && arr1[i] <= arr3[k]) i++;
            else if (arr2[j] <= arr3[k]) j++;
            else k++;
        }
    }
    return result;
}
```

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

public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
    int i = 0, j = 0, k = 0;
    ArrayList<Integer> result = new ArrayList<>();
    while (i < arr1.length && j < arr2.length && k < arr3.length) {
        if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
            result.add(arr1[i]);
            i++; j++; k++;
        } else {
            if (arr1[i] <= arr2[j] && arr1[i] <= arr3[k]) i++;
            else if (arr2[j] <= arr3[k]) j++;
            else k++;
        }
    }
    return result;
}
```


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

public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) {
    Set<Integer> set = new HashSet<>();
    buildSet(root1, set);
    return findPair(root2, target, set);
}

private void buildSet(TreeNode root, Set<Integer> set) {
    if (root == null) return;
    set.add(root.val);
    buildSet(root.left, set);
    buildSet(root.right, set);
}

private boolean findPair(TreeNode root, int target, Set<Integer> set) {
    if (root == null) return false;
    if (set.contains(target - root.val)) return true;
    return findPair(root.left, target, set) || findPair(root.right, target, set);
}
```

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

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

def twoSumBSTs(root1, root2, target):
    def build_set(node, s):
        if node:
            s.add(node.val)
            build_set(node.left, s)
            build_set(node.right, s)

    def find_pair(node, target, s):
        if node:
            if target - node.val in s:
                return True
            return find_pair(node.left, target, s) or find_pair(node.right, target, s)
        return False

    s = set()
    build_set(root1, s)
    return find_pair(root2, target, s)
```


```cpp
#include <vector>

std::vector<int> countSteppingNumbers(int low, int high) {
    std::vector<int> results;
    for (int i = low; i <= high; i++) {
        int prev = -1;
        int j = i;
        bool is_stepping = true;
        while (j > 0) {
            int digit = j % 10;
            if (prev != -1 && std::abs(prev - digit) != 1) {
                is_stepping = false;
                break;
            }
            prev = digit;
            j /= 10;
        }
        if (is_stepping) results.push_back(i);
    }
    return results;
}
```

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

public List<Integer> countSteppingNumbers(int low, int high) {
    List<Integer> results = new ArrayList<>();
    for (int i = low; i <= high; i++) {
        int prev = -1;
        int j = i;
        boolean isStepping = true;
        while (j > 0) {
            int digit = j % 10;
            if (prev != -1 && Math.abs(prev - digit) != 1) {
                isStepping = false;
                break;
            }
            prev = digit;
            j /= 10;
        }
        if (isStepping) results.add(i);
    }
    return results;
}
```


```java
import java.util.HashMap;

public int longestWPI(int[] hours) {
    int score = 0;
    int maxLength = 0;
    HashMap<Integer, Integer> firstOccurrence = new HashMap<>();

    for (int i = 0; i < hours.length; ++i) {
        score += hours[i] > 8 ? 1 : -1;
        if (score > 0) maxLength = i + 1;
        else {
            firstOccurrence.putIfAbsent(score, i);
            if (firstOccurrence.containsKey(score - 1))
                maxLength = Math.max(maxLength, i - firstOccurrence.get(score - 1));
        }
    }
    return maxLength;
}
```

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

int longestWPI(std::vector<int>& hours) {
    int score = 0;
    int maxLength = 0;
    std::unordered_map<int, int> firstOccurrence;

    for (int i = 0; i < hours.size(); ++i) {
        score += hours[i] > 8 ? 1 : -1;
        if (score > 0) maxLength = i + 1;
        else {
             if (firstOccurrence.find(score) == firstOccurrence.end())
                firstOccurrence[score] = i;
             if (firstOccurrence.find(score - 1) != firstOccurrence.end())
                maxLength = std::max(maxLength, i - firstOccurrence[score - 1]);
        }
    }
    return maxLength;
}
```


```cpp
int findSpecialInteger(const vector<int>& arr) {
    int n = arr.size(), requiredCount = n / 4;
    for (int i = 0; i < n; i++) {
        if (arr[i] == arr[i + requiredCount]) {
            return arr[i];
        }
    }
    return -1;
}
```

RRLRLRRLLR RLLRRRLRLL RRRLLRLRLR RRRLLRLRLR RRRLLRLRLR LLRLRRRLLL RLLRRRLRLL RRLRLRRLLR LLRLRRRLLL RLRRRLLRLL RRRLLRLRLR RRRLLRLRLR LLLLLRRRR RLLRRRLRLL LRLRLRLRRL RRRLLRLRLR LLRLRRRLLR RLLRRRLRLL RRLRLRRLLR RRLRLRRLLR RLLRRRLRLL RRRLLRLRLR LRRLRRLLRL RLRLRLRLRL RRLRLRRLLR LLRLRRRLLL LRRLRRLLRL LRRLRRLLRL RLLRRRLRLR RRRLLRLRLR RRLRLRRLLR LLRLRRRLLL RLRRLLRLRL LRRLRRLLRL RRLRLRRLLR RRLRLRRLLR LRRLRRLLRL RRRLLRLRLL RRLRLRRLLR LLRLRRRLLL RLLRRRLRLL RRLRLRRLLR RRLRLRRLLR RLLRRRLRLL RRRLLRLRLR LLRLRRRLLL RRRRRLLLL RRRLLRLRLR RRRLLRLRLR LLRLRRRLLL RLLRRRLRLL LRRLRRLLRL LLRLRRRLLL LRRLRRLLRL LLRLRRRLLL LRRLRRLLRL RRRLLRRLLR RLLRRRLRLL RLLRRRLRLL LLRLRRRLLL LRRLRRLLRL LRRLRRLLRL RLRRLLRLRL LRLRLRLRLR LRRLRRLLRL LLRLRRRLLL RRLRLRRLLR RLLRRRLRLL

R L L L L R R R R R R R R R L R R R R R L R R R L R L L L R R R R R R R R R L R R R R R R R R R L R R L L R R R L R R R R R R R R R R R

```python
def find_special_integer(arr):
    n = len(arr)
    required_count = n // 4
    for i in range(n):
        if arr[i] == arr[i + required_count]:
            return arr[i]
    return -1
```


```java
import java.util.Arrays;
import java.util.function.Function;
import java.util.function.BiConsumer;

public boolean[] areConnected(int n, int threshold, int[][] queries) {
    boolean[] answer = new boolean[queries.length];
    int[] parent = new int[n + 1];
    int[] rank = new int[n + 1];

    for (int i = 1; i <= n; i++) {
        parent[i] = i;
    }

    Function<Integer, Integer> find = x -> {
        if (parent[x] != x)
            parent[x] = find.apply(parent[x]);
        return parent[x];
    };

    BiConsumer<Integer, Integer> unite = (x, y) -> {
        int rootx = find.apply(x);
        int rooty = find.apply(y);
        if (rootx != rooty) {
            if (rank[rootx] > rank[rooty]) {
                int temp = rootx;
                rootx = rooty;
                rooty = temp;
            }
            parent[rootx] = rooty;
            if (rank[rootx] == rank[rooty])
                rank[rooty]++;
        }
    };

    for (int i = threshold + 1; i <= n; i++) {
        for (int j = 2 * i; j <= n; j += i) {
            unite.accept(i, j);
        }
    }

    for (int i = 0; i < queries.length; i++) {
        answer[i] = find.apply(queries[i][0]) == find.apply(queries[i][1]);
    }

    return answer;
}
```

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

vector<bool> areConnected(int n, int threshold, vector<vector<int>>& queries) {
    vector<bool> answer(queries.size());
    vector<int> parent(n + 1), rank(n + 1, 0);

    for (int i = 1; i <= n; ++i)
        parent[i] = i;

    function<int(int)> find = [&](int x) {
        if (parent[x] != x)
            parent[x] = find(parent[x]);
        return parent[x];
    };

    auto unite = [&](int x, int y) {
        int rootx = find(x);
        int rooty = find(y);
        if (rootx != rooty) {
            if (rank[rootx] > rank[rooty])
                swap(rootx, rooty);
            parent[rootx] = rooty;
            if (rank[rootx] == rank[rooty])
                rank[rooty]++;
        }
    };

    for (int i = threshold + 1; i <= n; ++i)
        for (int j = 2 * i; j <= n; j += i)
            unite(i, j);

    for (int i = 0; i < queries.size(); ++i)
        answer[i] = find(queries[i][0]) == find(queries[i][1]);

    return answer;
}
```


```java
public int mctFromLeafValues(int[] arr) {
    int n = arr.length;
    int[][] dp = new int[n][n];
    int[][] maxs = new int[n][n];

    for (int i = 0; i < n; ++i) {
        for (int j = i; j < n; ++j) {
            maxs[i][j] = Arrays.stream(arr, i, j + 1).max().getAsInt();
        }
    }

    for (int len = 1; len < n; ++len) {
        for (int i = 0; i + len < n; ++i) {
            int j = i + len;
            dp[i][j] = Integer.MAX_VALUE;
            for (int k = i; k < j; ++k) {
                dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + maxs[i][k] * maxs[k + 1][j]);
            }
        }
    }
    return dp[0][n - 1];
}
```

```python
def mctFromLeafValues(arr: List[int]) -> int:
    n = len(arr)
    dp = [[0] * n for _ in range(n)]
    maxs = [[0] * n for _ in range(n)]

    for i in range(n):
        for j in range(i, n):
            maxs[i][j] = max(arr[i:j+1])

    for len_ in range(1, n):
        for i in range(n - len_):
            j = i + len_
            dp[i][j] = float('inf')
            for k in range(i, j):
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + maxs[i][k] * maxs[k+1][j])

    return dp[0][n - 1]
```


```python
from typing import List

def removeSubfolders(folder: List[str]) -> List[str]:
    result = []
    folder.sort()
    prefix = "/"

    for path in folder:
        if not path.startswith(prefix):
            result.append(path)
            prefix = path + "/"
    return result
```

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

std::vector<std::string> removeSubfolders(std::vector<std::string>& folder) {
    std::vector<std::string> result;
    std::sort(folder.begin(), folder.end());
    std::string prefix = "/";

    for (const auto& path : folder) {
        if (path.compare(0, prefix.size(), prefix) != 0) {
            result.push_back(path);
            prefix = path + "/";
        }
    }
    return result;
}
```


```python
from bisect import bisect_left

def jobScheduling(startTime, endTime, profit):
    jobs = sorted(zip(endTime, startTime, profit))
    dp = [jobs[0][2]]

    def latestNonConflict(index):
        startTimeToFind = jobs[index][1]
        index = bisect_left([job[0] for job in jobs], startTimeToFind)
        if index:
            return index - 1
        return -1

    for i in range(1, len(jobs)):
        L = latestNonConflict(i)
        dp.append(max(dp[-1], (0 if L == -1 else dp[L]) + jobs[i][2]))

    return dp[-1]
```

```java
import java.util.Arrays;

public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
    int n = startTime.length;
    int[][] jobs = new int[n][3];

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

    Arrays.sort(jobs, (a, b) -> a[0] - b[0]);
    int[] dp = new int[n];
    dp[0] = jobs[0][2];

    for (int i = 1; i < n; i++) {
        int L = -1;
        for (int j = i - 1; j >= 0; j--) {
            if (jobs[j][1] >= jobs[L == -1 ? i : L][0]) {
                L = j;
            }
        }
        dp[i] = Math.max(dp[i - 1], (L == -1 ? 0 : dp[L]) + jobs[i][2]);
    }

    return dp[n - 1];
}
```


```python
from functools import lru_cache

def stoneGameII(piles):
    n = len(piles)
    for i in range(n - 2, -1, -1):
        piles[i] += piles[i + 1]

    @lru_cache(None)
    def search(idx, M):
        if idx + 2 * M >= n:
            return piles[idx]
        return max(piles[idx] - search(idx + x, max(M, x)) for x in range(1, 2 * M + 1))

    return search(0, 1)
```

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

int stoneGameII(std::vector<int>& piles) {
    int n = piles.size();
    std::vector<std::vector<int>> memo(n, std::vector<int>(n + 1, 0));

    for (int i = n - 2; i >= 0; --i) {
        piles[i] += piles[i + 1];
    }

    function<int(int, int)> search = [&](int idx, int M) {
        if (idx + 2 * M >= n) {
            return piles[idx];
        }
        if (memo[idx][M] > 0) {
            return memo[idx][M];
        }
        memo[idx][M] = 0;
        for (int x = 1; x <= 2 * M; ++x) {
            memo[idx][M] = std::max(memo[idx][M], piles[idx] - search(idx + x, std::max(M, x)));
        }
        return memo[idx][M];
    };

    return search(0, 1);
}
```


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

int treeDiameter(vector<vector<int>>& edges) {
    unordered_map<int, vector<int>> tree;
    for (const auto& edge : edges) {
        tree[edge[0]].push_back(edge[1]);
        tree[edge[1]].push_back(edge[0]);
    }

    queue<pair<int, int>> q;
    q.push({0, 0});
    int furthest = 0;
    int max_distance = 0;
    while (!q.empty()) {
        int node = q.front().first;
        int distance = q.front().second;
        q.pop();
        if (distance > max_distance) {
            max_distance = distance;
            furthest = node;
        }
        for (int neighbor : tree[node]) {
            tree[neighbor].erase(remove(tree[neighbor].begin(), tree[neighbor].end(), node), tree[neighbor].end());
            q.push({neighbor, distance + 1});
        }
    }

    q.push({furthest, 0});
    max_distance = 0;
    while (!q.empty()) {
        int node = q.front().first;
        int distance = q.front().second;
        q.pop();
        if (distance > max_distance) {
            max_distance = distance;
        }
        for (int neighbor : tree[node]) {
            tree[neighbor].erase(remove(tree[neighbor].begin(), tree[neighbor].end(), node), tree[neighbor].end());
            q.push({neighbor, distance + 1});
        }
    }

    return max_distance;
}
```

```python
from collections import deque, defaultdict

def tree_diameter(edges):
    tree = defaultdict(list)
    for edge in edges:
        tree[edge[0]].append(edge[1])
        tree[edge[1]].append(edge[0])

    queue = deque([(0, 0)])
    furthest, max_distance = 0, 0
    while queue:
        node, distance = queue.popleft()
        if distance > max_distance:
            max_distance = distance
            furthest = node
        for neighbor in tree[node]:
            tree[neighbor].remove(node)
            queue.append((neighbor, distance + 1))

    queue.append((furthest, 0))
    max_distance = 0
    while queue:
        node, distance = queue.popleft()
        if distance > max_distance:
            max_distance = distance
        for neighbor in tree[node]:
            tree[neighbor].remove(node)
            queue.append((neighbor, distance + 1))

    return max_distance
```


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

int dp[101][101];

bool isPalindrome(const vector<int>& arr, int i, int j) {
    while (i < j)
        if (arr[i++] != arr[j--]) return false;
    return true;
}

int minRemovals(vector<int>& arr, int i, int j) {
    if (i > j) return 0;
    if (i == j) return 1;
    if (dp[i][j] != -1) return dp[i][j];

    int ans = minRemovals(arr, i + 1, j) + 1;
    for (int k = i + 1; k <= j; k++)
        if (arr[i] == arr[k])
            ans = min(ans, minRemovals(arr, i + 1, k - 1) + minRemovals(arr, k + 1, j));
    return dp[i][j] = ans;
}

int minimumMoves(vector<int>& arr) {
    memset(dp, -1, sizeof(dp));
    return minRemovals(arr, 0, arr.size() - 1);
}
```

```python
def minimumMoves(arr):
    def minRemovals(i, j):
        if i > j:
            return 0
        if i == j:
            return 1
        if dp[i][j] != -1:
            return dp[i][j]

        ans = minRemovals(i + 1, j) + 1
        for k in range(i + 1, j + 1):
            if arr[i] == arr[k]:
                ans = min(ans, minRemovals(i + 1, k - 1) + minRemovals(k + 1, j))
        dp[i][j] = ans
        return ans

    dp = [[-1] * len(arr) for _ in range(len(arr))]
    return minRemovals(0, len(arr) - 1)
```


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

def isGoodArray(nums):
    return reduce(gcd, nums) == 1
```

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

```java
class Solution {
    public boolean isGoodArray(int[] nums) {
        int res = nums[0];
        for (int num : nums) {
            res = gcd(res, num);
        }
        return res == 1;
    }

    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}
```


```java
public int closedIsland(int[][] grid) {
    int count = 0;
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == 0 && dfs(grid, i, j)) {
                count++;
            }
        }
    }
    return count;
}

private boolean dfs(int[][] grid, int i, int j) {
    if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {
        return false;
    }

    if (grid[i][j] == 1) {
        return true;
    }

    grid[i][j] = 1;

    boolean up = dfs(grid, i - 1, j);
    boolean down = dfs(grid, i + 1, j);
    boolean left = dfs(grid, i, j - 1);
    boolean right = dfs(grid, i, j + 1);

    return up && down && left && right;
}
```

```python
def closedIsland(grid):
    def dfs(grid, i, j):
        if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]):
            return False

        if grid[i][j] == 1:
            return True

        grid[i][j] = 1

        up = dfs(grid, i - 1, j)
        down = dfs(grid, i + 1, j)
        left = dfs(grid, i, j - 1)
        right = dfs(grid, i, j + 1)

        return up and down and left and right

    count = 0
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            if grid[i][j] == 0 and dfs(grid, i, j):
                count += 1

    return count
```


```cpp
int numberOfWays(int numPeople) {
    const int MOD = 1000000007;
    vector<int> dp(numPeople / 2 + 1);
    dp[0] = 1;
    for (int i = 1; i <= numPeople / 2; ++i) {
        for (int j = 1; j <= i; ++j) {
            dp[i] = (dp[i] + ((long long) dp[i - j] * dp[j - 1]) % MOD) % MOD;
        }
    }
    return dp[numPeople / 2];
}
```

```java
public int numberOfWays(int numPeople) {
    int MOD = 1000000007;
    int[] dp = new int[numPeople / 2 + 1];
    dp[0] = 1;
    for (int i = 1; i <= numPeople / 2; ++i) {
        for (int j = 1; j <= i; ++j) {
            dp[i] = (dp[i] + (int)(((long) dp[i - j] * dp[j - 1]) % MOD )) % MOD;
        }
    }
    return dp[numPeople / 2];
}
```


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

```java
public int minTimeToVisitAllPoints(int[][] points) {
    int time = 0;
    for (int i = 1; i < points.length; i++) {
        int dx = Math.abs(points[i][0] - points[i - 1][0]);
        int dy = Math.abs(points[i][1] - points[i - 1][1]);
        time += Math.max(dx, dy);
    }
    return time;
}
```


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

int palindromePartition(std::string s, int k) {
    int n = s.size();
    std::vector<std::vector<int>> dp(n, std::vector<int>(n, 0));

    for (int len = 2; len <= n; ++len) {
        for (int i = 0; i <= n - len; ++i) {
            int j = i + len - 1;
            dp[i][j] = dp[i + 1][j - 1] + (s[i] != s[j]);
        }
    }

    std::vector<int> memo(n, 1e9);
    for (int i = 0; i < n; ++i) {
        if (dp[0][i] == 0) {
            memo[i] = 0;
        } else {
            for (int j = 0; j < i; ++j) {
                memo[i] = std::min(memo[i], memo[j] + dp[j + 1][i]);
            }
        }
    }

    return memo.back() + k;
}
```

```java
public int palindromePartition(String s, int k) {
    int n = s.length();
    int[][] dp = new int[n][n];

    for (int len = 2; len <= n; ++len) {
        for (int i = 0; i <= n - len; ++i) {
            int j = i + len - 1;
            dp[i][j] = dp[i + 1][j - 1] + (s.charAt(i) != s.charAt(j) ? 1 : 0);
        }
    }

    int[] memo = new int[n];
    for (int i = 0; i < n; ++i) {
        if (dp[0][i] == 0) {
            memo[i] = 0;
        } else {
            memo[i] = Integer.MAX_VALUE;
            for (int j = 0; j < i; ++j) {
                memo[i] = Math.min(memo[i], memo[j] + dp[j + 1][i]);
            }
        }
    }

    return memo[memo.length - 1] + k;
}
```


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

std::vector<std::vector<int>> groupThePeople(std::vector<int>& groupSizes) {
    std::unordered_map<int, std::vector<int>> groups;
    std::vector<std::vector<int>> result;

    for (int i = 0; i < groupSizes.size(); i++) {
        groups[groupSizes[i]].push_back(i);
        if (groups[groupSizes[i]].size() == groupSizes[i]) {
            result.push_back(groups[groupSizes[i]]);
            groups[groupSizes[i]].clear();
        }
    }

    return result;
}
```

```python
from collections import defaultdict

def groupThePeople(groupSizes):
    groups = defaultdict(list)
    result = []

    for i, size in enumerate(groupSizes):
        groups[size].append(i)
        if len(groups[size]) == size:
            result.append(groups[size])
            groups[size] = []

    return result
```


```python
def min_operations(arr1, arr2):
    n = len(arr1)
    dp = [float('inf')] * n
    for a in arr2:
        new_dp = [float('inf')] * n
        p = 0
        for i in range(n):
            if a < arr1[i]:
                new_dp[i] = p
            if i > 0 and dp[i - 1] < p:
                p = dp[i - 1]
            if arr1[i] > arr1[i + 1]:
                return -1
        dp = new_dp
    return dp[-1]
```

```cpp
#include <vector>
#include <limits>

int minOperations(std::vector<int>& arr1, std::vector<int>& arr2) {
    int n = arr1.size();
    std::vector<int> dp(n, std::numeric_limits<int>::max());
    for (int a : arr2) {
        std::vector<int> new_dp(n, std::numeric_limits<int>::max());
        int p = 0;
        for (int i = 0; i < n; ++i) {
            if (a < arr1[i]) new_dp[i] = p;
            if (i > 0 && dp[i - 1] < p) p = dp[i - 1];
            if (arr1[i] > arr1[i + 1]) return -1;
        }
        dp.swap(new_dp);
    }
    return dp.back();
}
```


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

public List<Integer> sequentialDigits(int low, int high) {
    List<Integer> result = new ArrayList<>();
    for (int i = 1; i <= 9; ++i) {
        int number = i;
        for (int j = i + 1; j <= 9; ++j) {
            number = number * 10 + j;
            if (number >= low && number <= high) {
                result.add(number);
            }
        }
    }
    Collections.sort(result);
    return result;
}
```

```python
def sequential_digits(low, high):
    result = []
    for i in range(1, 10):
        number = i
        for j in range(i + 1, 10):
            number = number * 10 + j
            if low <= number <= high:
                result.append(number)
    return sorted(result)
```


```cpp
int maxSideLength(vector<vector<int>>& mat, int threshold) {
    int m = mat.size(), n = mat[0].size();
    vector<vector<int>> preSum(m + 1, vector<int>(n + 1));
    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j <= n; ++j) {
            preSum[i][j] = mat[i-1][j-1] + preSum[i-1][j] + preSum[i][j-1] - preSum[i-1][j-1];
        }
    }

    int maxSide = 0;
    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j <= n; ++j) {
            for (int k = 1; k <= min(m, n); ++k) {
                int endX = i + k - 1, endY = j + k - 1;
                if (endX <= m && endY <= n) {
                    int sum = preSum[endX][endY] - preSum[endX][j - 1] - preSum[i - 1][endY] + preSum[i - 1][j - 1];
                    if (sum <= threshold) {
                        maxSide = max(maxSide, k);
                    }
                } else {
                    break;
                }
            }
        }
    }
    return maxSide;
}
```

```python
def maxSideLength(mat: List[List[int]], threshold: int) -> int:
    m, n = len(mat), len(mat[0])
    preSum = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            preSum[i][j] = mat[i - 1][j - 1] + preSum[i - 1][j] + preSum[i][j - 1] - preSum[i - 1][j - 1]

    maxSide = 0
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            for k in range(1, min(m, n) + 1):
                endX, endY = i + k - 1, j + k - 1
                if endX <= m and endY <= n:
                    sum = preSum[endX][endY] - preSum[endX][j - 1] - preSum[i - 1][endY] + preSum[i - 1][j - 1]
                    if sum <= threshold:
                        maxSide = max(maxSide, k)
                else:
                    break
    return maxSide
```


```python
from collections import deque

def shortestPath(grid, k):
    m, n = len(grid), len(grid[0])
    visited = [[[False for _ in range(k + 1)] for _ in range(n)] for _ in range(m)]
    q = deque([(0, 0, 0, k)])
    moves = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    steps = 0

    while q:
        for _ in range(len(q)):
            x, y, steps, k_remaining = q.popleft()
            if x == m - 1 and y == n - 1:
                return steps
            for dx, dy in moves:
                new_x, new_y, = x + dx, y + dy
                if 0 <= new_x < m and 0 <= new_y < n:
                    new_k_remaining = k_remaining - grid[new_x][new_y]
                    if new_k_remaining >= 0 and not visited[new_x][new_y][new_k_remaining]:
                        visited[new_x][new_y][new_k_remaining] = True
                        q.append((new_x, new_y, steps + 1, new_k_remaining))
        steps += 1

    return -1
```

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

int shortestPath(std::vector<std::vector<int>>& grid, int k) {
    int m = grid.size();
    int n = grid[0].size();
    std::vector<std::vector<std::vector<int>>> visited(m, std::vector<std::vector<int>>(n, std::vector<int>(k + 1, 0)));
    std::queue<std::tuple<int, int, int, int>> q;
    int steps = 0;
    int moves[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    q.push({0, 0, 0, k});

    while (!q.empty()) {
        int q_size = q.size();
        for (int i = 0; i < q_size; ++i) {
            int x, y, steps, k_remaining;
            std::tie(x, y, steps, k_remaining) = q.front();
            q.pop();
            if (x == m - 1 && y == n - 1) return steps;

            for (const auto& move : moves) {
                int new_x = x + move[0];
                int new_y = y + move[1];
                if (new_x >= 0 && new_x < m && new_y >= 0 && new_y < n) {
                    int new_k_remaining = k_remaining - grid[new_x][new_y];
                    if (new_k_remaining >= 0 && !visited[new_x][new_y][new_k_remaining]) {
                        visited[new_x][new_y][new_k_remaining] = 1;
                        q.push({new_x, new_y, steps + 1, new_k_remaining});
                    }
                }
            }
        }
    }

    return -1;
}
```


```python
from typing import List

MOD = 10**9 + 7

def pathsWithMaxScore(board: List[str]) -> List[int]:
    n = len(board)
    dp = [[0] * n for _ in range(n)]
    cnt = [[0] * n for _ in range(n)]

    board[0] = list(board[0])
    board[0][0] = '0'
    board[n-1] = list(board[n-1])
    board[n-1][n-1] = '0'
    cnt[n-1][n-1] = 1

    for i in range(n-1, -1, -1):
        for j in range(n-1, -1, -1):
            if board[i][j] != 'X':
                neighbors = [(i-1, j), (i, j-1), (i-1, j-1)]
                for x, y in neighbors:
                    if x >= 0 and y >= 0:
                        if dp[i][j] < dp[x][y] + int(board[i][j]):
                            dp[i][j] = dp[x][y] + int(board[i][j])
                            cnt[i][j] = cnt[x][y]
                        elif dp[i][j] == dp[x][y] + int(board[i][j]):
                            cnt[i][j] = (cnt[i][j] + cnt[x][y]) % MOD

    return [dp[0][0], cnt[0][0]]
```

```cpp
#include <vector>
#include <string>
using namespace std;
const int MOD = 1000000007;

vector<int> pathsWithMaxScore(vector<string>& board) {
    int n = board.size();
    vector<vector<int>> dp(n, vector<int>(n, 0)), cnt(n, vector<int>(n, 0));

    board[0][0] = '0';
    board[n-1][n-1] = '0';
    cnt[n-1][n-1] = 1;

    for (int i = n-1; i >= 0; i--) {
        for (int j = n-1; j >= 0; j--) {
            if (board[i][j] != 'X') {
                vector<pair<int, int>> neighbors = {{i-1, j}, {i, j-1}, {i-1, j-1}};
                for (auto neighbor : neighbors) {
                    int x = neighbor.first, y = neighbor.second;
                    if(x>=0 && y>=0) {
                        if (dp[i][j] < dp[x][y] + board[i][j] - '0') {
                            dp[i][j] = dp[x][y] + board[i][j] - '0';
                            cnt[i][j] = cnt[x][y];
                        } else if (dp[i][j] == dp[x][y] + board[i][j] - '0') {
                            cnt[i][j] = (cnt[i][j] + cnt[x][y]) % MOD;
                        }
                    }
                }
            }
        }
    }

    return {dp[0][0], cnt[0][0]};
}
```


```java
import java.util.Stack;

public int[] peopleCanSee(int[] heights) {
    int n = heights.length;
    int[] ans = new int[n];
    Stack<Integer> st = new Stack<>();

    for (int i = n - 1; i >= 0; --i) {
        while (!st.isEmpty() && heights[st.peek()] < heights[i]) {
            int idx = st.pop();
            ans[i]++;
            ans[i] += ans[idx];
        }
        st.push(i);
    }

    return ans;
}
```

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

std::vector<int> peopleCanSee(std::vector<int>& heights) {
    int n = heights.size();
    std::vector<int> ans(n, 0);
    std::stack<int> st;

    for (int i = n - 1; i >= 0; --i) {
        while (!st.empty() && heights[st.top()] < heights[i]) {
            int idx = st.top();
            st.pop();
            ans[i]++;
            ans[i] += ans[idx];
        }
        st.push(i);
    }

    return ans;
}
```


```python
def matrix_block_sum(mat, k):
    m, n = len(mat), len(mat[0])
    answer = [[0 for _ in range(n)] for _ in range(m)]

    for i in range(m):
        for j in range(n):
            for r in range(max(0, i - k), min(m, i + k + 1)):
                for c in range(max(0, j - k), min(n, j + k + 1)):
                    answer[i][j] += mat[r][c]

    return answer
```

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

vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
    int m = mat.size();
    int n = mat[0].size();
    vector<vector<int>> answer(m, vector<int>(n, 0));

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            for (int r = max(0, i - k); r <= min(m - 1, i + k); ++r) {
                for (int c = max(0, j - k); c <= min(n - 1, j + k); ++c) {
                    answer[i][j] += mat[r][c];
                }
            }
        }
    }

    return answer;
}
```