# Maximum Erasure Value

- slug: maximum-erasure-value
- difficulty: Medium

You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements.

Return _the **maximum score** you can get by erasing **exactly one** subarray._

An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to `a[l],a[l+1],...,a[r]` for some `(l,r)`.

**Example 1:**

**Input:** nums = \[4,2,4,5,6\]
**Output:** 17
**Explanation:** The optimal subarray here is \[2,4,5,6\].

**Example 2:**

**Input:** nums = \[5,2,1,2,5,2,1,2,5\]
**Output:** 8
**Explanation:** The optimal subarray here is \[5,2,1\] or \[1,2,5\].

**Constraints:**

*   `1 <= nums.length <= 105`
*   `1 <= nums[i] <= 104`

## A solution in Java

```java
import java.util.Arrays;

class Solution {
    public int maxSumRangeQuery(int[] nums, int[][] requests) {
        int n = nums.length;
        int[] cnt = new int[n];
        int mod = (int) 1e9 + 7;

        for (int[] req : requests) {
            cnt[req[0]]++;
            if (req[1] + 1 < n) cnt[req[1] + 1]--;
        }

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

        Arrays.sort(nums);
        Arrays.sort(cnt);

        long ans = 0;
        for (int i = 0; i < n; i++) {
            ans += (long) nums[i] * cnt[i];
            ans %= mod;
        }

        return (int) ans;
    }
}
```
1. Initialize an array `cnt` of the same length as `nums` and set all elements to 0.
2. For each request `[starti, endi]`, increment `cnt[starti]` and decrement `cnt[endi + 1]` if `endi + 1` is within the bounds of the array.
3. For each successive element in `cnt` starting from index 1, add the element at the previous index to it, thereby obtaining the prefix sum of the `cnt` array.
4. Sort both `nums` and `cnt` in ascending order.
5. Compute the sum by multiplying each element in `nums` with the corresponding element in `cnt`. Because the multiplication may cause overflow, this operation modulo 1e9 + 7 is taken.
6. Return the total sum modulo 1e9 + 7.

## A solution in C++

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

const int mod = 1e9 + 7;
int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) {
    vector<int> cnt(nums.size());
    for (auto &req : requests) {
        cnt[req[0]]++;
        if (req[1] + 1 < nums.size()) cnt[req[1] + 1]--;
    }

    for (int i = 1; i < nums.size(); i++) {
        cnt[i] += cnt[i - 1];
    }

    sort(nums.begin(), nums.end());
    sort(cnt.begin(), cnt.end());

    long long ans = 0;
    for (int i = 0; i < nums.size(); i++) {
        ans += (long long)nums[i] * cnt[i];
        ans %= mod;
    }

    return ans;
}
```
1. Initialize an array `cnt` of the same length as `nums` and set all elements to 0.
2. For each request `[starti, endi]`, increment `cnt[starti]` and decrement `cnt[endi + 1]` if `endi + 1` is within the bounds of the array.
3. For each successive element in `cnt` starting from index 1, add the element at the previous index to it, thereby obtaining the prefix sum of the `cnt` array.
4. Sort both `nums` and `cnt` in ascending order.
5. Compute the sum by multiplying each element in `nums` with the corresponding element in `cnt`. Because the multiplication may cause overflow, this operation modulo 1e9 + 7 is taken.
6. Return the total sum modulo 1e9 + 7.

## A solution in Python

```python
from typing import List

def maxSumRangeQuery(nums: List[int], requests: List[List[int]]) -> int:
    mod = 10**9 + 7
    n = len(nums)
    cnt = [0] * n

    for req in requests:
        cnt[req[0]] += 1
        if req[1] + 1 < n:
            cnt[req[1] + 1] -= 1

    for i in range(1, n):
        cnt[i] += cnt[i - 1]

    nums.sort()
    cnt.sort()

    ans = sum(nums[i] * cnt[i] for i in range(n)) % mod

    return ans
```
1. Initialize an array `cnt` of the same length as `nums` and set all elements to 0.
2. For each request `[starti, endi]`, increment `cnt[starti]` and decrement `cnt[endi + 1]` if `endi + 1` is within the bounds of the array.
3. For each successive element in `cnt` starting from index 1, add the element at the previous index to it, thereby obtaining the prefix sum of the `cnt` array.
4. Sort both `nums` and `cnt` in ascending order.
5. Compute the sum by multiplying each element in `nums` with the corresponding element in `cnt`. Because the multiplication may cause overflow, this operation modulo 1e9 + 7 is taken.
6. Return the total sum modulo 1e9 + 7.

## A solution in Javascript

```javascript
function maxSumRangeQuery(nums, requests) {
    const n = nums.length;
    const cnt = new Array(n).fill(0);
    const mod = 1e9 + 7;

    for (const req of requests) {
        cnt[req[0]]++;
        if (req[1] + 1 < n) cnt[req[1] + 1]--;
    }

    for (let i = 1; i < n; i++) {
        cnt[i] += cnt[i - 1];
    }

    nums.sort((a, b) => a - b);
    cnt.sort((a, b) => a - b);

    let ans = 0;
    for (let i = 0; i < n; i++) {
        ans += (BigInt(nums[i]) * BigInt(cnt[i])) % mod;
    }

    return Number(ans % mod);
}
```
1. Initialize an array `cnt` of the same length as `nums` and set all elements to 0.
2. For each request `[starti, endi]`, increment `cnt[starti]` and decrement `cnt[endi + 1]` if `endi + 1` is within the bounds of the array.
3. For each successive element in `cnt` starting from index 1, add the element at the previous index to it, thereby obtaining the prefix sum of the `cnt` array.
4. Sort both `nums` and `cnt` in ascending order.
5. Compute the sum by multiplying each element in `nums` with the corresponding element in `cnt`. Because the multiplication may cause overflow, this operation modulo 1e9 + 7 is taken.
6. Return the total sum modulo 1e9 + 7.


# Jump Game VI

- slug: jump-game-vi
- difficulty: Medium

You are given a **0-indexed** integer array `nums` and an integer `k`.

You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.

You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.

Return _the **maximum score** you can get_.

**Example 1:**

**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.

**Example 2:**

**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.

**Example 3:**

**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0

**Constraints:**

*   `1 <= nums.length, k <= 105`
*   `-104 <= nums[i] <= 104`

## A solution in Java

```java
import java.util.Arrays;

class Solution {
    public boolean isPrintable(int[][] targetGrid) {
        int m = targetGrid.length, n = targetGrid[0].length;
        int[] top = new int[61], bottom = new int[61], left = new int[61], right = new int[61];
        boolean[][] vis = new boolean[m][n];

        Arrays.fill(top, m);
        Arrays.fill(bottom, -1);
        Arrays.fill(left, n);
        Arrays.fill(right, -1);

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int c = targetGrid[i][j];
                top[c] = Math.min(top[c], i);
                bottom[c] = Math.max(bottom[c], i);
                left[c] = Math.min(left[c], j);
                right[c] = Math.max(right[c], j);
            }
        }

        for (int color = 1; color <= 60; ++color) {
            for (int i = top[color]; i <= bottom[color]; ++i) {
                for (int j = left[color]; j <= right[color]; ++j) {
                    if (!vis[i][j] && !dfs(i * n + j, targetGrid, vis, top, bottom, left, right)) {
                        return false;
                    }
                }
            }
        }

        return true;
    }

    private boolean dfs(int x, int[][] targetGrid, boolean[][] vis, int[] top, int[] bottom, int[] left, int[] right) {
        int n = targetGrid[0].length;
        int i = x / n, j = x % n;
        if (vis[i][j]) return true;
        int c = targetGrid[i][j];
        if (i < top[c] || i > bottom[c] || j < left[c] || j > right[c]) return false;
        vis[i][j] = true;
        for (int k = 1; k <= 60; ++k) {
            if (k == c) continue;
            if (i >= top[k] && i <= bottom[k] && j >= left[k] && j <= right[k]) return false;
            if (!dfs(((i-top[k])*(right[k]-left[k]+1)) + j - left[k], targetGrid, vis, top, bottom, left, right)) return false;
        }
        return true;
    }
}
```
We create separate bounds (top, bottom, left, and right) for each color, calculating the boundaries of the rectangle for that color. Then, for each cell in the grid that hasn't been visited, we perform a depth-first search (DFS) from it. The DFS checks if a cell belongs to the current color's boundary; if not, it returns False, causing backtracking in the search.

In each step of the DFS, we skip the current color and check if the cell on the search path belongs to another color's rectangle. If yes, we return False. Otherwise, we continue the DFS with the next cell in the sequence.

Finally, we iterate through all the colors and their rectangles, looking for unvisited cells. If a DFS at any cell location returns False, we can't print the grid, so the overall function returns False. Else, we return True, indicating it's possible to print the matrix targetGrid with the given constraints.

## A solution in C++

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

bool isPrintable(vector<vector<int>>& targetGrid) {
    int m = targetGrid.size(), n = targetGrid[0].size();
    vector<int> top(61, m), bottom(61, -1), left(61, n), right(61, -1);
    vector<vector<bool>> vis(m, vector<bool>(n, false));

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            int c = targetGrid[i][j];
            top[c] = min(top[c], i);
            bottom[c] = max(bottom[c], i);
            left[c] = min(left[c], j);
            right[c] = max(right[c], j);
        }
    }

    function<bool(int)> dfs = [&](int x) {
        int i = x / n, j = x % n;
        if (vis[i][j]) return true;
        int c = targetGrid[i][j];
        if (i < top[c] || i > bottom[c] || j < left[c] || j > right[c]) return false;
        vis[i][j] = true;
        for (int k = 1; k <= 60; ++k) {
            if (k == c) continue;
            if (i >= top[k] && i <= bottom[k] && j >= left[k] && j <= right[k]) return false;
            if (!dfs(((i-top[k])*(right[k]-left[k]+1)) + j - left[k])) return false;
        }
        return true;
    };

    for (int color = 1; color <= 60; ++color) {
        for (int i = top[color]; i <= bottom[color]; ++i) {
            for (int j = left[color]; j <= right[color]; ++j) {
                if (!vis[i][j] && !dfs(i * n + j)) return false;
            }
        }
    }

    return true;
}
```
We create separate bounds (top, bottom, left, and right) for each color, calculating the boundaries of the rectangle for that color. Then, for each cell in the grid that hasn't been visited, we perform a depth-first search (DFS) from it. The DFS checks if a cell belongs to the current color's boundary; if not, it returns False, causing backtracking in the search.

In each step of the DFS, we skip the current color and check if the cell on the search path belongs to another color's rectangle. If yes, we return False. Otherwise, we continue the DFS with the next cell in the sequence.

Finally, we iterate through all the colors and their rectangles, looking for unvisited cells. If a DFS at any cell location returns False, we can't print the grid, so the overall function returns False. Else, we return True, indicating it's possible to print the matrix targetGrid with the given constraints.

## A solution in Python

```python
def isPrintable(targetGrid):
    m, n = len(targetGrid), len(targetGrid[0])
    top, bottom, left, right = [m]*61, [-1]*61, [n]*61, [-1]*61
    vis = [[False]*n for _ in range(m)]

    for i in range(m):
        for j in range(n):
            c = targetGrid[i][j]
            top[c] = min(top[c], i)
            bottom[c] = max(bottom[c], i)
            left[c] = min(left[c], j)
            right[c] = max(right[c], j)

    def dfs(x):
        i, j = x // n, x % n
        if vis[i][j]: return True
        c = targetGrid[i][j]
        if i < top[c] or i > bottom[c] or j < left[c] or j > right[c]: return False
        vis[i][j] = True
        for k in range(1, 61):
            if k == c: continue
            if i >= top[k] and i <= bottom[k] and j >= left[k] and j <= right[k]: return False
            if not dfs(((i-top[k])*(right[k]-left[k]+1)) + j - left[k]): return False
        return True

    for color in range(1, 61):
        for i in range(top[color], bottom[color] + 1):
            for j in range(left[color], right[color] + 1):
                if not vis[i][j] and not dfs(i * n + j): return False

    return True
```
We create separate bounds (top, bottom, left, and right) for each color, calculating the boundaries of the rectangle for that color. Then, for each cell in the grid that hasn't been visited, we perform a depth-first search (DFS) from it. The DFS checks if a cell belongs to the current color's boundary; if not, it returns False, causing backtracking in the search.

In each step of the DFS, we skip the current color and check if the cell on the search path belongs to another color's rectangle. If yes, we return False. Otherwise, we continue the DFS with the next cell in the sequence.

Finally, we iterate through all the colors and their rectangles, looking for unvisited cells. If a DFS at any cell location returns False, we can't print the grid, so the overall function returns False. Else, we return True, indicating it's possible to print the matrix targetGrid with the given constraints.

## A solution in Javascript

```javascript
var isPrintable = function(targetGrid) {
    const m = targetGrid.length, n = targetGrid[0].length;
    const top = Array(61).fill(m), bottom = Array(61).fill(-1), left = Array(61).fill(n), right = Array(61).fill(-1);
    const vis = Array.from({ length: m }, () => Array(n).fill(false));

    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; ++j) {
            const c = targetGrid[i][j];
            top[c] = Math.min(top[c], i);
            bottom[c] = Math.max(bottom[c], i);
            left[c] = Math.min(left[c], j);
            right[c] = Math.max(right[c], j);
        }
    }

    const dfs = (x) => {
        const i = Math.floor(x / n), j = x % n;
        if (vis[i][j]) return true;
        const c = targetGrid[i][j];
        if (i < top[c] || i > bottom[c] || j < left[c] || j > right[c]) return false;
        vis[i][j] = true;
        for (let k = 1; k <= 60; ++k) {
            if (k === c) continue;
            if (i >= top[k] && i <= bottom[k] && j >= left[k] && j <= right[k]) return false;
            if (!dfs(((i-top[k])*(right[k]-left[k]+1)) + j - left[k])) return false;
        }
        return true;
    };

    for (let color = 1; color <= 60; ++color) {
        for (let i = top[color]; i <= bottom[color]; ++i) {
            for (let j = left[color]; j <= right[color]; ++j) {
                if (!vis[i][j] && !dfs(i * n + j)) return false;
            }
        }
    }

    return true;
};
```
We create separate bounds (top, bottom, left, and right) for each color, calculating the boundaries of the rectangle for that color. Then, for each cell in the grid that hasn't been visited, we perform a depth-first search (DFS) from it. The DFS checks if a cell belongs to the current color's boundary; if not, it returns False, causing backtracking in the search.

In each step of the DFS, we skip the current color and check if the cell on the search path belongs to another color's rectangle. If yes, we return False. Otherwise, we continue the DFS with the next cell in the sequence.

Finally, we iterate through all the colors and their rectangles, looking for unvisited cells. If a DFS at any cell location returns False, we can't print the grid, so the overall function returns False. Else, we return True, indicating it's possible to print the matrix targetGrid with the given constraints.


# Checking Existence of Edge Length Limited Paths

- slug: checking-existence-of-edge-length-limited-paths
- difficulty: Hard

An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.

Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance **strictly less than** `limitj` .

Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ `jth` _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_.

**Example 1:**

**Input:** n = 3, edgeList = \[\[0,1,2\],\[1,2,4\],\[2,0,8\],\[1,0,16\]\], queries = \[\[0,1,2\],\[0,2,5\]\]
**Output:** \[false,true\]
**Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.

**Example 2:**

**Input:** n = 5, edgeList = \[\[0,1,10\],\[1,2,5\],\[2,3,9\],\[3,4,13\]\], queries = \[\[0,4,14\],\[1,4,13\]\]
**Output:** \[true,false\]
**Exaplanation:** The above figure shows the given graph.

**Constraints:**

*   `2 <= n <= 105`
*   `1 <= edgeList.length, queries.length <= 105`
*   `edgeList[i].length == 3`
*   `queries[j].length == 3`
*   `0 <= ui, vi, pj, qj <= n - 1`
*   `ui != vi`
*   `pj != qj`
*   `1 <= disi, limitj <= 109`
*   There may be **multiple** edges between two nodes.

## A solution in Java

```java
import java.util.*;

public class Solution {
    public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {
        Map<Integer, List<int[]>> graph = new HashMap<>();

        for (int[] edge : edgeList) {
            graph.putIfAbsent(edge[0], new ArrayList<>());
            graph.putIfAbsent(edge[1], new ArrayList<>());
            graph.get(edge[0]).add(new int[]{edge[1], edge[2]});
            graph.get(edge[1]).add(new int[]{edge[0], edge[2]});
        }

        boolean[] answer = new boolean[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int pj = queries[i][0], qj = queries[i][1], limitj = queries[i][2];

            Queue<int[]> q = new LinkedList<>();
            q.add(new int[]{pj, 0});
            boolean[] visited = new boolean[n];
            visited[pj] = true;

            while (!q.isEmpty()) {
                int[] curr = q.poll();

                for (int[] next : graph.getOrDefault(curr[0], new ArrayList<>())) {
                    if (curr[1] + next[1] < limitj) {
                        if (next[0] == qj) {
                            answer[i] = true;
                            break;
                        }
                        if (!visited[next[0]]) {
                            visited[next[0]] = true;
                            q.add(new int[]{next[0], curr[1] + next[1]});
                        }
                    }
                }
                if (answer[i])
                    break;
            }
        }
        return answer;
    }
}
```
The algorithm first creates a graph representation using adjacency lists. Then, for each query, it performs a modified Breadth-First Search (BFS) starting from the node `pj`. During the BFS, we keep track of the distance travelled so far for each node in the queue. If we find the node `qj` with a distance less than `limitj`, we mark the answer for the current query as `true` and exit the BFS loop. If not, the answer for the current query will be `false`. We repeat this process for all queries and return the result as a boolean array.

## A solution in C++

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

using namespace std;

vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {
    unordered_map<int, vector<pair<int, int>>> graph;
    for (auto& edge : edgeList) {
        graph[edge[0]].emplace_back(edge[1], edge[2]);
        graph[edge[1]].emplace_back(edge[0], edge[2]);
    }

    vector<bool> answer(queries.size());
    for (int i = 0; i < queries.size(); i++) {
        int pj = queries[i][0], qj = queries[i][1], limitj = queries[i][2];

        queue<pair<int, int>> q;
        q.push({pj, 0});
        vector<bool> visited(n, false);
        visited[pj] = true;

        while (!q.empty()) {
            auto curr = q.front();
            q.pop();

            for (auto& next : graph[curr.first]) {
                if (curr.second + next.second < limitj) {
                    if (next.first == qj) {
                        answer[i] = true;
                        break;
                    }
                    if (!visited[next.first]) {
                        visited[next.first] = true;
                        q.push({next.first, curr.second + next.second});
                    }
                }
            }
            if (answer[i])
                break;
        }
    }
    return answer;
}
```
The algorithm first creates a graph representation using adjacency lists. Then, for each query, it performs a modified Breadth-First Search (BFS) starting from the node `pj`. During the BFS, we keep track of the distance travelled so far for each node in the queue. If we find the node `qj` with a distance less than `limitj`, we mark the answer for the current query as `true` and exit the BFS loop. If not, the answer for the current query will be `false`. We repeat this process for all queries and return the result as a boolean array.

## A solution in Python

```python
from collections import defaultdict, deque

def distanceLimitedPathsExist(n, edgeList, queries):
    graph = defaultdict(list)

    for u, v, dis in edgeList:
        graph[u].append((v, dis))
        graph[v].append((u, dis))

    answer = [False] * len(queries)
    for i, (pj, qj, limitj) in enumerate(queries):
        q = deque([(pj, 0)])
        visited = [False] * n
        visited[pj] = True

        while q:
            curr_node, curr_dist = q.popleft()

            for next_node, next_dist in graph[curr_node]:
                if curr_dist + next_dist < limitj:
                    if next_node == qj:
                        answer[i] = True
                        break
                    if not visited[next_node]:
                        visited[next_node] = True
                        q.append((next_node, curr_dist + next_dist))
            if answer[i]:
                break

    return answer
```
The algorithm first creates a graph representation using adjacency lists. Then, for each query, it performs a modified Breadth-First Search (BFS) starting from the node `pj`. During the BFS, we keep track of the distance travelled so far for each node in the queue. If we find the node `qj` with a distance less than `limitj`, we mark the answer for the current query as `true` and exit the BFS loop. If not, the answer for the current query will be `false`. We repeat this process for all queries and return the result as a boolean array.

## A solution in Javascript

```javascript
function distanceLimitedPathsExist(n, edgeList, queries) {
    const graph = new Map();

    for (const [u, v, dis] of edgeList) {
        if (!graph.has(u)) graph.set(u, []);
        if (!graph.has(v)) graph.set(v, []);
        graph.get(u).push([v, dis]);
        graph.get(v).push([u, dis]);
    }

    const answer = new Array(queries.length).fill(false);
    for (let i = 0; i < queries.length; i++) {
        const [pj, qj, limitj] = queries[i];

        const q = [[pj, 0]];
        const visited = new Array(n).fill(false);
        visited[pj] = true;

        while (q.length > 0) {
            const [curr_node, curr_dist] = q.shift();

            for (const [next_node, next_dist] of graph.get(curr_node) || []) {
                if (curr_dist + next_dist < limitj) {
                    if (next_node === qj) {
                        answer[i] = true;
                        break;
                    }
                    if (!visited[next_node]) {
                        visited[next_node] = true;
                        q.push([next_node, curr_dist + next_dist]);
                    }
                }
            }
            if (answer[i]) break;
        }
    }
    return answer;
}
```
The algorithm first creates a graph representation using adjacency lists. Then, for each query, it performs a modified Breadth-First Search (BFS) starting from the node `pj`. During the BFS, we keep track of the distance travelled so far for each node in the queue. If we find the node `qj` with a distance less than `limitj`, we mark the answer for the current query as `true` and exit the BFS loop. If not, the answer for the current query will be `false`. We repeat this process for all queries and return the result as a boolean array.


# Number of Distinct Substrings in a String

- slug: number-of-distinct-substrings-in-a-string
- difficulty: Medium

Given a string `s`, return _the number of **distinct** substrings of_ `s`.

A **substring** of a string is obtained by deleting any number of characters (possibly zero) from the front of the string and any number (possibly zero) from the back of the string.

**Example 1:**

**Input:** s =  "aabbaba "
**Output:** 21
**Explanation:** The set of distinct strings is \[ "a ", "b ", "aa ", "bb ", "ab ", "ba ", "aab ", "abb ", "bab ", "bba ", "aba ", "aabb ", "abba ", "bbab ", "baba ", "aabba ", "abbab ", "bbaba ", "aabbab ", "abbaba ", "aabbaba "\]

**Example 2:**

**Input:** s =  "abcdefg "
**Output:** 28

**Constraints:**

*   `1 <= s.length <= 500`
*   `s` consists of lowercase English letters.

**Follow up:** Can you solve this problem in `O(n)` time complexity?

## A solution in Java

```java
public String modifyString(String s) {
    char[] result = s.toCharArray();
    for (int i = 0; i < result.length; i++) {
        if (result[i] == '?') {
            for (char c = 'a'; c <= 'z'; c++) {
                if ((i - 1 < 0 || result[i - 1] != c) && (i + 1 >= result.length || result[i + 1] != c)) {
                    result[i] = c;
                    break;
                }
            }
        }
    }
    return new String(result);
}
```
The algorithm iterates through each character in the input string s. If it encounters the '?' character, it iterates through the lowercase English alphabet (from 'a' to 'z') and checks if any character doesn't match the adjacent characters (previous and next, if available). If such a character is found, replace the '?' with it and break the character search loop. Once done iterating through the whole string, return the modified string. This ensures that no consecutive repeating characters are there in the final string.

## A solution in C++

```cpp
#include <string>

std::string modifyString(std::string s) {
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == '?') {
            for (char c = 'a'; c <= 'z'; c++) {
                if ((i - 1 < 0 || s[i - 1] != c) && (i + 1 >= s.size() || s[i + 1] != c)) {
                    s[i] = c;
                    break;
                }
            }
        }
    }
    return s;
}
```
The algorithm iterates through each character in the input string s. If it encounters the '?' character, it iterates through the lowercase English alphabet (from 'a' to 'z') and checks if any character doesn't match the adjacent characters (previous and next, if available). If such a character is found, replace the '?' with it and break the character search loop. Once done iterating through the whole string, return the modified string. This ensures that no consecutive repeating characters are there in the final string.

## A solution in Python

```python
def modifyString(s: str) -> str:
    s = list(s)
    for i in range(len(s)):
        if s[i] == '?':
            for c in range(ord('a'), ord('z') + 1):
                if (i - 1 < 0 or s[i - 1] != chr(c)) and (i + 1 >= len(s) or s[i + 1] != chr(c)):
                    s[i] = chr(c)
                    break
    return ''.join(s)
```
The algorithm iterates through each character in the input string s. If it encounters the '?' character, it iterates through the lowercase English alphabet (from 'a' to 'z') and checks if any character doesn't match the adjacent characters (previous and next, if available). If such a character is found, replace the '?' with it and break the character search loop. Once done iterating through the whole string, return the modified string. This ensures that no consecutive repeating characters are there in the final string.

## A solution in Javascript

```javascript
function modifyString(s) {
    s = s.split('');
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '?') {
            for (let c = 'a'.charCodeAt(0); c <= 'z'.charCodeAt(0); c++) {
                if ((i - 1 < 0 || s[i - 1] !== String.fromCharCode(c)) && (i + 1 >= s.length || s[i + 1] !== String.fromCharCode(c))) {
                    s[i] = String.fromCharCode(c);
                    break;
                }
            }
        }
    }
    return s.join('');
}
```
The algorithm iterates through each character in the input string s. If it encounters the '?' character, it iterates through the lowercase English alphabet (from 'a' to 'z') and checks if any character doesn't match the adjacent characters (previous and next, if available). If such a character is found, replace the '?' with it and break the character search loop. Once done iterating through the whole string, return the modified string. This ensures that no consecutive repeating characters are there in the final string.


# Number of Students Unable to Eat Lunch

- slug: number-of-students-unable-to-eat-lunch
- difficulty: Easy

The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.

The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a **stack**. At each step:

*   If the student at the front of the queue **prefers** the sandwich on the top of the stack, they will **take it** and leave the queue.
*   Otherwise, they will **leave it** and go to the queue's end.

This continues until none of the queue students want to take the top sandwich and are thus unable to eat.

You are given two integer arrays `students` and `sandwiches` where `sandwiches[i]` is the type of the `ith` sandwich in the stack (`i = 0` is the top of the stack) and `students[j]` is the preference of the `jth` student in the initial queue (`j = 0` is the front of the queue). Return _the number of students that are unable to eat._

**Example 1:**

**Input:** students = \[1,1,0,0\], sandwiches = \[0,1,0,1\]
**Output:** 0
**Explanation:**
- Front student leaves the top sandwich and returns to the end of the line making students = \[1,0,0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[0,0,1,1\].
- Front student takes the top sandwich and leaves the line making students = \[0,1,1\] and sandwiches = \[1,0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[1,1,0\].
- Front student takes the top sandwich and leaves the line making students = \[1,0\] and sandwiches = \[0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[0,1\].
- Front student takes the top sandwich and leaves the line making students = \[1\] and sandwiches = \[1\].
- Front student takes the top sandwich and leaves the line making students = \[\] and sandwiches = \[\].
Hence all students are able to eat.

**Example 2:**

**Input:** students = \[1,1,1,0,0,1\], sandwiches = \[1,0,0,0,1,1\]
**Output:** 3

**Constraints:**

*   `1 <= students.length, sandwiches.length <= 100`
*   `students.length == sandwiches.length`
*   `sandwiches[i]` is `0` or `1`.
*   `students[i]` is `0` or `1`.

## A solution in Java

```java
public int min_time_to_remove_balloons(String colors, int[] neededTime) {
    int n = colors.length();
    int[][] dp = new int[n][26];
    final int INF = (int) 1e9;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 26; j++) {
            dp[i][j] = INF;
        }
    }

    for (int color = 0; color < 26; color++) {
        if (colors.charAt(0) != 'A' + color) dp[0][color] = neededTime[0];
    }

    for (int i = 1; i < n; i++) {
        for (int color1 = 0; color1 < 26; color1++) {
            for (int color2 = 0; color2 < 26; color2++) {
                if (color1 != color2 && colors.charAt(i) != 'A' + color1) {
                    dp[i][color1] = Math.min(dp[i][color1], dp[i-1][color2] + neededTime[i]);
                }
            }
        }
    }

    int ans = INF;
    for (int color = 0; color < 26; color++) {
        ans = Math.min(ans, dp[n-1][color]);
    }
    return ans;
}
```
The algorithm uses dynamic programming. We maintain a 2D table dp[i][j] that represents the minimum time Bob needs to make the rope colorful up to (and including) the i-th balloon, with the assumption that the i-th balloon's color is changed to color j. Initially, we fill the table with a large value (here, 1e9).

We then loop through each balloon, and for each balloon, we loop through all pairs of colors (26^2 possibilities). For each pair of colors, if the colors are different and the i-th balloon is not of color1, we update dp[i][color1] by taking the minimum between its current value and dp[i - 1][color2] + the time needed to remove the i-th balloon.

After iterating over all balloons and color pairs, we search for the minimum value in the last row of the dp table, as this represents the minimum time needed to make the whole rope colorful.

The time complexity of this algorithm is O(n * 26^2), where n is the length of the string colors, since the algorithm needs to loop through each balloon and all possible color pairs. This complexity is acceptable for the problem's constraints.

## A solution in C++

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

int min_time_to_remove_balloons(const std::string& colors, const std::vector<int>& neededTime) {
    int n = colors.size();
    int dp[n][26];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 26; j++) {
            dp[i][j] = 1e9;
        }
    }

    for (int color = 0; color < 26; color++) {
        if (colors[0] != 'A' + color) dp[0][color] = neededTime[0];
    }

    for (int i = 1; i < n; i++) {
        for (int color1 = 0; color1 < 26; color1++) {
            for (int color2 = 0; color2 < 26; color2++) {
                if (color1 != color2 && colors[i] != 'A' + color1) {
                    dp[i][color1] = std::min(dp[i][color1], dp[i-1][color2] + neededTime[i]);
                }
            }
        }
    }

    int ans = 1e9;
    for (int color = 0; color < 26; color++) {
        ans = std::min(ans, dp[n-1][color]);
    }
    return ans;
}
```
The algorithm uses dynamic programming. We maintain a 2D table dp[i][j] that represents the minimum time Bob needs to make the rope colorful up to (and including) the i-th balloon, with the assumption that the i-th balloon's color is changed to color j. Initially, we fill the table with a large value (here, 1e9).

We then loop through each balloon, and for each balloon, we loop through all pairs of colors (26^2 possibilities). For each pair of colors, if the colors are different and the i-th balloon is not of color1, we update dp[i][color1] by taking the minimum between its current value and dp[i - 1][color2] + the time needed to remove the i-th balloon.

After iterating over all balloons and color pairs, we search for the minimum value in the last row of the dp table, as this represents the minimum time needed to make the whole rope colorful.

The time complexity of this algorithm is O(n * 26^2), where n is the length of the string colors, since the algorithm needs to loop through each balloon and all possible color pairs. This complexity is acceptable for the problem's constraints.

## A solution in Python

```python
def min_time_to_remove_balloons(colors, neededTime):
    n = len(colors)
    INF = 10**9
    dp = [[INF] * 26 for _ in range(n)]

    for color in range(26):
        if colors[0] != chr(ord('A') + color):
            dp[0][color] = neededTime[0]

    for i in range(1, n):
        for color1 in range(26):
            for color2 in range(26):
                if color1 != color2 and colors[i] != chr(ord('A') + color1):
                    dp[i][color1] = min(dp[i][color1], dp[i-1][color2] + neededTime[i])

    ans = INF
    for color in range(26):
        ans = min(ans, dp[n-1][color])

    return ans
```
The algorithm uses dynamic programming. We maintain a 2D table dp[i][j] that represents the minimum time Bob needs to make the rope colorful up to (and including) the i-th balloon, with the assumption that the i-th balloon's color is changed to color j. Initially, we fill the table with a large value (here, 1e9).

We then loop through each balloon, and for each balloon, we loop through all pairs of colors (26^2 possibilities). For each pair of colors, if the colors are different and the i-th balloon is not of color1, we update dp[i][color1] by taking the minimum between its current value and dp[i - 1][color2] + the time needed to remove the i-th balloon.

After iterating over all balloons and color pairs, we search for the minimum value in the last row of the dp table, as this represents the minimum time needed to make the whole rope colorful.

The time complexity of this algorithm is O(n * 26^2), where n is the length of the string colors, since the algorithm needs to loop through each balloon and all possible color pairs. This complexity is acceptable for the problem's constraints.

## A solution in Javascript

```javascript
function min_time_to_remove_balloons(colors, neededTime) {
    const n = colors.length;
    const INF = 1e9;
    let dp = Array.from({ length: n }, () => Array(26).fill(INF));

    for (let color = 0; color < 26; color++) {
        if (colors.charAt(0) !== String.fromCharCode('A'.charCodeAt(0) + color))
            dp[0][color] = neededTime[0];
    }

    for (let i = 1; i < n; i++) {
        for (let color1 = 0; color1 < 26; color1++) {
            for (let color2 = 0; color2 < 26; color2++) {
                if (color1 !== color2 && colors.charAt(i) !== String.fromCharCode('A'.charCodeAt(0) + color1)) {
                    dp[i][color1] = Math.min(dp[i][color1], dp[i - 1][color2] + neededTime[i]);
                }
            }
        }
    }

    let ans = INF;
    for (let color = 0; color < 26; color++) {
        ans = Math.min(ans, dp[n - 1][color]);
    }

    return ans;
}
```
The algorithm uses dynamic programming. We maintain a 2D table dp[i][j] that represents the minimum time Bob needs to make the rope colorful up to (and including) the i-th balloon, with the assumption that the i-th balloon's color is changed to color j. Initially, we fill the table with a large value (here, 1e9).

We then loop through each balloon, and for each balloon, we loop through all pairs of colors (26^2 possibilities). For each pair of colors, if the colors are different and the i-th balloon is not of color1, we update dp[i][color1] by taking the minimum between its current value and dp[i - 1][color2] + the time needed to remove the i-th balloon.

After iterating over all balloons and color pairs, we search for the minimum value in the last row of the dp table, as this represents the minimum time needed to make the whole rope colorful.

The time complexity of this algorithm is O(n * 26^2), where n is the length of the string colors, since the algorithm needs to loop through each balloon and all possible color pairs. This complexity is acceptable for the problem's constraints.


# Average Waiting Time

- slug: average-waiting-time
- difficulty: Medium

There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:`

*   `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order.
*   `timei` is the time needed to prepare the order of the `ith` customer.

When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**.

Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted.

**Example 1:**

**Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\]
**Output:** 5.00000
**Explanation:**
1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.
2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.
3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.
So the average waiting time = (2 + 6 + 7) / 3 = 5.

**Example 2:**

**Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\]
**Output:** 3.25000
**Explanation:**
1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.
2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.
3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.
4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.
So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.

**Constraints:**

*   `1 <= customers.length <= 105`
*   `1 <= arrivali, timei <= 104`
*   `arrivali <= arrivali+1`

## A solution in Java

```java
public int maxNumEdgesToRemove(int n, int[][] edges) {
    int[] parent = new int[2 * n + 1];
    for (int i = 0; i <= 2 * n; ++i) parent[i] = i;
    int[] ct = new int[2], both = new int[]{n - 1};

    Arrays.sort(edges, (o1, o2) -> Integer.compare(o2[0], o1[0]));
    for (int[] edge : edges) {
        if (edge[0] == 3 && unite(parent, edge[1], edge[2] + n)) --both[0];
        if (both[0] == 0) break;
    }

    for (int type = 1; type < 3; ++type) {
        for (int[] edge : edges) {
            if (edge[0] == type && unite(parent, edge[1], edge[2] + n)) ++ct[type - 1];
        }
        if (both[type - 1] + ct[type - 1] < n - 1) return -1;
    }
    return ct[0] + ct[1] - n + 1;
}

private boolean unite(int[] parent, int u, int v) {
    u = find(parent, u);
    v = find(parent, v);
    if (u != v) {
        parent[u] = v;
        return true;
    }
    return false;
}

private int find(int[] parent, int u) {
    return parent[u] == u ? u : (parent[u] = find(parent, parent[u]));
}
```
1. Initialize the parent array for the union-find data structure for each node, twice the size of n (to handle both Alice and Bob).
2. Define find and unite functions for the union-find data structure.
3. Sort the edges in descending order based on their type.
4. Iterate through the edges, and only process type 3 (common) edges.
5. During the iteration, attempt to unite the current edge nodes. If successful, decrement the remaining edges to be fully traversed (both variable).
6. Once both variable becomes 0, break from the loop.
7. For each type (Alice or Bob):
   * Iterate through the edges
   * If the edge type matches the current type and the edge can be united, increment the count for the current type.
   * If the total count of edges for fully traversal by Alice and Bob is less than the required number, return -1 as it is impossible.
8. Finally, return the total count of removed edges.

## A solution in C++

```cpp
int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) {
    vector<int> parent(2 * n + 1);
    iota(parent.begin(), parent.end(), 0);
    function<int(int)> find = [&](int x) { return x == parent[x] ? x : parent[x] = find(parent[x]); };
    auto unite = [&](int x, int y) { x = find(x); y = find(y); if (x != y) return parent[x] = y, true; return false; };
    sort(edges.begin(), edges.end(), greater<vector<int>>());
    int ans = 0, both = n - 1;
    for (auto &edge : edges) {
        int type, u, v; tie(type, u, v) = make_tuple(edge[0], edge[1], edge[2] + n);
        if (type == 3) if (unite(u, v)) --both;
        if (!both) break;
    }
    for (int type = 1; type < 3; ++type) {
        int ct = 0;
        for (auto &edge : edges) {
            int a, u, v; tie(a, u, v) = make_tuple(edge[0], edge[1], edge[2] + n);
            if (a == type) if (unite(u, v)) ++ct;
        }
        if (both + ct < n - 1) return -1;
        ans += ct;
    }
    return ans;
}
```
1. Initialize the parent array for the union-find data structure for each node, twice the size of n (to handle both Alice and Bob).
2. Define find and unite functions for the union-find data structure.
3. Sort the edges in descending order based on their type.
4. Iterate through the edges, and only process type 3 (common) edges.
5. During the iteration, attempt to unite the current edge nodes. If successful, decrement the remaining edges to be fully traversed (both variable).
6. Once both variable becomes 0, break from the loop.
7. For each type (Alice or Bob):
   * Iterate through the edges
   * If the edge type matches the current type and the edge can be united, increment the count for the current type.
   * If the total count of edges for fully traversal by Alice and Bob is less than the required number, return -1 as it is impossible.
8. Finally, return the total count of removed edges.

## A solution in Python

```python
def maxNumEdgesToRemove(n, edges):
    def find(u):
        if parent[u] == u:
            return u
        else:
            parent[u] = find(parent[u])
            return parent[u]

    def unite(u, v):
        u = find(u)
        v = find(v)
        if u != v:
            parent[u] = v
            return True
        return False

    parent = list(range(2 * n + 1))
    ct = [0, 0]
    both = n - 1
    edges.sort(reverse=True)
    for edge in edges:
        type, u, v = edge
        if type == 3 and unite(u, v + n):
            both -= 1
        if both == 0:
            break

    for type in range(1, 3):
        for edge in edges:
            a, u, v = edge
            if a == type and unite(u, v + n):
                ct[type - 1] += 1
        if both + ct[type - 1] < n - 1:
            return -1

    return ct[0] + ct[1] - n + 1
```
1. Initialize the parent array for the union-find data structure for each node, twice the size of n (to handle both Alice and Bob).
2. Define find and unite functions for the union-find data structure.
3. Sort the edges in descending order based on their type.
4. Iterate through the edges, and only process type 3 (common) edges.
5. During the iteration, attempt to unite the current edge nodes. If successful, decrement the remaining edges to be fully traversed (both variable).
6. Once both variable becomes 0, break from the loop.
7. For each type (Alice or Bob):
   * Iterate through the edges
   * If the edge type matches the current type and the edge can be united, increment the count for the current type.
   * If the total count of edges for fully traversal by Alice and Bob is less than the required number, return -1 as it is impossible.
8. Finally, return the total count of removed edges.

## A solution in Javascript

```javascript
function maxNumEdgesToRemove(n, edges) {
    let parent = new Array(2 * n + 1).fill().map((_, i) => i);

    function find(u) {
        return parent[u] === u ? u : parent[u] = find(parent[u]);
    }

    function unite(u, v) {
        u = find(u);
        v = find(v);
        if (u !== v) {
            parent[u] = v;
            return true;
        }
        return false;
    }

    edges.sort((a, b) => b[0] - a[0]);
    let ct = [0, 0];
    let both = n - 1;
    for (let edge of edges) {
        if (edge[0] === 3 && unite(edge[1], edge[2] + n)) {
            both--;
        }
        if (both === 0) break;
    }

    for (let type = 1; type < 3; type++) {
        for (let edge of edges) {
            if (edge[0] === type && unite(edge[1], edge[2] + n)) {
                ct[type - 1]++;
            }
        }
        if (both + ct[type - 1] < n - 1) {
            return -1;
        }
    }

    return ct[0] + ct[1] - n + 1;
}
```
1. Initialize the parent array for the union-find data structure for each node, twice the size of n (to handle both Alice and Bob).
2. Define find and unite functions for the union-find data structure.
3. Sort the edges in descending order based on their type.
4. Iterate through the edges, and only process type 3 (common) edges.
5. During the iteration, attempt to unite the current edge nodes. If successful, decrement the remaining edges to be fully traversed (both variable).
6. Once both variable becomes 0, break from the loop.
7. For each type (Alice or Bob):
   * Iterate through the edges
   * If the edge type matches the current type and the edge can be united, increment the count for the current type.
   * If the total count of edges for fully traversal by Alice and Bob is less than the required number, return -1 as it is impossible.
8. Finally, return the total count of removed edges.


# Maximum Binary String After Change

- slug: maximum-binary-string-after-change
- difficulty: Medium

You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times:

*   Operation 1: If the number contains the substring `"00 "`, you can replace it with `"10 "`.
    *   For example, `"00010 " -> "10010` "
*   Operation 2: If the number contains the substring `"10 "`, you can replace it with `"01 "`.
    *   For example, `"00010 " -> "00001 "`

_Return the **maximum binary string** you can obtain after any number of operations. Binary string `x` is greater than binary string `y` if `x`'s decimal representation is greater than `y`'s decimal representation._

**Example 1:**

**Input:** binary =  "000110 "
**Output:**  "111011 "
**Explanation:** A valid transformation sequence can be:
 "000110 " ->  "000101 "
 "000101 " ->  "100101 "
 "100101 " ->  "110101 "
 "110101 " ->  "110011 "
 "110011 " ->  "111011 "

**Example 2:**

**Input:** binary =  "01 "
**Output:**  "01 "
**Explanation:**  "01 " cannot be transformed any further.

**Constraints:**

*   `1 <= binary.length <= 105`
*   `binary` consist of `'0'` and `'1'`.

## A solution in Java

```java
public String maximumBinaryString(String binary) {
    int zeroCount = 0;
    int oneCount = 0;

    for (char c : binary.toCharArray()) {
        if (c == '0') {
            zeroCount++;
        } else {
            oneCount++;
        }
    }

    if (zeroCount <= 1) {
        return binary;
    }

    StringBuilder result = new StringBuilder();
    for (int i = 0; i < oneCount; ++i) {
        result.append('1');
    }
    for (int i = 0; i < zeroCount - 1; ++i) {
        result.append('0');
    }
    result.append("1####1");
    return result.substring(0, binary.length());
}
```
The algorithm starts by counting the number of zeros and ones in the given binary string. If there is one or no zeros, the binary string cannot be further transformed, so we return the original binary string.

If there is more than one zero, the goal is to group all the ones together and place them before any zeros. This will create the maximum binary string. To do this, we first append ones to the result string `oneCount` times. Then we append zeros `zeroCount - 1` times (since we are going to insert a one in between these zeros). Finally, we add a dummy string "1####1" to force the zeros to be at least as long as the original binary string, and we then truncate the result back to the original binary string length.

The time complexity of this algorithm is O(n) as we loop through the binary string once to count zeros and ones, and then another two times to construct the result string. The space complexity is also O(n) as we store the result string.

## A solution in C++

```cpp
#include <string>

std::string maximumBinaryString(std::string binary) {
    int zeroCount = 0;
    int oneCount = 0;

    for (char c : binary) {
        if (c == '0') {
            zeroCount++;
        } else {
            oneCount++;
        }
    }

    if (zeroCount <= 1) {
        return binary;
    }

    std::string result = "";
    for (int i = 0; i < oneCount; ++i) {
        result += '1';
    }
    for (int i = 0; i < zeroCount - 1; ++i) {
        result += '0';
    }
    result += "1####1";
    return result.substr(0, binary.length());
}
```
The algorithm starts by counting the number of zeros and ones in the given binary string. If there is one or no zeros, the binary string cannot be further transformed, so we return the original binary string.

If there is more than one zero, the goal is to group all the ones together and place them before any zeros. This will create the maximum binary string. To do this, we first append ones to the result string `oneCount` times. Then we append zeros `zeroCount - 1` times (since we are going to insert a one in between these zeros). Finally, we add a dummy string "1####1" to force the zeros to be at least as long as the original binary string, and we then truncate the result back to the original binary string length.

The time complexity of this algorithm is O(n) as we loop through the binary string once to count zeros and ones, and then another two times to construct the result string. The space complexity is also O(n) as we store the result string.

## A solution in Python

```python
def maximum_binary_string(binary: str) -> str:
    zero_count = binary.count('0')

    if zero_count <= 1:
        return binary

    one_count = len(binary) - zero_count

    result = "1" * one_count + "0" * (zero_count - 1) + "1####1"
    return result[:len(binary)]
```
The algorithm starts by counting the number of zeros and ones in the given binary string. If there is one or no zeros, the binary string cannot be further transformed, so we return the original binary string.

If there is more than one zero, the goal is to group all the ones together and place them before any zeros. This will create the maximum binary string. To do this, we first append ones to the result string `oneCount` times. Then we append zeros `zeroCount - 1` times (since we are going to insert a one in between these zeros). Finally, we add a dummy string "1####1" to force the zeros to be at least as long as the original binary string, and we then truncate the result back to the original binary string length.

The time complexity of this algorithm is O(n) as we loop through the binary string once to count zeros and ones, and then another two times to construct the result string. The space complexity is also O(n) as we store the result string.

## A solution in Javascript

```javascript
function maximumBinaryString(binary) {
    let zeroCount = 0;
    let oneCount = 0;

    for (const c of binary) {
        if (c === '0') {
            zeroCount++;
        } else {
            oneCount++;
        }
    }

    if (zeroCount <= 1) {
        return binary;
    }

    let result = "";
    for (let i = 0; i < oneCount; ++i) {
        result += '1';
    }
    for (let i = 0; i < zeroCount - 1; ++i) {
        result += '0';
    }
    result += "1####1";
    return result.substr(0, binary.length);
}
```
The algorithm starts by counting the number of zeros and ones in the given binary string. If there is one or no zeros, the binary string cannot be further transformed, so we return the original binary string.

If there is more than one zero, the goal is to group all the ones together and place them before any zeros. This will create the maximum binary string. To do this, we first append ones to the result string `oneCount` times. Then we append zeros `zeroCount - 1` times (since we are going to insert a one in between these zeros). Finally, we add a dummy string "1####1" to force the zeros to be at least as long as the original binary string, and we then truncate the result back to the original binary string length.

The time complexity of this algorithm is O(n) as we loop through the binary string once to count zeros and ones, and then another two times to construct the result string. The space complexity is also O(n) as we store the result string.


# Minimum Adjacent Swaps for K Consecutive Ones

- slug: minimum-adjacent-swaps-for-k-consecutive-ones
- difficulty: Hard

You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values.

Return _the **minimum** number of moves required so that_ `nums` _has_ `k` _**consecutive**_ `1`_'s_.

**Example 1:**

**Input:** nums = \[1,0,0,1,0,1\], k = 2
**Output:** 1
**Explanation:** In 1 move, nums could be \[1,0,0,0,1,1\] and have 2 consecutive 1's.

**Example 2:**

**Input:** nums = \[1,0,0,0,0,0,1,1\], k = 3
**Output:** 5
**Explanation:** In 5 moves, the leftmost 1 can be shifted right until nums = \[0,0,0,0,0,1,1,1\].

**Example 3:**

**Input:** nums = \[1,1,0,1\], k = 2
**Output:** 0
**Explanation:** nums already has 2 consecutive 1's.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `nums[i]` is `0` or `1`.
*   `1 <= k <= sum(nums)`

## A solution in Java

```java
public int minMoves(int[] nums, int k) {
    List<Integer> ones_pos = new ArrayList<>();
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 1) {
            ones_pos.add(i - ones_pos.size());
        }
    }
    int sum = 0;
    for (int i = 0; i < k; i++) {
        sum += ones_pos.get(i);
    }
    int min_sum = sum;
    for (int i = k; i < ones_pos.size(); i++) {
        sum += ones_pos.get(i) - ones_pos.get(i - k);
        min_sum = Math.min(min_sum, sum);
    }
    return min_sum - (k - 1) * k / 2;
}
```
The algorithm finds the positions of all the 1s in the input array. Then, it calculates the differences between positions and takes out the prefix sum of differences. After that, it finds the minimum sum of the differences for the sliding window of size `k`. The final result is the minimum sum of differences minus the sum of integers from 0 to `k - 1`. All the implementations follow the above algorithm and are adjusted to work with the respective languages.

## A solution in C++

```cpp
int minMoves(vector<int>& nums, int k) {
    vector<int> ones_pos;
    int moves = 0;
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] == 1) {
            ones_pos.push_back(i);
        }
    }
    for (int i = 0; i + k <= ones_pos.size(); i++) {
        int pos = ones_pos[i + k / 2];
        for (int j = i; j < i + k; j++) {
            moves += abs(ones_pos[j] - pos);
        }
    }
    return moves;
}
```
The algorithm finds the positions of all the 1s in the input array. Then, it calculates the differences between positions and takes out the prefix sum of differences. After that, it finds the minimum sum of the differences for the sliding window of size `k`. The final result is the minimum sum of differences minus the sum of integers from 0 to `k - 1`. All the implementations follow the above algorithm and are adjusted to work with the respective languages.

## A solution in Python

```python
def minMoves(nums, k):
    ones_pos = [i for i, x in enumerate(nums) if x == 1]
    to_move = [i_b - i_a for i_a, i_b in zip(range(k), ones_pos)]
    min_moves = sum(to_move[k // 2:])
    move = min_moves
    for left, right in zip(
        to_move[:-k],       # left "window" of k-sized sliding window
        to_move[k // 2 + 1:],  # right "window" of k-sized sliding window
    ):
        move += left - right
        min_moves = min(min_moves, move)
    return min_moves
```
The algorithm finds the positions of all the 1s in the input array. Then, it calculates the differences between positions and takes out the prefix sum of differences. After that, it finds the minimum sum of the differences for the sliding window of size `k`. The final result is the minimum sum of differences minus the sum of integers from 0 to `k - 1`. All the implementations follow the above algorithm and are adjusted to work with the respective languages.

## A solution in Javascript

```javascript
function minMoves(nums, k) {
    const ones_pos = [];
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] === 1) {
            ones_pos.push(i - ones_pos.length);
        }
    }
    let sum = 0;
    for (let i = 0; i < k; i++) {
        sum += ones_pos[i];
    }
    let min_sum = sum;
    for (let i = k; i < ones_pos.length; i++) {
        sum += ones_pos[i] - ones_pos[i - k];
        min_sum = Math.min(min_sum, sum);
    }
    return min_sum - (k - 1) * k / 2;
}
```
The algorithm finds the positions of all the 1s in the input array. Then, it calculates the differences between positions and takes out the prefix sum of differences. After that, it finds the minimum sum of the differences for the sliding window of size `k`. The final result is the minimum sum of differences minus the sum of integers from 0 to `k - 1`. All the implementations follow the above algorithm and are adjusted to work with the respective languages.


# Determine if String Halves Are Alike

- slug: determine-if-string-halves-are-alike
- difficulty: Easy

You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.

Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.

Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.

**Example 1:**

**Input:** s =  "book "
**Output:** true
**Explanation:** a =  "bo " and b =  "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.

**Example 2:**

**Input:** s =  "textbook "
**Output:** false
**Explanation:** a =  "text " and b =  "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.

**Constraints:**

*   `2 <= s.length <= 1000`
*   `s.length` is even.
*   `s` consists of **uppercase and lowercase** letters.

## A solution in Java

```java
public int numSpecial(int[][] mat) {
    int m = mat.length, n = mat[0].length;
    int[] row = new int[m], col = new int[n];

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (mat[i][j] == 1) {
                ++row[i];
                ++col[j];
            }
        }
    }

    int special_positions = 0;
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) {
                ++special_positions;
            }
        }
    }

    return special_positions;
}
```
1. First, initialize variables `m` and `n` to be the number of rows and columns of the given matrix `mat`. Also, create two vectors `row` and `col` of size `m` and `n` respectively, and initialize them with all zeros. These vectors will be used to store the one's count of each row and column in the matrix.
2. For each cell of the matrix, add 1 to the corresponding row and column vectors' elements if the cell value is 1. Thus, by the end of the nested loop, we'll have the count of one's in each row and column in our `row` and `col` vectors.
3. Now, iterate over each cell of the matrix once again. If the cell value is 1, and the corresponding row and column count in `row` and `col` vectors are both 1, increment the special_positions count.
4. Finally, return the special_positions count, which represents the number of special positions in the matrix `mat`.

## A solution in C++

```cpp
int numSpecial(vector<vector<int>>& mat) {
    int m = mat.size(), n = mat[0].size();
    vector<int> row(m, 0), col(n, 0);

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (mat[i][j] == 1) {
                ++row[i];
                ++col[j];
            }
        }
    }

    int special_positions = 0;
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) {
                ++special_positions;
            }
        }
    }

    return special_positions;
}
```
1. First, initialize variables `m` and `n` to be the number of rows and columns of the given matrix `mat`. Also, create two vectors `row` and `col` of size `m` and `n` respectively, and initialize them with all zeros. These vectors will be used to store the one's count of each row and column in the matrix.
2. For each cell of the matrix, add 1 to the corresponding row and column vectors' elements if the cell value is 1. Thus, by the end of the nested loop, we'll have the count of one's in each row and column in our `row` and `col` vectors.
3. Now, iterate over each cell of the matrix once again. If the cell value is 1, and the corresponding row and column count in `row` and `col` vectors are both 1, increment the special_positions count.
4. Finally, return the special_positions count, which represents the number of special positions in the matrix `mat`.

## A solution in Python

```python
def numSpecial(mat):
    m, n = len(mat), len(mat[0])
    row, col = [0] * m, [0] * n

    for i in range(m):
        for j in range(n):
            if mat[i][j] == 1:
                row[i] += 1
                col[j] += 1

    special_positions = 0
    for i in range(m):
        for j in range(n):
            if mat[i][j] == 1 and row[i] == 1 and col[j] == 1:
                special_positions += 1

    return special_positions
```
1. First, initialize variables `m` and `n` to be the number of rows and columns of the given matrix `mat`. Also, create two vectors `row` and `col` of size `m` and `n` respectively, and initialize them with all zeros. These vectors will be used to store the one's count of each row and column in the matrix.
2. For each cell of the matrix, add 1 to the corresponding row and column vectors' elements if the cell value is 1. Thus, by the end of the nested loop, we'll have the count of one's in each row and column in our `row` and `col` vectors.
3. Now, iterate over each cell of the matrix once again. If the cell value is 1, and the corresponding row and column count in `row` and `col` vectors are both 1, increment the special_positions count.
4. Finally, return the special_positions count, which represents the number of special positions in the matrix `mat`.

## A solution in Javascript

```javascript
function numSpecial(mat) {
    let m = mat.length, n = mat[0].length;
    let row = new Array(m).fill(0), col = new Array(n).fill(0);

    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; ++j) {
            if (mat[i][j] == 1) {
                ++row[i];
                ++col[j];
            }
        }
    }

    let special_positions = 0;
    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; ++j) {
            if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) {
                ++special_positions;
            }
        }
    }

    return special_positions;
}
```
1. First, initialize variables `m` and `n` to be the number of rows and columns of the given matrix `mat`. Also, create two vectors `row` and `col` of size `m` and `n` respectively, and initialize them with all zeros. These vectors will be used to store the one's count of each row and column in the matrix.
2. For each cell of the matrix, add 1 to the corresponding row and column vectors' elements if the cell value is 1. Thus, by the end of the nested loop, we'll have the count of one's in each row and column in our `row` and `col` vectors.
3. Now, iterate over each cell of the matrix once again. If the cell value is 1, and the corresponding row and column count in `row` and `col` vectors are both 1, increment the special_positions count.
4. Finally, return the special_positions count, which represents the number of special positions in the matrix `mat`.


# Maximum Number of Eaten Apples

- slug: maximum-number-of-eaten-apples
- difficulty: Medium

There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`.

You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days.

Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._

**Example 1:**

**Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\]
**Output:** 7
**Explanation:** You can eat 7 apples:
- On the first day, you eat an apple that grew on the first day.
- On the second day, you eat an apple that grew on the second day.
- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.
- On the fourth to the seventh days, you eat apples that grew on the fourth day.

**Example 2:**

**Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\]
**Output:** 5
**Explanation:** You can eat 5 apples:
- On the first to the third day you eat apples that grew on the first day.
- Do nothing on the fouth and fifth days.
- On the sixth and seventh days you eat apples that grew on the sixth day.

**Constraints:**

*   `n == apples.length == days.length`
*   `1 <= n <= 2 * 104`
*   `0 <= apples[i], days[i] <= 2 * 104`
*   `days[i] = 0` if and only if `apples[i] = 0`.

## A solution in Java

```java
public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
    int[] pairMapping = new int[n];
    for (int[] pair : pairs) {
        pairMapping[pair[0]] = pair[1];
        pairMapping[pair[1]] = pair[0];
    }

    int unhappyCount = 0;
    for (int x = 0; x < n; x++) {
        int y = pairMapping[x];
        int[] prefX = preferences[x];
        int idxY = -1;
        for (int i = 0; i < prefX.length; i++) {
            if (prefX[i] == y) {
                idxY = i;
                break;
            }
        }

        for (int i = 0; i < idxY; i++) {
            int u = prefX[i];
            int v = pairMapping[u];
            int[] prefU = preferences[u];
            for (int j = 0; j < prefU.length; j++) {
                if (prefU[j] == x) {
                    unhappyCount++;
                    break;
                } else if (prefU[j] == v) {
                    break;
                }
            }
        }
    }

    return unhappyCount / 2;
}
```
1. Initialize a pair_mapping array to store the pairings given in pairs.
2. Loop through each friend (denoted by x in the for loop) from 0 to n.
3. Check the y position in x's preference list.
4. Loop through friends 0 to y position in x's preference list (excluding y).
5. For each friend u, who x prefers more than y, check if u prefers x over its paired friend v.
6. If u does prefer x over v, increment the unhappy_count and break the loop.
7. Once all friends are checked, return half the value of the unhappy_count, as each unhappy friend is counted twice.

## A solution in C++

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

int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) {
    vector<int> pair_mapping(n);
    for (vector<int>& pair : pairs) {
        pair_mapping[pair[0]] = pair[1];
        pair_mapping[pair[1]] = pair[0];
    }

    int unhappy_count = 0;
    for (int x = 0; x < n; x++) {
        int y = pair_mapping[x];
        vector<int>& pref_x = preferences[x];
        int idx_y = -1;
        for (int i = 0; i < pref_x.size(); i++) {
            if (pref_x[i] == y) {
                idx_y = i;
                break;
            }
        }

        for (int i = 0; i < idx_y; i++) {
            int u = pref_x[i];
            int v = pair_mapping[u];
            vector<int>& pref_u = preferences[u];
            for (int j = 0; j < pref_u.size(); j++) {
                if (pref_u[j] == x) {
                    unhappy_count++;
                    break;
                } else if (pref_u[j] == v) {
                    break;
                }
            }
        }
    }

    return unhappy_count / 2;
}
```
1. Initialize a pair_mapping array to store the pairings given in pairs.
2. Loop through each friend (denoted by x in the for loop) from 0 to n.
3. Check the y position in x's preference list.
4. Loop through friends 0 to y position in x's preference list (excluding y).
5. For each friend u, who x prefers more than y, check if u prefers x over its paired friend v.
6. If u does prefer x over v, increment the unhappy_count and break the loop.
7. Once all friends are checked, return half the value of the unhappy_count, as each unhappy friend is counted twice.

## A solution in Python

```python
def unhappyFriends(n, preferences, pairs):
    pair_mapping = [0] * n
    for pair in pairs:
        pair_mapping[pair[0]] = pair[1]
        pair_mapping[pair[1]] = pair[0]

    unhappy_count = 0
    for x in range(n):
        y = pair_mapping[x]
        pref_x = preferences[x]
        idx_y = pref_x.index(y)

        for i in range(idx_y):
            u = pref_x[i]
            v = pair_mapping[u]
            pref_u = preferences[u]
            if x in pref_u[:pref_u.index(v)]:
                unhappy_count += 1
                break

    return unhappy_count // 2
```
1. Initialize a pair_mapping array to store the pairings given in pairs.
2. Loop through each friend (denoted by x in the for loop) from 0 to n.
3. Check the y position in x's preference list.
4. Loop through friends 0 to y position in x's preference list (excluding y).
5. For each friend u, who x prefers more than y, check if u prefers x over its paired friend v.
6. If u does prefer x over v, increment the unhappy_count and break the loop.
7. Once all friends are checked, return half the value of the unhappy_count, as each unhappy friend is counted twice.

## A solution in Javascript

```javascript
function unhappyFriends(n, preferences, pairs) {
    const pairMapping = new Array(n);
    for (const pair of pairs) {
        pairMapping[pair[0]] = pair[1];
        pairMapping[pair[1]] = pair[0];
    }

    let unhappyCount = 0;
    for (let x = 0; x < n; x++) {
        const y = pairMapping[x];
        const prefX = preferences[x];
        const idxY = prefX.indexOf(y);

        for (let i = 0; i < idxY; i++) {
            const u = prefX[i];
            const v = pairMapping[u];
            const prefU = preferences[u];
            const idxV = prefU.indexOf(v);
            if (prefU.indexOf(x) < idxV) {
                unhappyCount++;
                break;
            }
        }
    }

    return Math.floor(unhappyCount / 2);
}
```
1. Initialize a pair_mapping array to store the pairings given in pairs.
2. Loop through each friend (denoted by x in the for loop) from 0 to n.
3. Check the y position in x's preference list.
4. Loop through friends 0 to y position in x's preference list (excluding y).
5. For each friend u, who x prefers more than y, check if u prefers x over its paired friend v.
6. If u does prefer x over v, increment the unhappy_count and break the loop.
7. Once all friends are checked, return half the value of the unhappy_count, as each unhappy friend is counted twice.


# Where Will the Ball Fall

- slug: where-will-the-ball-fall
- difficulty: Medium

You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.

Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.

*   A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`.
*   A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`.

We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box.

Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._

**Example 1:**

**Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\]
**Output:** \[1,-1,-1,-1,-1\]
**Explanation:** This example is shown in the photo.
Ball b0 is dropped at column 0 and falls out of the box at column 1.
Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.
Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.
Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.
Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.

**Example 2:**

**Input:** grid = \[\[-1\]\]
**Output:** \[-1\]
**Explanation:** The ball gets stuck against the left wall.

**Example 3:**

**Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\]
**Output:** \[0,1,2,3,4,-1\]

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 100`
*   `grid[i][j]` is `1` or `-1`.

## A solution in Java

```java
import java.util.Arrays;

public int minCostConnectPoints(int[][] points) {
    int n = points.length;
    int[] cost = new int[n];
    boolean[] visited = new boolean[n];
    Arrays.fill(cost, Integer.MAX_VALUE);
    cost[0] = 0;

    int ans = 0;

    for (int i = 0; i < n; i++) {
        int min_cost = Integer.MAX_VALUE;
        int cur_point = -1;
        for (int j = 0; j < n; j++) {
            if (!visited[j] && cost[j] < min_cost) {
                min_cost = cost[j];
                cur_point = j;
            }
        }

        visited[cur_point] = true;
        ans += min_cost;

        for (int j = 0; j < n; j++) {
            if (!visited[j]) {
                int new_cost = Math.abs(points[cur_point][0] - points[j][0]) + Math.abs(points[cur_point][1] - points[j][1]);
                cost[j] = Math.min(cost[j], new_cost);
            }
        }
    }

    return ans;
}
```
The solution uses Prim's algorithm for constructing a minimum spanning tree. Prim's algorithm maintains a tree of visited points and a set of unvisited points. Initially, the tree contains just one point (selected arbitrarily), and the set contains all other points. We repeat the following steps until all points are visited:

1. Find the point in the unvisited set with the minimum cost to connect it to any point in the visited set. Call this point the current point and add it to the visited set.
2. Update the costs of all unvisited points by calculating the Manhattan distance between the current point and each unvisited point. If this distance is smaller than the previously recorded cost for the unvisited point, replace the cost.

The total cost of the minimum spanning tree is the sum of connection costs for all points added to the visited set.

## A solution in C++

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

int minCostConnectPoints(std::vector<std::vector<int>>& points) {
    int n = points.size();
    std::vector<int> cost(n);
    std::vector<bool> visited(n, false);
    std::fill(cost.begin(), cost.end(), INT_MAX);
    cost[0] = 0;

    int ans = 0;

    for (int i = 0; i < n; ++i) {
        int min_cost = INT_MAX;
        int cur_point = -1;
        for (int j = 0; j < n; ++j) {
            if (!visited[j] && cost[j] < min_cost) {
                min_cost = cost[j];
                cur_point = j;
            }
        }

        visited[cur_point] = true;
        ans += min_cost;

        for (int j = 0; j < n; ++j) {
            if (!visited[j]) {
                int new_cost = std::abs(points[cur_point][0] - points[j][0]) + std::abs(points[cur_point][1] - points[j][1]);
                cost[j] = std::min(cost[j], new_cost);
            }
        }
    }

    return ans;
}
```
The solution uses Prim's algorithm for constructing a minimum spanning tree. Prim's algorithm maintains a tree of visited points and a set of unvisited points. Initially, the tree contains just one point (selected arbitrarily), and the set contains all other points. We repeat the following steps until all points are visited:

1. Find the point in the unvisited set with the minimum cost to connect it to any point in the visited set. Call this point the current point and add it to the visited set.
2. Update the costs of all unvisited points by calculating the Manhattan distance between the current point and each unvisited point. If this distance is smaller than the previously recorded cost for the unvisited point, replace the cost.

The total cost of the minimum spanning tree is the sum of connection costs for all points added to the visited set.

## A solution in Python

```python
def minCostConnectPoints(points):
    n = len(points)
    cost = [float('inf')] * n
    visited = [False] * n
    cost[0] = 0

    ans = 0

    for _ in range(n):
        min_cost = float('inf')
        cur_point = -1
        for j in range(n):
            if not visited[j] and cost[j] < min_cost:
                min_cost = cost[j]
                cur_point = j

        visited[cur_point] = True
        ans += min_cost

        for j in range(n):
            if not visited[j]:
                new_cost = abs(points[cur_point][0] - points[j][0]) + abs(points[cur_point][1] - points[j][1])
                cost[j] = min(cost[j], new_cost)

    return ans
```
The solution uses Prim's algorithm for constructing a minimum spanning tree. Prim's algorithm maintains a tree of visited points and a set of unvisited points. Initially, the tree contains just one point (selected arbitrarily), and the set contains all other points. We repeat the following steps until all points are visited:

1. Find the point in the unvisited set with the minimum cost to connect it to any point in the visited set. Call this point the current point and add it to the visited set.
2. Update the costs of all unvisited points by calculating the Manhattan distance between the current point and each unvisited point. If this distance is smaller than the previously recorded cost for the unvisited point, replace the cost.

The total cost of the minimum spanning tree is the sum of connection costs for all points added to the visited set.

## A solution in Javascript

```javascript
function minCostConnectPoints(points) {
    const n = points.length;
    const cost = new Array(n).fill(Infinity);
    const visited = new Array(n).fill(false);
    cost[0] = 0;

    let ans = 0;

    for (let i = 0; i < n; i++) {
        let min_cost = Infinity;
        let cur_point = -1;
        for (let j = 0; j < n; j++) {
            if (!visited[j] && cost[j] < min_cost) {
                min_cost = cost[j];
                cur_point = j;
            }
        }

        visited[cur_point] = true;
        ans += min_cost;

        for (let j = 0; j < n; j++) {
            if (!visited[j]) {
                const new_cost = Math.abs(points[cur_point][0] - points[j][0]) + Math.abs(points[cur_point][1] - points[j][1]);
                cost[j] = Math.min(cost[j], new_cost);
            }
        }
    }

    return ans;
}
```
The solution uses Prim's algorithm for constructing a minimum spanning tree. Prim's algorithm maintains a tree of visited points and a set of unvisited points. Initially, the tree contains just one point (selected arbitrarily), and the set contains all other points. We repeat the following steps until all points are visited:

1. Find the point in the unvisited set with the minimum cost to connect it to any point in the visited set. Call this point the current point and add it to the visited set.
2. Update the costs of all unvisited points by calculating the Manhattan distance between the current point and each unvisited point. If this distance is smaller than the previously recorded cost for the unvisited point, replace the cost.

The total cost of the minimum spanning tree is the sum of connection costs for all points added to the visited set.


# Maximum XOR With an Element From Array

- slug: maximum-xor-with-an-element-from-array
- difficulty: Hard

You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.

The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`.

Return _an integer array_ `answer` _where_ `answer.length == queries.length` _and_ `answer[i]` _is the answer to the_ `ith` _query._

**Example 1:**

**Input:** nums = \[0,1,2,3,4\], queries = \[\[3,1\],\[1,3\],\[5,6\]\]
**Output:** \[3,3,7\]
**Explanation:**
1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
2) 1 XOR 2 = 3.
3) 5 XOR 2 = 7.

**Example 2:**

**Input:** nums = \[5,2,4,6,6,3\], queries = \[\[12,4\],\[8,1\],\[6,3\]\]
**Output:** \[15,-1,5\]

**Constraints:**

*   `1 <= nums.length, queries.length <= 105`
*   `queries[i].length == 2`
*   `0 <= nums[j], xi, mi <= 109`

## A solution in Java

```java
boolean canTransform(String s, String t) {
    int i = 0, j = 0;
    while (i < s.length() && j < t.length()) {
        if (s.charAt(i) == t.charAt(j)) {
            i++;
            j++;
        } else {
            i++;
        }
    }
    return j == t.length();
}
```
The algorithm used in all these implementations is the same. We use two pointers `i` and `j` to iterate through string `s` and `t`, respectively. We start at the beginning of each string and compare the characters at `i` and `j` indices.

If the characters are the same, we increment both `i` and `j`. If the characters are different, we increment only `i`, which effectively deletes the character at index `i` from string `s`.

We repeat this process until we have iterated through the entire string `s` or string `t`. If we've reached the end of string `t`, it means we could possibly transform `s` into `t` by visiting/deleting some characters from `s`. In this case, we return `true`. If we haven't reached the end of string `t`, it means we couldn't transform `s` into `t`, and we return `false`.

For all languages, the implementation and logic are the same, only the syntax differs. For example, in Python, we use `len()` to find the length of a string, while in Java, we use the `.length()` method. Likewise, in JavaScript, we use the `.length` property of a string.

## A solution in C++

```cpp
bool canTransform(string s, string t) {
    int i = 0, j = 0;
    while (i < s.size() && j < t.size()) {
        if (s[i] == t[j]) {
            i++;
            j++;
        } else {
            i++;
        }
    }
    return j == t.size();
}
```
The algorithm used in all these implementations is the same. We use two pointers `i` and `j` to iterate through string `s` and `t`, respectively. We start at the beginning of each string and compare the characters at `i` and `j` indices.

If the characters are the same, we increment both `i` and `j`. If the characters are different, we increment only `i`, which effectively deletes the character at index `i` from string `s`.

We repeat this process until we have iterated through the entire string `s` or string `t`. If we've reached the end of string `t`, it means we could possibly transform `s` into `t` by visiting/deleting some characters from `s`. In this case, we return `true`. If we haven't reached the end of string `t`, it means we couldn't transform `s` into `t`, and we return `false`.

For all languages, the implementation and logic are the same, only the syntax differs. For example, in Python, we use `len()` to find the length of a string, while in Java, we use the `.length()` method. Likewise, in JavaScript, we use the `.length` property of a string.

## A solution in Python

```python
def can_transform(s, t):
    i, j = 0, 0
    while i < len(s) and j < len(t):
        if s[i] == t[j]:
            i += 1
            j += 1
        else:
            i += 1
    return j == len(t)
```
The algorithm used in all these implementations is the same. We use two pointers `i` and `j` to iterate through string `s` and `t`, respectively. We start at the beginning of each string and compare the characters at `i` and `j` indices.

If the characters are the same, we increment both `i` and `j`. If the characters are different, we increment only `i`, which effectively deletes the character at index `i` from string `s`.

We repeat this process until we have iterated through the entire string `s` or string `t`. If we've reached the end of string `t`, it means we could possibly transform `s` into `t` by visiting/deleting some characters from `s`. In this case, we return `true`. If we haven't reached the end of string `t`, it means we couldn't transform `s` into `t`, and we return `false`.

For all languages, the implementation and logic are the same, only the syntax differs. For example, in Python, we use `len()` to find the length of a string, while in Java, we use the `.length()` method. Likewise, in JavaScript, we use the `.length` property of a string.

## A solution in Javascript

```javascript
function canTransform(s, t) {
    let i = 0, j = 0;
    while (i < s.length && j < t.length) {
        if (s[i] === t[j]) {
            i++;
            j++;
        } else {
            i++;
        }
    }
    return j === t.length;
}
```
The algorithm used in all these implementations is the same. We use two pointers `i` and `j` to iterate through string `s` and `t`, respectively. We start at the beginning of each string and compare the characters at `i` and `j` indices.

If the characters are the same, we increment both `i` and `j`. If the characters are different, we increment only `i`, which effectively deletes the character at index `i` from string `s`.

We repeat this process until we have iterated through the entire string `s` or string `t`. If we've reached the end of string `t`, it means we could possibly transform `s` into `t` by visiting/deleting some characters from `s`. In this case, we return `true`. If we haven't reached the end of string `t`, it means we couldn't transform `s` into `t`, and we return `false`.

For all languages, the implementation and logic are the same, only the syntax differs. For example, in Python, we use `len()` to find the length of a string, while in Java, we use the `.length()` method. Likewise, in JavaScript, we use the `.length` property of a string.


# Largest Subarray Length K

- slug: largest-subarray-length-k
- difficulty: Easy

An array `A` is larger than some array `B` if for the first index `i` where `A[i] != B[i]`, `A[i] > B[i]`.

For example, consider `0`\-indexing:

*   `[1,3,2,4] > [1,2,2,4]`, since at index `1`, `3 > 2`.
*   `[1,4,4,4] < [2,1,1,1]`, since at index `0`, `1 < 2`.

A subarray is a contiguous subsequence of the array.

Given an integer array `nums` of **distinct** integers, return the **largest** subarray of `nums` of length `k`.

**Example 1:**

**Input:** nums = \[1,4,5,2,3\], k = 3
**Output:** \[5,2,3\]
**Explanation:** The subarrays of size 3 are: \[1,4,5\], \[4,5,2\], and \[5,2,3\].
Of these, \[5,2,3\] is the largest.

**Example 2:**

**Input:** nums = \[1,4,5,2,3\], k = 4
**Output:** \[4,5,2,3\]
**Explanation:** The subarrays of size 4 are: \[1,4,5,2\], and \[4,5,2,3\].
Of these, \[4,5,2,3\] is the largest.

**Example 3:**

**Input:** nums = \[1,4,5,2,3\], k = 1
**Output:** \[5\]

**Constraints:**

*   `1 <= k <= nums.length <= 105`
*   `1 <= nums[i] <= 109`
*   All the integers of `nums` are **unique**.

**Follow up:** What if the integers in `nums` are not distinct?

## A solution in Java

```java
public class ParkingSystem {
    private int[] slots;

    public ParkingSystem(int big, int medium, int small) {
        slots = new int[]{big, medium, small};
    }

    public boolean addCar(int carType) {
        if (slots[carType - 1] > 0) {
            slots[carType - 1]--;
            return true;
        } else {
            return false;
        }
    }
}
```
The ParkingSystem class is designed such that an instance of the class contains an array of integers 'slots', representing the number of big, medium, and small slots available. The constructor takes in the respective number of big, medium, and small slots as arguments and assigns the input values to the slots array.

The addCar() function is then implemented to take in an integer value carType (1, 2, or 3) representing the type of car. We then check if the number of slots for that specific type of car is more than 0. If there is available space (i.e., the respective slot count is > 0), we decrement the slot count and return true. If there is no space available (i.e., slot count is 0), we return false.

The solution is O(1) for addCar() as it directly accesses and modifies the slots array.

## A solution in C++

```cpp
class ParkingSystem {
public:
    ParkingSystem(int big, int medium, int small) {
        slots = {big, medium, small};
    }

    bool addCar(int carType) {
        if (slots[carType - 1] > 0) {
            slots[carType - 1]--;
            return true;
        } else {
            return false;
        }
    }

private:
    vector<int> slots;
};
```
The ParkingSystem class is designed such that an instance of the class contains an array of integers 'slots', representing the number of big, medium, and small slots available. The constructor takes in the respective number of big, medium, and small slots as arguments and assigns the input values to the slots array.

The addCar() function is then implemented to take in an integer value carType (1, 2, or 3) representing the type of car. We then check if the number of slots for that specific type of car is more than 0. If there is available space (i.e., the respective slot count is > 0), we decrement the slot count and return true. If there is no space available (i.e., slot count is 0), we return false.

The solution is O(1) for addCar() as it directly accesses and modifies the slots array.

## A solution in Python

```python
class ParkingSystem:

    def __init__(self, big: int, medium: int, small: int):
        self.slots = [big, medium, small]

    def addCar(self, carType: int) -> bool:
        if self.slots[carType - 1] > 0:
            self.slots[carType - 1] -= 1
            return True
        else:
            return False
```
The ParkingSystem class is designed such that an instance of the class contains an array of integers 'slots', representing the number of big, medium, and small slots available. The constructor takes in the respective number of big, medium, and small slots as arguments and assigns the input values to the slots array.

The addCar() function is then implemented to take in an integer value carType (1, 2, or 3) representing the type of car. We then check if the number of slots for that specific type of car is more than 0. If there is available space (i.e., the respective slot count is > 0), we decrement the slot count and return true. If there is no space available (i.e., slot count is 0), we return false.

The solution is O(1) for addCar() as it directly accesses and modifies the slots array.

## A solution in Javascript

```javascript
class ParkingSystem {
    constructor(big, medium, small) {
        this.slots = [big, medium, small];
    }

    addCar(carType) {
        if (this.slots[carType - 1] > 0) {
            this.slots[carType - 1]--;
            return true;
        } else {
            return false;
        }
    }
}
```
The ParkingSystem class is designed such that an instance of the class contains an array of integers 'slots', representing the number of big, medium, and small slots available. The constructor takes in the respective number of big, medium, and small slots as arguments and assigns the input values to the slots array.

The addCar() function is then implemented to take in an integer value carType (1, 2, or 3) representing the type of car. We then check if the number of slots for that specific type of car is more than 0. If there is available space (i.e., the respective slot count is > 0), we decrement the slot count and return true. If there is no space available (i.e., slot count is 0), we return false.

The solution is O(1) for addCar() as it directly accesses and modifies the slots array.