# Replace All Digits with Characters

- slug: replace-all-digits-with-characters
- difficulty: Easy

You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices.

There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`.

*   For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`.

For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`.

Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`.

**Example 1:**

**Input:** s =  "a1c1e1 "
**Output:**  "abcdef "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('c',1) = 'd'
- s\[5\] -> shift('e',1) = 'f'

**Example 2:**

**Input:** s =  "a1b2c3d4e "
**Output:**  "abbdcfdhe "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('b',2) = 'd'
- s\[5\] -> shift('c',3) = 'f'
- s\[7\] -> shift('d',4) = 'h'

**Constraints:**

*   `1 <= s.length <= 100`
*   `s` consists only of lowercase English letters and digits.
*   `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.

## A solution in Java

```java
public int countBalls(int lowLimit, int highLimit) {
    int[] boxCounts = new int[46];
    for(int i = lowLimit; i <= highLimit; i++) {
        int boxNumber = 0;
        int num = i;
        while(num != 0) {
            boxNumber += num % 10;
            num /= 10;
        }
        boxCounts[boxNumber]++;
    }
    return Arrays.stream(boxCounts).max().orElse(0);
}
```
1. Initialize an array `boxCounts` with 46 elements, all set to 0. This array will store the counts of balls in each box. We use 46 because the maximum possible sum of digits for numbers in the range of the problem is 9 + 9 + 9 + 9 + 9 = 45.
2. Iterate through numbers from `lowLimit` to `highLimit`, inclusive.
3. For each number, calculate the sum of its digits (box number) using a while loop.
4. Increment the count in `boxCounts` corresponding to the calculated box number.
5. Once all numbers have been placed in boxes, return the maximum count in the `boxCounts` array.

## A solution in C++

```cpp
int countBalls(int lowLimit, int highLimit) {
    std::vector<int> boxCounts(46, 0);
    for(int i = lowLimit; i <= highLimit; i++) {
        int boxNumber = 0;
        int num = i;
        while(num) {
            boxNumber += num % 10;
            num /= 10;
        }
        boxCounts[boxNumber]++;
    }
    return *std::max_element(boxCounts.begin(), boxCounts.end());
}
```
1. Initialize an array `boxCounts` with 46 elements, all set to 0. This array will store the counts of balls in each box. We use 46 because the maximum possible sum of digits for numbers in the range of the problem is 9 + 9 + 9 + 9 + 9 = 45.
2. Iterate through numbers from `lowLimit` to `highLimit`, inclusive.
3. For each number, calculate the sum of its digits (box number) using a while loop.
4. Increment the count in `boxCounts` corresponding to the calculated box number.
5. Once all numbers have been placed in boxes, return the maximum count in the `boxCounts` array.

## A solution in Python

```python
def count_balls(low_limit: int, high_limit: int) -> int:
    box_counts = [0] * 46
    for i in range(low_limit, high_limit + 1):
        box_number = sum(map(int, str(i)))
        box_counts[box_number] += 1
    return max(box_counts)
```
1. Initialize an array `boxCounts` with 46 elements, all set to 0. This array will store the counts of balls in each box. We use 46 because the maximum possible sum of digits for numbers in the range of the problem is 9 + 9 + 9 + 9 + 9 = 45.
2. Iterate through numbers from `lowLimit` to `highLimit`, inclusive.
3. For each number, calculate the sum of its digits (box number) using a while loop.
4. Increment the count in `boxCounts` corresponding to the calculated box number.
5. Once all numbers have been placed in boxes, return the maximum count in the `boxCounts` array.

## A solution in Javascript

```javascript
function countBalls(lowLimit, highLimit) {
    const boxCounts = new Array(46).fill(0);
    for(let i = lowLimit; i <= highLimit; i++) {
        let boxNumber = 0;
        let num = i;
        while(num) {
            boxNumber += num % 10;
            num = Math.floor(num / 10);
        }
        boxCounts[boxNumber]++;
    }
    return Math.max(...boxCounts);
}
```
1. Initialize an array `boxCounts` with 46 elements, all set to 0. This array will store the counts of balls in each box. We use 46 because the maximum possible sum of digits for numbers in the range of the problem is 9 + 9 + 9 + 9 + 9 = 45.
2. Iterate through numbers from `lowLimit` to `highLimit`, inclusive.
3. For each number, calculate the sum of its digits (box number) using a while loop.
4. Increment the count in `boxCounts` corresponding to the calculated box number.
5. Once all numbers have been placed in boxes, return the maximum count in the `boxCounts` array.


# Seat Reservation Manager

- slug: seat-reservation-manager
- difficulty: Medium

Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.

Implement the `SeatManager` class:

*   `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
*   `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
*   `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.

**Example 1:**

**Input**
\[ "SeatManager ",  "reserve ",  "reserve ",  "unreserve ",  "reserve ",  "reserve ",  "reserve ",  "reserve ",  "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]

**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve();    // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve();    // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve();    // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve();    // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve();    // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve();    // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].

**Constraints:**

*   `1 <= n <= 105`
*   `1 <= seatNumber <= n`
*   For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
*   For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
*   At most `105` calls **in total** will be made to `reserve` and `unreserve`.

## A solution in Java

```java
import java.util.Arrays;

class Solution {
    public int largestSubmatrix(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        int[] height = new int[n];
        int max_area = 0;

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (matrix[i][j] == 1) height[j]++;
                else height[j] = 0;
            }
            int[] sorted_height = height.clone();
            Arrays.sort(sorted_height);
            for (int j = 0; j < n; ++j) {
                max_area = Math.max(max_area, sorted_height[j] * (n - j));
            }
        }
        return max_area;
    }
}
```
1. Initialize a height array of size n with all elements as 0, and set max_area as 0.
2. Iterate through each row of the matrix:
   a. For each column, if the current matrix element is 1, increment the height array element. Otherwise, set the height element to 0.
   b. Create a sorted copy of the height array.
   c. Iterate through the sorted height array and update the max_area as maximum of max_area and the product of the current sorted height element and the difference between n and the current index.
3. Return the max_area. This represents the optimal area of the largest submatrix with all elements as 1.

## A solution in C++

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

int largestSubmatrix(vector<vector<int>>& matrix) {
    int m = matrix.size(), n = matrix[0].size();
    vector<int> height(n, 0);
    int max_area = 0;

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (matrix[i][j] == 1) height[j]++;
            else height[j] = 0;
        }
        vector<int> sorted_height(height);
        sort(sorted_height.begin(), sorted_height.end());
        for (int j = 0; j < n; ++j) {
            max_area = max(max_area, sorted_height[j] * (n - j));
        }
    }
    return max_area;
}
```
1. Initialize a height array of size n with all elements as 0, and set max_area as 0.
2. Iterate through each row of the matrix:
   a. For each column, if the current matrix element is 1, increment the height array element. Otherwise, set the height element to 0.
   b. Create a sorted copy of the height array.
   c. Iterate through the sorted height array and update the max_area as maximum of max_area and the product of the current sorted height element and the difference between n and the current index.
3. Return the max_area. This represents the optimal area of the largest submatrix with all elements as 1.

## A solution in Python

```python
def largestSubmatrix(matrix):
    m, n = len(matrix), len(matrix[0])
    height = [0] * n
    max_area = 0

    for i in range(m):
        for j in range(n):
            if matrix[i][j] == 1:
                height[j] += 1
            else:
                height[j] = 0
        sorted_height = sorted(height)
        for j in range(n):
            max_area = max(max_area, sorted_height[j] * (n - j))

    return max_area
```
1. Initialize a height array of size n with all elements as 0, and set max_area as 0.
2. Iterate through each row of the matrix:
   a. For each column, if the current matrix element is 1, increment the height array element. Otherwise, set the height element to 0.
   b. Create a sorted copy of the height array.
   c. Iterate through the sorted height array and update the max_area as maximum of max_area and the product of the current sorted height element and the difference between n and the current index.
3. Return the max_area. This represents the optimal area of the largest submatrix with all elements as 1.

## A solution in Javascript

```javascript
function largestSubmatrix(matrix) {
    const m = matrix.length, n = matrix[0].length;
    const height = Array(n).fill(0);
    let max_area = 0;

    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; ++j) {
            if (matrix[i][j] === 1) height[j]++;
            else height[j] = 0;
        }
        const sorted_height = [...height].sort((a, b) => a - b);
        for (let j = 0; j < n; ++j) {
            max_area = Math.max(max_area, sorted_height[j] * (n - j));
        }
    }
    return max_area;
}
```
1. Initialize a height array of size n with all elements as 0, and set max_area as 0.
2. Iterate through each row of the matrix:
   a. For each column, if the current matrix element is 1, increment the height array element. Otherwise, set the height element to 0.
   b. Create a sorted copy of the height array.
   c. Iterate through the sorted height array and update the max_area as maximum of max_area and the product of the current sorted height element and the difference between n and the current index.
3. Return the max_area. This represents the optimal area of the largest submatrix with all elements as 1.


# Maximum Element After Decreasing and Rearranging

- slug: maximum-element-after-decreasing-and-rearranging
- difficulty: Medium

You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:

*   The value of the **first** element in `arr` must be `1`.
*   The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.

There are 2 types of operations that you can perform any number of times:

*   **Decrease** the value of any element of `arr` to a **smaller positive integer**.
*   **Rearrange** the elements of `arr` to be in any order.

Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.

**Example 1:**

**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.

**Example 2:**

**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`

**Example 3:**

**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.

**Constraints:**

*   `1 <= arr.length <= 105`
*   `1 <= arr[i] <= 109`

## A solution in Java

```java
public int maximumElementAfterDecrementingAndRearranging(int[] arr) {
    Arrays.sort(arr);
    arr[0] = 1;
    for (int i = 1; i < arr.length; i++) {
        arr[i] = Math.min(arr[i], arr[i - 1] + 1);
    }
    return arr[arr.length - 1];
}
```
The main idea of this algorithm is to sort the array and modify it following these steps:
1. Set the first element to 1.
2. Iterate through the array starting from the second element. For each element, set its value to the minimum of its current value and the value of the previous element plus one.

Since we sort the array, the absolute difference between adjacent elements after this transformation will always satisfy the conditions. Sorting ensures that we decrement the values as little as possible.

Our goal is to return the maximum value, which will be the last element of the array after modifying it in this way.

## A solution in C++

```cpp
int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {
    sort(arr.begin(), arr.end());
    arr[0] = 1;
    for (int i = 1; i < arr.size(); i++) {
        arr[i] = min(arr[i], arr[i - 1] + 1);
    }
    return arr[arr.size() - 1];
}
```
The main idea of this algorithm is to sort the array and modify it following these steps:
1. Set the first element to 1.
2. Iterate through the array starting from the second element. For each element, set its value to the minimum of its current value and the value of the previous element plus one.

Since we sort the array, the absolute difference between adjacent elements after this transformation will always satisfy the conditions. Sorting ensures that we decrement the values as little as possible.

Our goal is to return the maximum value, which will be the last element of the array after modifying it in this way.

## A solution in Python

```python
def maximumElementAfterDecrementingAndRearranging(arr: List[int]) -> int:
    arr.sort()
    arr[0] = 1
    for i in range(1, len(arr)):
        arr[i] = min(arr[i], arr[i - 1] + 1)
    return arr[-1]
```
The main idea of this algorithm is to sort the array and modify it following these steps:
1. Set the first element to 1.
2. Iterate through the array starting from the second element. For each element, set its value to the minimum of its current value and the value of the previous element plus one.

Since we sort the array, the absolute difference between adjacent elements after this transformation will always satisfy the conditions. Sorting ensures that we decrement the values as little as possible.

Our goal is to return the maximum value, which will be the last element of the array after modifying it in this way.

## A solution in Javascript

```javascript
function maximumElementAfterDecrementingAndRearranging(arr) {
    arr.sort((a, b) => a - b);
    arr[0] = 1;
    for (let i = 1; i < arr.length; i++) {
        arr[i] = Math.min(arr[i], arr[i - 1] + 1);
    }
    return arr[arr.length - 1];
}
```
The main idea of this algorithm is to sort the array and modify it following these steps:
1. Set the first element to 1.
2. Iterate through the array starting from the second element. For each element, set its value to the minimum of its current value and the value of the previous element plus one.

Since we sort the array, the absolute difference between adjacent elements after this transformation will always satisfy the conditions. Sorting ensures that we decrement the values as little as possible.

Our goal is to return the maximum value, which will be the last element of the array after modifying it in this way.


# Closest Room

- slug: closest-room
- difficulty: Hard

There is a hotel with `n` rooms. The rooms are represented by a 2D integer array `rooms` where `rooms[i] = [roomIdi, sizei]` denotes that there is a room with room number `roomIdi` and size equal to `sizei`. Each `roomIdi` is guaranteed to be **unique**.

You are also given `k` queries in a 2D array `queries` where `queries[j] = [preferredj, minSizej]`. The answer to the `jth` query is the room number `id` of a room such that:

*   The room has a size of **at least** `minSizej`, and
*   `abs(id - preferredj)` is **minimized**, where `abs(x)` is the absolute value of `x`.

If there is a **tie** in the absolute difference, then use the room with the **smallest** such `id`. If there is **no such room**, the answer is `-1`.

Return _an array_ `answer` _of length_ `k` _where_ `answer[j]` _contains the answer to the_ `jth` _query_.

**Example 1:**

**Input:** rooms = \[\[2,2\],\[1,2\],\[3,2\]\], queries = \[\[3,1\],\[3,3\],\[5,2\]\]
**Output:** \[3,-1,3\]
**Explanation:** The answers to the queries are as follows:
Query = \[3,1\]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.
Query = \[3,3\]: There are no rooms with a size of at least 3, so the answer is -1.
Query = \[5,2\]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.

**Example 2:**

**Input:** rooms = \[\[1,4\],\[2,3\],\[3,5\],\[4,1\],\[5,2\]\], queries = \[\[2,3\],\[2,4\],\[2,5\]\]
**Output:** \[2,1,3\]
**Explanation:** The answers to the queries are as follows:
Query = \[2,3\]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.
Query = \[2,4\]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.
Query = \[2,5\]: Room number 3 is the only room with a size of at least 5. The answer is 3.

**Constraints:**

*   `n == rooms.length`
*   `1 <= n <= 105`
*   `k == queries.length`
*   `1 <= k <= 104`
*   `1 <= roomIdi, preferredj <= 107`
*   `1 <= sizei, minSizej <= 107`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int[] closestRoom(int[][] rooms, int[][] queries) {
        Arrays.sort(rooms, (a, b) -> b[1] - a[1]);
        int[] result = new int[queries.length];

        for (int i = 0; i < queries.length; ++i) {
            int[] q = new int[]{queries[i][0], queries[i][1], i};
            queries[i] = q;
        }

        Arrays.sort(queries, (a, b) -> b[1] - a[1]);

        TreeSet<Integer> ids = new TreeSet<>();
        int j = 0;
        for (int[] q : queries) {
            while (j < rooms.length && rooms[j][1] >= q[1]) {
                ids.add(rooms[j++][0]);
            }
            if (ids.isEmpty()) {
                result[q[2]] = -1;
            } else {
                Integer cid1 = ids.ceiling(q[0]);
                Integer cid2 = ids.floor(q[0]);
                if (cid1 == null) {
                    result[q[2]] = cid2;
                } else if (cid2 == null) {
                    result[q[2]] = cid1;
                } else {
                    result[q[2]] = (q[0] - cid2 <= cid1 - q[0]) ? cid2 : cid1;
                }
            }
        }

        return result;
    }
}
```
1. Sort the rooms by size in descending order.
2. Sort the queries by minOccurs in descending order.
3. Iterate over the sorted queries, maintaining a sorted set of available room ids meeting the minOccurs requirement for the current query (by adding ids from the sorted rooms list when the corresponding room is large enough).
4. For each query, find the closest available id (if any) by searching the sorted set for the value closest to the preferred room number.
5. Return the answers in the original order of the queries.

## A solution in C++

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

vector<int> closestRoom(vector<vector<int>>& rooms, vector<vector<int>>& queries) {
    sort(rooms.begin(), rooms.end(), [](const vector<int>& a, const vector<int>& b) {
        return a[1] > b[1];
    });

    vector<int> result(queries.size());
    for (int i = 0; i < queries.size(); ++i) {
        queries[i].push_back(i);
    }

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

    set<int> ids;
    int j = 0;
    for (const auto& q : queries) {
        while (j < rooms.size() && rooms[j][1] >= q[1]) {
            ids.insert(rooms[j++][0]);
        }
        if (ids.empty()) {
            result[q[2]] = -1;
        } else {
            int closestDiff = numeric_limits<int>::max();
            int closestId = -1;
            for (int id : {q[0], *ids.upper_bound(q[0]), *prev(ids.upper_bound(q[0]))}) {
                if (ids.count(id)) {
                    int diff = abs(id - q[0]);
                    if (diff < closestDiff) {
                        closestDiff = diff;
                        closestId = id;
                    }
                }
            }
            result[q[2]] = closestId;
        }
    }

    return result;
}
```
1. Sort the rooms by size in descending order.
2. Sort the queries by minOccurs in descending order.
3. Iterate over the sorted queries, maintaining a sorted set of available room ids meeting the minOccurs requirement for the current query (by adding ids from the sorted rooms list when the corresponding room is large enough).
4. For each query, find the closest available id (if any) by searching the sorted set for the value closest to the preferred room number.
5. Return the answers in the original order of the queries.

## A solution in Python

```javascript
function closestRoom(rooms, queries) {
    rooms.sort((a, b) => b[1] - a[1]);

    for (let i = 0; i < queries.length; ++i) {
        queries[i].push(i);
    }

    queries.sort((a, b) => b[1] - a[1]);

    let result = new Array(queries.length);
    let ids = new Set();

    let j = 0;
    for (const q of queries) {
        while (j < rooms.length && rooms[j][1] >= q[1]) {
            ids.add(rooms[j++][0]);
        }
        if (ids.size === 0) {
            result[q[2]] = -1;
        } else {
            let minAbsDiff = Infinity;
            let minId = undefined;
            for (let id = q[0]; id <= 10000000; ++id) {
                if (ids.has(id) && Math.abs(id-q[0]) < minAbsDiff) {
                    minAbsDiff = Math.abs(id - q[0]);
                    minId = id;
                }
                if (ids.has(id-1) && Math.abs(id-1-q[0]) < minAbsDiff) {
                    minAbsDiff = Math.abs(id - 1 - q[0]);
                    minId = id - 1;
                }
                if (minId !== undefined)
                    break;
            }
            result[q[2]] = minId;
        }
    }

    return result;
}
```
1. Sort the rooms by size in descending order.
2. Sort the queries by minOccurs in descending order.
3. Iterate over the sorted queries, maintaining a sorted set of available room ids meeting the minOccurs requirement for the current query (by adding ids from the sorted rooms list when the corresponding room is large enough).
4. For each query, find the closest available id (if any) by searching the sorted set for the value closest to the preferred room number.
5. Return the answers in the original order of the queries.

## A solution in Javascript

```python
from typing import List
import bisect

class Solution:
    def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]:
        rooms.sort(key=lambda x: -x[1])
        ans = [0] * len(queries)

        for idx, q in enumerate(queries):
            q.append(idx)
        queries.sort(key=lambda x: -x[1])

        ids = []
        j = 0
        for q in queries:
            while j < len(rooms) and rooms[j][1] >= q[1]:
                bisect.insort(ids, rooms[j][0])
                j += 1
            if not ids:
                ans[q[2]] = -1
            else:
                k = bisect.bisect_left(ids, q[0])
                choices = [k-1, k] if k > 0 else [k]
                closest_idx = min(choices, key=lambda x: abs(ids[x]-q[0]))
                ans[q[2]] = ids[closest_idx]

        return ans
```
1. Sort the rooms by size in descending order.
2. Sort the queries by minOccurs in descending order.
3. Iterate over the sorted queries, maintaining a sorted set of available room ids meeting the minOccurs requirement for the current query (by adding ids from the sorted rooms list when the corresponding room is large enough).
4. For each query, find the closest available id (if any) by searching the sorted set for the value closest to the preferred room number.
5. Return the answers in the original order of the queries.


# Minimum Distance to the Target Element

- slug: minimum-distance-to-the-target-element
- difficulty: Easy

Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`.

Return `abs(i - start)`.

It is **guaranteed** that `target` exists in `nums`.

**Example 1:**

**Input:** nums = \[1,2,3,4,5\], target = 5, start = 3
**Output:** 1
**Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.

**Example 2:**

**Input:** nums = \[1\], target = 1, start = 0
**Output:** 0
**Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.

**Example 3:**

**Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0
**Output:** 0
**Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0.

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `1 <= nums[i] <= 104`
*   `0 <= start < nums.length`
*   `target` is in `nums`.

## A solution in Java

```java
public int sumOfUniqueElements(int[] nums) {
    Map<Integer, Integer> elemCount = new HashMap<>();
    for (int num : nums) {
        elemCount.put(num, elemCount.getOrDefault(num, 0) + 1);
    }
    int sum = 0;
    for (Map.Entry<Integer, Integer> entry : elemCount.entrySet()) {
        if (entry.getValue() == 1) {
            sum += entry.getKey();
        }
    }
    return sum;
}
```
The algorithm starts by creating an empty hash map (or dictionary in Python) to store the count of each element in the input array. After that, it iterates through the input array and increments the count of each element in the hash map. Finally, it iterates through the hash map and checks the count of each element. If the count is 1, it adds the element to the sum. Once iteration is complete, the total sum of unique elements is returned.

## A solution in C++

```cpp
int sumOfUniqueElements(const std::vector<int>& nums) {
    std::unordered_map<int, int> elemCount;
    for (const int num : nums) {
        elemCount[num]++;
    }
    int sum = 0;
    for (const auto &[elem, count] : elemCount) {
        if (count == 1) {
            sum += elem;
        }
    }
    return sum;
}
```
The algorithm starts by creating an empty hash map (or dictionary in Python) to store the count of each element in the input array. After that, it iterates through the input array and increments the count of each element in the hash map. Finally, it iterates through the hash map and checks the count of each element. If the count is 1, it adds the element to the sum. Once iteration is complete, the total sum of unique elements is returned.

## A solution in Python

```python
def sum_of_unique_elements(nums):
    elem_count = {}
    for num in nums:
        elem_count[num] = elem_count.get(num, 0) + 1
    sum = 0
    for elem, count in elem_count.items():
        if count == 1:
            sum += elem
    return sum
```
The algorithm starts by creating an empty hash map (or dictionary in Python) to store the count of each element in the input array. After that, it iterates through the input array and increments the count of each element in the hash map. Finally, it iterates through the hash map and checks the count of each element. If the count is 1, it adds the element to the sum. Once iteration is complete, the total sum of unique elements is returned.

## A solution in Javascript

```javascript
function sumOfUniqueElements(nums) {
    const elemCount = {};
    for (const num of nums) {
        elemCount[num] = (elemCount[num] || 0) + 1;
    }
    let sum = 0;
    for (const [elem, count] of Object.entries(elemCount)) {
        if (count === 1) {
            sum += parseInt(elem);
        }
    }
    return sum;
}
```
The algorithm starts by creating an empty hash map (or dictionary in Python) to store the count of each element in the input array. After that, it iterates through the input array and increments the count of each element in the hash map. Finally, it iterates through the hash map and checks the count of each element. If the count is 1, it adds the element to the sum. Once iteration is complete, the total sum of unique elements is returned.


# Splitting a String Into Descending Consecutive Values

- slug: splitting-a-string-into-descending-consecutive-values
- difficulty: Medium

You are given a string `s` that consists of only digits.

Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`.

*   For example, the string `s = "0090089 "` can be split into `[ "0090 ", "089 "]` with numerical values `[90,89]`. The values are in descending order and adjacent values differ by `1`, so this way is valid.
*   Another example, the string `s = "001 "` can be split into `[ "0 ", "01 "]`, `[ "00 ", "1 "]`, or `[ "0 ", "0 ", "1 "]`. However all the ways are invalid because they have numerical values `[0,1]`, `[0,1]`, and `[0,0,1]` respectively, all of which are not in descending order.

Return `true` _if it is possible to split_ `s` _as described above__, or_ `false` _otherwise._

A **substring** is a contiguous sequence of characters in a string.

**Example 1:**

**Input:** s =  "1234 "
**Output:** false
**Explanation:** There is no valid way to split s.

**Example 2:**

**Input:** s =  "050043 "
**Output:** true
**Explanation:** s can be split into \[ "05 ",  "004 ",  "3 "\] with numerical values \[5,4,3\].
The values are in descending order with adjacent values differing by 1.

**Example 3:**

**Input:** s =  "9080701 "
**Output:** false
**Explanation:** There is no valid way to split s.

**Constraints:**

*   `1 <= s.length <= 20`
*   `s` only consists of digits.

## A solution in Java

```java
public int maxAbsoluteSum(int[] nums) {
    int maxSum = 0, minSum = 0, maxSoFar = 0, minSoFar = 0;
    for (int num : nums) {
        maxSoFar = Math.max(num, maxSoFar + num);
        maxSum = Math.max(maxSum, maxSoFar);

        minSoFar = Math.min(num, minSoFar + num);
        minSum = Math.min(minSum, minSoFar);
    }
    return Math.max(maxSum, Math.abs(minSum));
}
```
The algorithm uses the famous Kadane's Algorithm for finding the maximum subarray sum with a slight modification for finding both maximum and minimum subarray sums.

1. Use two sets of variables: `max_so_far`, `max_sum` for maximum subarray sum and `min_so_far`, `min_sum` for minimum subarray sum.
2. Iterate through the input `nums`.
3. For each number, update `max_so_far` with the maximum of the current number and the sum of the current number and `max_so_far`.
4. Update `max_sum` with the maximum of itself and `max_so_far`.
5. Similarly, update `min_so_far` with the minimum of the current number and the sum of the current number and `min_so_far`. Also, update `min_sum` with the minimum of itself and `min_so_far`.
6. After iterating through the input, return the maximum of `max_sum` and the absolute value of `min_sum`, as the result will be the maximum absolute value among the `max_sum` and the absolute of `min_sum`.

This approach runs in O(n) linear time complexity as it goes through the input array just once.

## A solution in C++

```cpp
int maxAbsoluteSum(vector<int>& nums) {
    int max_sum = 0, min_sum = 0, max_so_far = 0, min_so_far = 0;
    for (int num : nums) {
        max_so_far = max(num, max_so_far + num);
        max_sum = max(max_sum, max_so_far);

        min_so_far = min(num,min_so_far + num);
        min_sum = min(min_sum, min_so_far);
    }
    return max(max_sum, abs(min_sum));
}
```
The algorithm uses the famous Kadane's Algorithm for finding the maximum subarray sum with a slight modification for finding both maximum and minimum subarray sums.

1. Use two sets of variables: `max_so_far`, `max_sum` for maximum subarray sum and `min_so_far`, `min_sum` for minimum subarray sum.
2. Iterate through the input `nums`.
3. For each number, update `max_so_far` with the maximum of the current number and the sum of the current number and `max_so_far`.
4. Update `max_sum` with the maximum of itself and `max_so_far`.
5. Similarly, update `min_so_far` with the minimum of the current number and the sum of the current number and `min_so_far`. Also, update `min_sum` with the minimum of itself and `min_so_far`.
6. After iterating through the input, return the maximum of `max_sum` and the absolute value of `min_sum`, as the result will be the maximum absolute value among the `max_sum` and the absolute of `min_sum`.

This approach runs in O(n) linear time complexity as it goes through the input array just once.

## A solution in Python

```python
def maxAbsoluteSum(nums):
    max_sum, min_sum, max_so_far, min_so_far = 0, 0, 0, 0
    for num in nums:
        max_so_far = max(num, max_so_far + num)
        max_sum = max(max_sum, max_so_far)

        min_so_far = min(num, min_so_far + num)
        min_sum = min(min_sum, min_so_far)
    return max(max_sum, abs(min_sum))
```
The algorithm uses the famous Kadane's Algorithm for finding the maximum subarray sum with a slight modification for finding both maximum and minimum subarray sums.

1. Use two sets of variables: `max_so_far`, `max_sum` for maximum subarray sum and `min_so_far`, `min_sum` for minimum subarray sum.
2. Iterate through the input `nums`.
3. For each number, update `max_so_far` with the maximum of the current number and the sum of the current number and `max_so_far`.
4. Update `max_sum` with the maximum of itself and `max_so_far`.
5. Similarly, update `min_so_far` with the minimum of the current number and the sum of the current number and `min_so_far`. Also, update `min_sum` with the minimum of itself and `min_so_far`.
6. After iterating through the input, return the maximum of `max_sum` and the absolute value of `min_sum`, as the result will be the maximum absolute value among the `max_sum` and the absolute of `min_sum`.

This approach runs in O(n) linear time complexity as it goes through the input array just once.

## A solution in Javascript

```javascript
function maxAbsoluteSum(nums) {
    let maxSum = 0, minSum = 0, maxSoFar = 0, minSoFar = 0;
    for (let num of nums) {
        maxSoFar = Math.max(num, maxSoFar + num);
        maxSum = Math.max(maxSum, maxSoFar);

        minSoFar = Math.min(num, minSoFar + num);
        minSum = Math.min(minSum, minSoFar);
    }
    return Math.max(maxSum, Math.abs(minSum));
}
```
The algorithm uses the famous Kadane's Algorithm for finding the maximum subarray sum with a slight modification for finding both maximum and minimum subarray sums.

1. Use two sets of variables: `max_so_far`, `max_sum` for maximum subarray sum and `min_so_far`, `min_sum` for minimum subarray sum.
2. Iterate through the input `nums`.
3. For each number, update `max_so_far` with the maximum of the current number and the sum of the current number and `max_so_far`.
4. Update `max_sum` with the maximum of itself and `max_so_far`.
5. Similarly, update `min_so_far` with the minimum of the current number and the sum of the current number and `min_so_far`. Also, update `min_sum` with the minimum of itself and `min_so_far`.
6. After iterating through the input, return the maximum of `max_sum` and the absolute value of `min_sum`, as the result will be the maximum absolute value among the `max_sum` and the absolute of `min_sum`.

This approach runs in O(n) linear time complexity as it goes through the input array just once.


# Minimum Adjacent Swaps to Reach the Kth Smallest Number

- slug: minimum-adjacent-swaps-to-reach-the-kth-smallest-number
- difficulty: Medium

You are given a string `num`, representing a large integer, and an integer `k`.

We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones.

*   For example, when `num = "5489355142 "`:
    *   The 1st smallest wonderful integer is `"5489355214 "`.
    *   The 2nd smallest wonderful integer is `"5489355241 "`.
    *   The 3rd smallest wonderful integer is `"5489355412 "`.
    *   The 4th smallest wonderful integer is `"5489355421 "`.

Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_.

The tests are generated in such a way that `kth` smallest wonderful integer exists.

**Example 1:**

**Input:** num =  "5489355142 ", k = 4
**Output:** 2
**Explanation:** The 4th smallest wonderful number is  "5489355421 ". To get this number:
- Swap index 7 with index 8:  "5489355142 " ->  "5489355412 "
- Swap index 8 with index 9:  "5489355412 " ->  "5489355421 "

**Example 2:**

**Input:** num =  "11112 ", k = 4
**Output:** 4
**Explanation:** The 4th smallest wonderful number is  "21111 ". To get this number:
- Swap index 3 with index 4:  "11112 " ->  "11121 "
- Swap index 2 with index 3:  "11121 " ->  "11211 "
- Swap index 1 with index 2:  "11211 " ->  "12111 "
- Swap index 0 with index 1:  "12111 " ->  "21111 "

**Example 3:**

**Input:** num =  "00123 ", k = 1
**Output:** 1
**Explanation:** The 1st smallest wonderful number is  "00132 ". To get this number:
- Swap index 3 with index 4:  "00123 " ->  "00132 "

**Constraints:**

*   `2 <= num.length <= 1000`
*   `1 <= k <= 1000`
*   `num` only consists of digits.

## A solution in Java

```java
public int minLengthAfterOperations(String s) {
    int aCount = s.length() - s.replace("a", "").length();
    int bCount = s.length() - s.replace("b", "").length();
    int cCount = s.length() - s.replace("c", "").length();

    if (aCount % 2 == bCount % 2 && bCount % 2 == cCount % 2) {
        return s.length() % 2;
    }
    return (s.length() + 1) % 2;
}
```
The algorithm counts the occurrences of each character ('a', 'b', 'c') in the given string. Then, it checks if the counts are all even or all odd, which means that the count of the three characters has the same parity. In this case, the minimum length of the string after performing the operations would be the length of the string modulo 2. Otherwise, the minimum length would be the length of the string plus 1 modulo 2. This is because one character will always remain after performing the operations if the parities of the character counts aren't the same.

## A solution in C++

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

int min_length_after_operations(const std::string &s) {
    int a_count = std::count(s.begin(), s.end(), 'a');
    int b_count = std::count(s.begin(), s.end(), 'b');
    int c_count = std::count(s.begin(), s.end(), 'c');

    if (a_count % 2 == b_count % 2 && b_count % 2 == c_count % 2) {
        return s.length() % 2;
    }
    return (s.length() + 1) % 2;
}
```
The algorithm counts the occurrences of each character ('a', 'b', 'c') in the given string. Then, it checks if the counts are all even or all odd, which means that the count of the three characters has the same parity. In this case, the minimum length of the string after performing the operations would be the length of the string modulo 2. Otherwise, the minimum length would be the length of the string plus 1 modulo 2. This is because one character will always remain after performing the operations if the parities of the character counts aren't the same.

## A solution in Python

```python
def min_length_after_operations(s: str) -> int:
    a_count = s.count('a')
    b_count = s.count('b')
    c_count = s.count('c')

    if a_count % 2 == b_count % 2 and b_count % 2 == c_count % 2:
        return len(s) % 2
    return (len(s) + 1) % 2
```
The algorithm counts the occurrences of each character ('a', 'b', 'c') in the given string. Then, it checks if the counts are all even or all odd, which means that the count of the three characters has the same parity. In this case, the minimum length of the string after performing the operations would be the length of the string modulo 2. Otherwise, the minimum length would be the length of the string plus 1 modulo 2. This is because one character will always remain after performing the operations if the parities of the character counts aren't the same.

## A solution in Javascript

```javascript
function minLengthAfterOperations(s) {
    const aCount = s.split('a').length - 1;
    const bCount = s.split('b').length - 1;
    const cCount = s.split('c').length - 1;

    if (aCount % 2 === bCount % 2 && bCount % 2 === cCount % 2) {
        return s.length % 2;
    }
    return (s.length + 1) % 2;
}
```
The algorithm counts the occurrences of each character ('a', 'b', 'c') in the given string. Then, it checks if the counts are all even or all odd, which means that the count of the three characters has the same parity. In this case, the minimum length of the string after performing the operations would be the length of the string modulo 2. Otherwise, the minimum length would be the length of the string plus 1 modulo 2. This is because one character will always remain after performing the operations if the parities of the character counts aren't the same.


# Minimum Interval to Include Each Query

- slug: minimum-interval-to-include-each-query
- difficulty: Hard

You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`.

You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`.

Return _an array containing the answers to the queries_.

**Example 1:**

**Input:** intervals = \[\[1,4\],\[2,4\],\[3,6\],\[4,4\]\], queries = \[2,3,4,5\]
**Output:** \[3,3,1,4\]
**Explanation:** The queries are processed as follows:
- Query = 2: The interval \[2,4\] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.
- Query = 3: The interval \[2,4\] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.
- Query = 4: The interval \[4,4\] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.
- Query = 5: The interval \[3,6\] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.

**Example 2:**

**Input:** intervals = \[\[2,3\],\[2,5\],\[1,8\],\[20,25\]\], queries = \[2,19,5,22\]
**Output:** \[2,-1,4,6\]
**Explanation:** The queries are processed as follows:
- Query = 2: The interval \[2,3\] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.
- Query = 19: None of the intervals contain 19. The answer is -1.
- Query = 5: The interval \[2,5\] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.
- Query = 22: The interval \[20,25\] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.

**Constraints:**

*   `1 <= intervals.length <= 105`
*   `1 <= queries.length <= 105`
*   `intervals[i].length == 2`
*   `1 <= lefti <= righti <= 107`
*   `1 <= queries[j] <= 107`

## A solution in Java

```java
import java.util.Arrays;

class Solution {
    public int maxValue(int[][] events, int k) {
        Arrays.sort(events, (a, b) -> a[1] - b[1]);
        int n = events.length;
        int[][] dp = new int[n + 1][k + 1];

        for (int i = 1; i <= n; i++) {
            int start = -1;
            for (int j = i - 1; j >= 1; j--) {
                if (events[j - 1][1] < events[i - 1][0]) {
                    start = j;
                    break;
                }
            }

            for (int j = 1; j <= k; j++) {
                if (start == -1) {
                    dp[i][j] = Math.max(dp[i - 1][j], events[i - 1][2]);
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[start][j - 1] + events[i - 1][2]);
                }
            }
        }

        return dp[n][k];
    }
}
```
1. Sort the events based on their end day.
2. Initialize a 2D array dp to store the maximum sum of values for choosing a number of events.
3. Iterate through the sorted events, and for each event find the latest non-overlapping event.
4. Iterate through 1 to k, and for each count of events to attend, update the dp array using the latest non-overlapping event.
5. Return the maximum sum of values found in the dp array for attending k events.

## A solution in C++

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

bool compare(vector<int>& a, vector<int>& b) {
    return a[1] < b[1];
}

int maxValue(vector<vector<int>>& events, int k) {
    sort(events.begin(), events.end(), compare);
    int n = events.size();
    vector<vector<int>> dp(n + 1, vector<int>(k + 1, 0));

    for (int i = 1; i <= n; i++) {
        int start = -1;
        for (int j = i - 1; j >= 1; j--) {
            if(events[j - 1][1] < events[i - 1][0]) {
                start = j;
                break;
            }
        }

        for (int j = 1; j <= k; j++) {
            if (start == -1) {
                dp[i][j] = max(dp[i - 1][j], events[i - 1][2]);
            } else {
                dp[i][j] = max(dp[i - 1][j], dp[start][j - 1] + events[i - 1][2]);
            }
        }
    }

    return dp[n][k];
}
```
1. Sort the events based on their end day.
2. Initialize a 2D array dp to store the maximum sum of values for choosing a number of events.
3. Iterate through the sorted events, and for each event find the latest non-overlapping event.
4. Iterate through 1 to k, and for each count of events to attend, update the dp array using the latest non-overlapping event.
5. Return the maximum sum of values found in the dp array for attending k events.

## A solution in Python

```python
from bisect import bisect_left

def maxValue(events, k):
    events.sort(key=lambda x: x[1])
    n = len(events)
    dp = [[0] * (k + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        start = -1
        for j in range(i - 1, 0, -1):
            if events[j - 1][1] < events[i - 1][0]:
                start = j
                break

        for j in range(1, k + 1):
            if start == -1:
                dp[i][j] = max(dp[i - 1][j], events[i - 1][2])
            else:
                dp[i][j] = max(dp[i - 1][j], dp[start][j - 1] + events[i - 1][2])

    return dp[n][k]
```
1. Sort the events based on their end day.
2. Initialize a 2D array dp to store the maximum sum of values for choosing a number of events.
3. Iterate through the sorted events, and for each event find the latest non-overlapping event.
4. Iterate through 1 to k, and for each count of events to attend, update the dp array using the latest non-overlapping event.
5. Return the maximum sum of values found in the dp array for attending k events.

## A solution in Javascript

```javascript
function maxValue(events, k) {
  events.sort((a, b) => a[1] - b[1]);
  const n = events.length;
  const dp = Array.from({ length: n + 1 }, () => new Array(k + 1).fill(0));

  for (let i = 1; i <= n; i++) {
    let start = -1;
    for (let j = i - 1; j >= 1; j--) {
      if (events[j - 1][1] < events[i - 1][0]) {
        start = j;
        break;
      }
    }

    for (let j = 1; j <= k; j++) {
      if (start === -1) {
        dp[i][j] = Math.max(dp[i - 1][j], events[i - 1][2]);
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[start][j - 1] + events[i - 1][2]);
      }
    }
  }

  return dp[n][k];
}
```
1. Sort the events based on their end day.
2. Initialize a 2D array dp to store the maximum sum of values for choosing a number of events.
3. Iterate through the sorted events, and for each event find the latest non-overlapping event.
4. Iterate through 1 to k, and for each count of events to attend, update the dp array using the latest non-overlapping event.
5. Return the maximum sum of values found in the dp array for attending k events.


# Distinct Numbers in Each Subarray

- slug: distinct-numbers-in-each-subarray
- difficulty: Medium

Given an integer array `nums` and an integer `k`, you are asked to construct the array `ans` of size `n-k+1` where `ans[i]` is the number of **distinct** numbers in the subarray `nums[i:i+k-1] = [nums[i], nums[i+1], ..., nums[i+k-1]]`.

Return _the array_ `ans`.

**Example 1:**

**Input:** nums = \[1,2,3,2,2,1,3\], k = 3
**Output:** \[3,2,2,2,3\]
**Explanation:** The number of distinct elements in each subarray goes as follows:
- nums\[0:2\] = \[1,2,3\] so ans\[0\] = 3
- nums\[1:3\] = \[2,3,2\] so ans\[1\] = 2
- nums\[2:4\] = \[3,2,2\] so ans\[2\] = 2
- nums\[3:5\] = \[2,2,1\] so ans\[3\] = 2
- nums\[4:6\] = \[2,1,3\] so ans\[4\] = 3

**Example 2:**

**Input:** nums = \[1,1,1,1,2,3,4\], k = 4
**Output:** \[1,2,3,4\]
**Explanation:** The number of distinct elements in each subarray goes as follows:
- nums\[0:3\] = \[1,1,1,1\] so ans\[0\] = 1
- nums\[1:4\] = \[1,1,1,2\] so ans\[1\] = 2
- nums\[2:5\] = \[1,1,2,3\] so ans\[2\] = 3
- nums\[3:6\] = \[1,2,3,4\] so ans\[3\] = 4

**Constraints:**

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

## A solution in Java

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

public int[] distinctNumbersInSubarrays(int[] nums, int k) {
    HashMap<Integer, Integer> counts = new HashMap<>();
    ArrayList<Integer> ans = new ArrayList<>();
    for (int i = 0; i < nums.length; i++) {
        counts.put(nums[i], counts.getOrDefault(nums[i], 0) + 1);
        if (i >= k) {
            counts.put(nums[i - k], counts.get(nums[i - k]) - 1);
            if (counts.get(nums[i - k]) == 0) {
                counts.remove(nums[i - k]);
            }
        }
        if (i >= k - 1) {
            ans.add(counts.size());
        }
    }
    return ans.stream().mapToInt(i -> i).toArray();
}
```
We use a sliding window approach to keep track of a subarray of the size k in the given array. To find the distinct elements in the subarray, we maintain a hash map named `counts` to store the frequency of each element in the subarray. We iterate through the given array and perform the following steps for each element:

1. Increment the frequency count of the element in the `counts` hash map.
2. If the index `i` is larger or equal to `k`, we know the subarray of size k has moved to the next index. We decrement the frequency count of the element at `nums[i - k]`. If the frequency count becomes zero, we remove this element from the hash map.
3. If the index `i` is larger or equal to `k - 1`, we have a valid subarray of size k. In this case, we append the length of the hash map (which represents the number of distinct elements) to the `ans` array.

At the end, we return the `ans` array.

## A solution in C++

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

vector<int> distinctNumbersInSubarrays(vector<int>& nums, int k) {
    unordered_map<int, int> counts;
    vector<int> ans;
    for (int i = 0; i < nums.size(); i++) {
        counts[nums[i]]++;
        if (i >= k) {
            counts[nums[i - k]]--;
            if (counts[nums[i - k]] == 0) {
                counts.erase(nums[i - k]);
            }
        }
        if (i >= k - 1) {
            ans.push_back(counts.size());
        }
    }
    return ans;
}
```
We use a sliding window approach to keep track of a subarray of the size k in the given array. To find the distinct elements in the subarray, we maintain a hash map named `counts` to store the frequency of each element in the subarray. We iterate through the given array and perform the following steps for each element:

1. Increment the frequency count of the element in the `counts` hash map.
2. If the index `i` is larger or equal to `k`, we know the subarray of size k has moved to the next index. We decrement the frequency count of the element at `nums[i - k]`. If the frequency count becomes zero, we remove this element from the hash map.
3. If the index `i` is larger or equal to `k - 1`, we have a valid subarray of size k. In this case, we append the length of the hash map (which represents the number of distinct elements) to the `ans` array.

At the end, we return the `ans` array.

## A solution in Python

```python
def distinct_numbers_in_subarrays(nums, k):
    counts = {}
    ans = []
    for i, num in enumerate(nums):
        counts[num] = counts.get(num, 0) + 1
        if i >= k:
            counts[nums[i - k]] -= 1
            if counts[nums[i - k]] == 0:
                del counts[nums[i - k]]
        if i >= k - 1:
            ans.append(len(counts))
    return ans
```
We use a sliding window approach to keep track of a subarray of the size k in the given array. To find the distinct elements in the subarray, we maintain a hash map named `counts` to store the frequency of each element in the subarray. We iterate through the given array and perform the following steps for each element:

1. Increment the frequency count of the element in the `counts` hash map.
2. If the index `i` is larger or equal to `k`, we know the subarray of size k has moved to the next index. We decrement the frequency count of the element at `nums[i - k]`. If the frequency count becomes zero, we remove this element from the hash map.
3. If the index `i` is larger or equal to `k - 1`, we have a valid subarray of size k. In this case, we append the length of the hash map (which represents the number of distinct elements) to the `ans` array.

At the end, we return the `ans` array.

## A solution in Javascript

```javascript
function distinctNumbersInSubarrays(nums, k) {
    let counts = new Map();
    let ans = [];
    for (let i = 0; i < nums.length; i++) {
        counts.set(nums[i], (counts.get(nums[i]) || 0) + 1);
        if (i >= k) {
            counts.set(nums[i - k], counts.get(nums[i - k]) - 1);
            if (counts.get(nums[i - k]) === 0) {
                counts.delete(nums[i - k]);
            }
        }
        if (i >= k - 1) {
            ans.push(counts.size);
        }
    }
    return ans;
}
```
We use a sliding window approach to keep track of a subarray of the size k in the given array. To find the distinct elements in the subarray, we maintain a hash map named `counts` to store the frequency of each element in the subarray. We iterate through the given array and perform the following steps for each element:

1. Increment the frequency count of the element in the `counts` hash map.
2. If the index `i` is larger or equal to `k`, we know the subarray of size k has moved to the next index. We decrement the frequency count of the element at `nums[i - k]`. If the frequency count becomes zero, we remove this element from the hash map.
3. If the index `i` is larger or equal to `k - 1`, we have a valid subarray of size k. In this case, we append the length of the hash map (which represents the number of distinct elements) to the `ans` array.

At the end, we return the `ans` array.


# Maximum Population Year

- slug: maximum-population-year
- difficulty: Easy

You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person.

The **population** of some year `x` is the number of people alive during that year. The `ith` person is counted in year `x`'s population if `x` is in the **inclusive** range `[birthi, deathi - 1]`. Note that the person is **not** counted in the year that they die.

Return _the **earliest** year with the **maximum population**_.

**Example 1:**

**Input:** logs = \[\[1993,1999\],\[2000,2010\]\]
**Output:** 1993
**Explanation:** The maximum population is 1, and 1993 is the earliest year with this population.

**Example 2:**

**Input:** logs = \[\[1950,1961\],\[1960,1971\],\[1970,1981\]\]
**Output:** 1960
**Explanation:**
The maximum population is 2, and it had happened in years 1960 and 1970.
The earlier year between them is 1960.

**Constraints:**

*   `1 <= logs.length <= 100`
*   `1950 <= birthi < deathi <= 2050`

## A solution in Java

```java
public int maxAliveYear(int[][] logs) {
    int[] years = new int[101];
    for (int[] log : logs) {
        years[log[0] - 1950]++;
        years[log[1] - 1950]--;
    }
    int max_population = years[0];
    int max_year = 1950;
    for (int i = 1; i < 101; i++) {
        years[i] += years[i - 1];
        if (years[i] > max_population) {
            max_population = years[i];
            max_year = i + 1950;
        }
    }
    return max_year;
}
```
The algorithm iterates through the logs and increments the birth year and decrements the death year in the years array. Then, starting from the first year, it accumulates the population for each year by summing up the previous year's population with the current year's population. After that, it checks which year has the maximum population and returns that year.

## A solution in C++

```cpp
int maxAliveYear(vector<vector<int>>& logs) {
    vector<int> years(101, 0);
    for (vector<int> log : logs) {
        years[log[0] - 1950]++;
        years[log[1] - 1950]--;
    }
    int max_population = years[0];
    int max_year = 1950;
    for (int i = 1; i < 101; i++) {
        years[i] += years[i - 1];
        if (years[i] > max_population) {
            max_population = years[i];
            max_year = i + 1950;
        }
    }
    return max_year;
}
```
The algorithm iterates through the logs and increments the birth year and decrements the death year in the years array. Then, starting from the first year, it accumulates the population for each year by summing up the previous year's population with the current year's population. After that, it checks which year has the maximum population and returns that year.

## A solution in Python

```python
def maxAliveYear(logs):
    years = [0] * 101
    for log in logs:
        years[log[0] - 1950] += 1
        years[log[1] - 1950] -= 1
    max_population = years[0]
    max_year = 1950
    for i in range(1, 101):
        years[i] += years[i - 1]
        if years[i] > max_population:
            max_population = years[i]
            max_year = i + 1950
    return max_year
```
The algorithm iterates through the logs and increments the birth year and decrements the death year in the years array. Then, starting from the first year, it accumulates the population for each year by summing up the previous year's population with the current year's population. After that, it checks which year has the maximum population and returns that year.

## A solution in Javascript

```javascript
function maxAliveYear(logs) {
    let years = new Array(101).fill(0);
    for (let log of logs) {
        years[log[0] - 1950]++;
        years[log[1] - 1950]--;
    }
    let max_population = years[0];
    let max_year = 1950;
    for (let i = 1; i < 101; i++) {
        years[i] += years[i - 1];
        if (years[i] > max_population) {
            max_population = years[i];
            max_year = i + 1950;
        }
    }
    return max_year;
}
```
The algorithm iterates through the logs and increments the birth year and decrements the death year in the years array. Then, starting from the first year, it accumulates the population for each year by summing up the previous year's population with the current year's population. After that, it checks which year has the maximum population and returns that year.


# Maximum Distance Between a Pair of Values

- slug: maximum-distance-between-a-pair-of-values
- difficulty: Medium

You are given two **non-increasing 0-indexed** integer arrays `nums1` and `nums2`.

A pair of indices `(i, j)`, where `0 <= i < nums1.length` and `0 <= j < nums2.length`, is **valid** if both `i <= j` and `nums1[i] <= nums2[j]`. The **distance** of the pair is `j - i`.

Return _the **maximum distance** of any **valid** pair_ `(i, j)`_. If there are no valid pairs, return_ `0`.

An array `arr` is **non-increasing** if `arr[i-1] >= arr[i]` for every `1 <= i < arr.length`.

**Example 1:**

**Input:** nums1 = \[55,30,5,4,2\], nums2 = \[100,20,10,10,5\]
**Output:** 2
**Explanation:** The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).
The maximum distance is 2 with pair (2,4).

**Example 2:**

**Input:** nums1 = \[2,2,2\], nums2 = \[10,10,1\]
**Output:** 1
**Explanation:** The valid pairs are (0,0), (0,1), and (1,1).
The maximum distance is 1 with pair (0,1).

**Example 3:**

**Input:** nums1 = \[30,29,19,5\], nums2 = \[25,25,25,25,25\]
**Output:** 2
**Explanation:** The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).
The maximum distance is 2 with pair (2,4).

**Constraints:**

*   `1 <= nums1.length, nums2.length <= 105`
*   `1 <= nums1[i], nums2[j] <= 105`
*   Both `nums1` and `nums2` are **non-increasing**.

## A solution in Java

```java
public int maxDistance(int[] nums1, int[] nums2) {
    int i = 0, j = 0, maxDist = 0;
    while (i < nums1.length && j < nums2.length) {
        if (nums1[i] > nums2[j]) {
            ++i;
        } else {
            maxDist = Math.max(maxDist, j - i);
            ++j;
        }
    }
    return maxDist;
}
```
The algorithm starts with setting both indices `i` and `j` to zero. A `maxDist` variable is initialized as zero as well. It uses a while loop to navigate through both arrays (nums1 and nums2) as long as the indices are within their respective array boundaries. It then checks whether the element at `nums1[i]` is greater than the element at `nums2[j]`, if true, it increments the index `i`. Otherwise, it updates the `maxDist` variable as the maximum between the existing maximum distance and the new distance (`j - i`), and increments the index `j`.

This algorithm works because it takes advantage of the non-increasing property of both arrays. It moves through the arrays checking each possible valid pair `(i, j)`. It moves index `i` right when the current pair is invalid and moves `j` right when a valid pair is found, updating the maximum distance when necessary.

## A solution in C++

```cpp
int maxDistance(vector<int>& nums1, vector<int>& nums2) {
    int i = 0, j = 0, maxDist = 0;
    while (i < nums1.size() && j < nums2.size()) {
        if (nums1[i] > nums2[j]) {
            ++i;
        } else {
            maxDist = max(maxDist, j - i);
            ++j;
        }
    }
    return maxDist;
}
```
The algorithm starts with setting both indices `i` and `j` to zero. A `maxDist` variable is initialized as zero as well. It uses a while loop to navigate through both arrays (nums1 and nums2) as long as the indices are within their respective array boundaries. It then checks whether the element at `nums1[i]` is greater than the element at `nums2[j]`, if true, it increments the index `i`. Otherwise, it updates the `maxDist` variable as the maximum between the existing maximum distance and the new distance (`j - i`), and increments the index `j`.

This algorithm works because it takes advantage of the non-increasing property of both arrays. It moves through the arrays checking each possible valid pair `(i, j)`. It moves index `i` right when the current pair is invalid and moves `j` right when a valid pair is found, updating the maximum distance when necessary.

## A solution in Python

```python
def maxDistance(nums1, nums2):
    i, j, maxDist = 0, 0, 0
    while i < len(nums1) and j < len(nums2):
        if nums1[i] > nums2[j]:
            i += 1
        else:
            maxDist = max(maxDist, j - i)
            j += 1
    return maxDist
```
The algorithm starts with setting both indices `i` and `j` to zero. A `maxDist` variable is initialized as zero as well. It uses a while loop to navigate through both arrays (nums1 and nums2) as long as the indices are within their respective array boundaries. It then checks whether the element at `nums1[i]` is greater than the element at `nums2[j]`, if true, it increments the index `i`. Otherwise, it updates the `maxDist` variable as the maximum between the existing maximum distance and the new distance (`j - i`), and increments the index `j`.

This algorithm works because it takes advantage of the non-increasing property of both arrays. It moves through the arrays checking each possible valid pair `(i, j)`. It moves index `i` right when the current pair is invalid and moves `j` right when a valid pair is found, updating the maximum distance when necessary.

## A solution in Javascript

```javascript
function maxDistance(nums1, nums2) {
    let i = 0, j = 0, maxDist = 0;
    while (i < nums1.length && j < nums2.length) {
        if (nums1[i] > nums2[j]) {
            ++i;
        } else {
            maxDist = Math.max(maxDist, j - i);
            ++j;
        }
    }
    return maxDist;
}
```
The algorithm starts with setting both indices `i` and `j` to zero. A `maxDist` variable is initialized as zero as well. It uses a while loop to navigate through both arrays (nums1 and nums2) as long as the indices are within their respective array boundaries. It then checks whether the element at `nums1[i]` is greater than the element at `nums2[j]`, if true, it increments the index `i`. Otherwise, it updates the `maxDist` variable as the maximum between the existing maximum distance and the new distance (`j - i`), and increments the index `j`.

This algorithm works because it takes advantage of the non-increasing property of both arrays. It moves through the arrays checking each possible valid pair `(i, j)`. It moves index `i` right when the current pair is invalid and moves `j` right when a valid pair is found, updating the maximum distance when necessary.


# Maximum Subarray Min-Product

- slug: maximum-subarray-min-product
- difficulty: Medium

The **min-product** of an array is equal to the **minimum value** in the array **multiplied by** the array's **sum**.

*   For example, the array `[3,2,5]` (minimum value is `2`) has a min-product of `2 * (3+2+5) = 2 * 10 = 20`.

Given an array of integers `nums`, return _the **maximum min-product** of any **non-empty subarray** of_ `nums`. Since the answer may be large, return it **modulo** `109 + 7`.

Note that the min-product should be maximized **before** performing the modulo operation. Testcases are generated such that the maximum min-product **without** modulo will fit in a **64-bit signed integer**.

A **subarray** is a **contiguous** part of an array.

**Example 1:**

**Input:** nums = \[1,2,3,2\]
**Output:** 14
**Explanation:** The maximum min-product is achieved with the subarray \[2,3,2\] (minimum value is 2).
2 \* (2+3+2) = 2 \* 7 = 14.

**Example 2:**

**Input:** nums = \[2,3,3,1,2\]
**Output:** 18
**Explanation:** The maximum min-product is achieved with the subarray \[3,3\] (minimum value is 3).
3 \* (3+3) = 3 \* 6 = 18.

**Example 3:**

**Input:** nums = \[3,1,5,6,4,2\]
**Output:** 60
**Explanation:** The maximum min-product is achieved with the subarray \[5,6,4\] (minimum value is 4).
4 \* (5+6+4) = 4 \* 15 = 60.

**Constraints:**

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

## A solution in Java

```java
import java.util.Stack;

public int maxSumMinProduct(int[] nums) {
    long max_product = 0;
    Stack<Integer> stk = new Stack<>();
    long[] prefix_sum = new long[nums.length + 1];
    final int MOD = 1000000007;

    for (int i = 0; i < nums.length; i++) {
        prefix_sum[i + 1] = prefix_sum[i] + nums[i];
    }

    for (int i = 0; i < nums.length; i++) {
        while (!stk.isEmpty() && nums[stk.peek()] > nums[i]) {
            int min_val = nums[stk.pop()];
            max_product = Math.max(max_product, min_val * (prefix_sum[i] - prefix_sum[stk.isEmpty() ? 0 : stk.peek() + 1]));
        }
        stk.push(i);
    }

    while (!stk.isEmpty()) {
        int min_val = nums[stk.pop()];
        max_product = Math.max(max_product, min_val * (prefix_sum[nums.length] - prefix_sum[stk.isEmpty() ? 0 : stk.peek() + 1]));
    }

    return (int) (max_product % MOD);
}
```
1. Calculate the prefix sums for every element in the input array.
2. Then, we iterate through the input array and maintain a decreasing monotonic stack.
3. If the current element is lower than the top element of the stack, we calculate the maximum min-product for the top element by popping it from the stack.
4. After processing all elements, we calculate the maximum min-product for the remaining elements in the stack.
5. The time complexity is O(n) as we push and pop each element exactly once.

## A solution in C++

```cpp
#include <vector>
#include <stack>
using namespace std;
constexpr int MOD = 1e9 + 7;

int maxSumMinProduct(vector<int>& nums) {
    long long max_product = 0;
    stack<int> stk;
    vector<long long> prefix_sum(nums.size() + 1);

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

    for(int i = 0; i < nums.size(); i++) {
        while (!stk.empty() && nums[stk.top()] > nums[i]) {
            int min_val = nums[stk.top()];
            stk.pop();
            max_product = max(max_product, min_val * (prefix_sum[i] - prefix_sum[stk.empty() ? 0 : stk.top() + 1]));
        }
        stk.push(i);
    }

    while (!stk.empty()) {
        int min_val = nums[stk.top()];
        stk.pop();
        max_product = max(max_product, min_val * (prefix_sum[nums.size()] - prefix_sum[stk.empty() ? 0 : stk.top() + 1]));
    }

    return max_product % MOD;
}
```
1. Calculate the prefix sums for every element in the input array.
2. Then, we iterate through the input array and maintain a decreasing monotonic stack.
3. If the current element is lower than the top element of the stack, we calculate the maximum min-product for the top element by popping it from the stack.
4. After processing all elements, we calculate the maximum min-product for the remaining elements in the stack.
5. The time complexity is O(n) as we push and pop each element exactly once.

## A solution in Python

```python
def maxSumMinProduct(nums: list[int]) -> int:
    MOD = int(1e9 + 7)
    max_product = 0
    stk = []
    prefix_sum = [0] * (len(nums) + 1)

    for i in range(len(nums)):
        prefix_sum[i + 1] = prefix_sum[i] + nums[i]

    for i in range(len(nums)):
        while stk and nums[stk[-1]] > nums[i]:
            min_val = nums[stk.pop()]
            max_product = max(max_product, min_val * (prefix_sum[i] - prefix_sum[stk[-1] + 1 if stk else 0]))
        stk.append(i)

    while stk:
        min_val = nums[stk.pop()]
        max_product = max(max_product, min_val * (prefix_sum[len(nums)] - prefix_sum[stk[-1] + 1 if stk else 0]))

    return max_product % MOD
```
1. Calculate the prefix sums for every element in the input array.
2. Then, we iterate through the input array and maintain a decreasing monotonic stack.
3. If the current element is lower than the top element of the stack, we calculate the maximum min-product for the top element by popping it from the stack.
4. After processing all elements, we calculate the maximum min-product for the remaining elements in the stack.
5. The time complexity is O(n) as we push and pop each element exactly once.

## A solution in Javascript

```javascript
var maxSumMinProduct = function(nums) {
    const MOD = BigInt(1000000007);
    let max_product = BigInt(0);
    let stk = [];
    let prefix_sum = new BigInt64Array(nums.length + 1);

    for (let i = 0; i < nums.length; i++) {
        prefix_sum[i + 1] = prefix_sum[i] + BigInt(nums[i]);
    }

    for (let i = 0; i < nums.length; i++) {
        while (stk.length > 0 && nums[stk[stk.length - 1]] > nums[i]) {
            let min_val = nums[stk.pop()];
            max_product = BigInt(Math.max(Number(max_product), Number(min_val * (prefix_sum[i] - prefix_sum[stk.length === 0 ? 0 : stk[stk.length - 1] + 1]))));
        }
        stk.push(i);
    }

    while (stk.length > 0) {
        let min_val = nums[stk.pop()];
        max_product = BigInt(Math.max(Number(max_product), Number(min_val * (prefix_sum[nums.length] - prefix_sum[stk.length === 0 ? 0 : stk[stk.length - 1] + 1]))));
    }

    return Number(max_product % MOD);
};
```
1. Calculate the prefix sums for every element in the input array.
2. Then, we iterate through the input array and maintain a decreasing monotonic stack.
3. If the current element is lower than the top element of the stack, we calculate the maximum min-product for the top element by popping it from the stack.
4. After processing all elements, we calculate the maximum min-product for the remaining elements in the stack.
5. The time complexity is O(n) as we push and pop each element exactly once.


# Largest Color Value in a Directed Graph

- slug: largest-color-value-in-a-directed-graph
- difficulty: Hard

There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`.

You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node in this graph (**0-indexed**). You are also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that there is a **directed edge** from node `aj` to node `bj`.

A valid **path** in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk` such that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`. The **color value** of the path is the number of nodes that are colored the **most frequently** occurring color along that path.

Return _the **largest color value** of any valid path in the given graph, or_ `-1` _if the graph contains a cycle_.

**Example 1:**

**Input:** colors =  "abaca ", edges = \[\[0,1\],\[0,2\],\[2,3\],\[3,4\]\]
**Output:** 3
**Explanation:** The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored ` "a " (red in the above image)`.

**Example 2:**

**Input:** colors =  "a ", edges = \[\[0,0\]\]
**Output:** -1
**Explanation:** There is a cycle from 0 to 0.

**Constraints:**

*   `n == colors.length`
*   `m == edges.length`
*   `1 <= n <= 105`
*   `0 <= m <= 105`
*   `colors` consists of lowercase English letters.
*   `0 <= aj, bj < n`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int largestPathValue(String colors, int[][] edges) {
        int n = colors.length();
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<>());
        }

        int[] inDegrees = new int[n];
        for (int[] e : edges) {
            adj.get(e[0]).add(e[1]);
            inDegrees[e[1]]++;
        }

        int[][] colorCounts = new int[n][26];
        Deque<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            if (inDegrees[i] == 0) {
                queue.addLast(i);
            }
        }

        int visitedNodes = 0;
        int maxColorValue = 0;

        while (!queue.isEmpty()) {
            int node = queue.removeLast();
            int color = colors.charAt(node) - 'a';
            visitedNodes++;

            for (int neighbor : adj.get(node)) {
                for (int c = 0; c < 26; c++) {
                    int count = colorCounts[node][c] + (c == color ? 1 : 0);
                    colorCounts[neighbor][c] = Math.max(colorCounts[neighbor][c], count);
                    maxColorValue = Math.max(maxColorValue, count);
                }
                if (--inDegrees[neighbor] == 0) {
                    queue.addLast(neighbor);
                }
            }
        }

        return visitedNodes == n ? maxColorValue : -1;
    }
}
```
We will use the Kahn's algorithm for topological sort to solve this problem. Before starting the algorithm, create an adjacency list representation of the graph and calculate the in-degrees of all nodes.

1. Create an array `colorCounts` of size `n x 26`, where `colorCounts[i][j]` will store the maximum color count of color `j` reachable from node `i` in the given graph.
2. Initialize the `queue` with nodes having 0 in-degree.
3. Initialize `visitedNodes` and `maxColorValue` to 0.
4. While the `queue` is not empty, remove a node. Increment `visitedNodes`.
5. For each neighbor of the removed node, update the color count reachable using this path. If a path with a higher color count is found, update the `maxColorValue`.
6. If a neighbor's in-degree becomes 0, add it to the `queue`.
7. Return the `maxColorValue` if all nodes were visited. Otherwise, there's a cycle in the graph, return -1.

## A solution in C++

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

using namespace std;

int largestPathValue(string colors, vector<vector<int>>& edges) {
    int n = colors.size();
    vector<vector<int>> adj(n);
    vector<int> inDegrees(n, 0);

    for (auto& e : edges) {
        adj[e[0]].push_back(e[1]);
        inDegrees[e[1]]++;
    }

    vector<vector<int>> colorCounts(n, vector<int>(26, 0));
    vector<int> queue;
    for (int i = 0; i < n; i++) {
        if (inDegrees[i] == 0) {
            queue.push_back(i);
        }
    }

    int visitedNodes = 0;
    int maxColorValue = 0;

    while (!queue.empty()) {
        int node = queue.back();
        queue.pop_back();
        int color = colors[node] - 'a';
        visitedNodes++;

        for (int neighbor : adj[node]) {
            for (int c = 0; c < 26; c++) {
                int count = colorCounts[node][c] + (c == color);
                colorCounts[neighbor][c] = max(colorCounts[neighbor][c], count);
                maxColorValue = max(maxColorValue, count);
            }
            if (--inDegrees[neighbor] == 0) {
                queue.push_back(neighbor);
            }
        }
    }

    return visitedNodes == n ? maxColorValue : -1;
}
```
We will use the Kahn's algorithm for topological sort to solve this problem. Before starting the algorithm, create an adjacency list representation of the graph and calculate the in-degrees of all nodes.

1. Create an array `colorCounts` of size `n x 26`, where `colorCounts[i][j]` will store the maximum color count of color `j` reachable from node `i` in the given graph.
2. Initialize the `queue` with nodes having 0 in-degree.
3. Initialize `visitedNodes` and `maxColorValue` to 0.
4. While the `queue` is not empty, remove a node. Increment `visitedNodes`.
5. For each neighbor of the removed node, update the color count reachable using this path. If a path with a higher color count is found, update the `maxColorValue`.
6. If a neighbor's in-degree becomes 0, add it to the `queue`.
7. Return the `maxColorValue` if all nodes were visited. Otherwise, there's a cycle in the graph, return -1.

## A solution in Python

```python
from collections import deque

def largestPathValue(colors: str, edges: List[List[int]]) -> int:
    n = len(colors)
    adj = [[] for _ in range(n)]

    in_degrees = [0] * n
    for e in edges:
        adj[e[0]].append(e[1])
        in_degrees[e[1]] += 1

    color_counts = [[0] * 26 for _ in range(n)]
    queue = deque()

    for i in range(n):
        if in_degrees[i] == 0:
            queue.append(i)

    visited_nodes = 0
    max_color_value = 0

    while queue:
        node = queue.pop()
        color = ord(colors[node]) - ord('a')
        visited_nodes += 1

        for neighbor in adj[node]:
            for c in range(26):
                count = color_counts[node][c] + (c == color)
                color_counts[neighbor][c] = max(color_counts[neighbor][c], count)
                max_color_value = max(max_color_value, count)

            in_degrees[neighbor] -= 1
            if in_degrees[neighbor] == 0:
                queue.append(neighbor)

    return max_color_value if visited_nodes == n else -1
```
We will use the Kahn's algorithm for topological sort to solve this problem. Before starting the algorithm, create an adjacency list representation of the graph and calculate the in-degrees of all nodes.

1. Create an array `colorCounts` of size `n x 26`, where `colorCounts[i][j]` will store the maximum color count of color `j` reachable from node `i` in the given graph.
2. Initialize the `queue` with nodes having 0 in-degree.
3. Initialize `visitedNodes` and `maxColorValue` to 0.
4. While the `queue` is not empty, remove a node. Increment `visitedNodes`.
5. For each neighbor of the removed node, update the color count reachable using this path. If a path with a higher color count is found, update the `maxColorValue`.
6. If a neighbor's in-degree becomes 0, add it to the `queue`.
7. Return the `maxColorValue` if all nodes were visited. Otherwise, there's a cycle in the graph, return -1.

## A solution in Javascript

```javascript
function largestPathValue(colors, edges) {
    const n = colors.length;
    const adj = Array.from({ length: n }, () => []);
    const inDegrees = Array(n).fill(0);

    for (const e of edges) {
        adj[e[0]].push(e[1]);
        inDegrees[e[1]]++;
    }

    const colorCounts = Array.from({ length: n }, () => Array(26).fill(0));
    const queue = [];

    for (let i = 0; i < n; i++) {
        if (inDegrees[i] === 0) {
            queue.push(i);
        }
    }

    let visitedNodes = 0;
    let maxColorValue = 0;

    while (queue.length > 0) {
        const node = queue.pop();
        const color = colors.charCodeAt(node) - 'a'.charCodeAt();
        visitedNodes++;

        for (const neighbor of adj[node]) {
            for (let c = 0; c < 26; c++) {
                const count = colorCounts[node][c] + (c === color ? 1 : 0);
                colorCounts[neighbor][c] = Math.max(colorCounts[neighbor][c], count);
                maxColorValue = Math.max(maxColorValue, count);
            }
            if (--inDegrees[neighbor] === 0) {
                queue.push(neighbor);
            }
        }
    }

    return visitedNodes === n ? maxColorValue : -1;
}
```
We will use the Kahn's algorithm for topological sort to solve this problem. Before starting the algorithm, create an adjacency list representation of the graph and calculate the in-degrees of all nodes.

1. Create an array `colorCounts` of size `n x 26`, where `colorCounts[i][j]` will store the maximum color count of color `j` reachable from node `i` in the given graph.
2. Initialize the `queue` with nodes having 0 in-degree.
3. Initialize `visitedNodes` and `maxColorValue` to 0.
4. While the `queue` is not empty, remove a node. Increment `visitedNodes`.
5. For each neighbor of the removed node, update the color count reachable using this path. If a path with a higher color count is found, update the `maxColorValue`.
6. If a neighbor's in-degree becomes 0, add it to the `queue`.
7. Return the `maxColorValue` if all nodes were visited. Otherwise, there's a cycle in the graph, return -1.


# Longest Word With All Prefixes

- slug: longest-word-with-all-prefixes
- difficulty: Medium

Given an array of strings `words`, find the **longest** string in `words` such that **every prefix** of it is also in `words`.

*   For example, let `words = [ "a ", "app ", "ap "]`. The string `"app "` has prefixes `"ap "` and `"a "`, all of which are in `words`.

Return _the string described above. If there is more than one string with the same length, return the **lexicographically smallest** one, and if no string exists, return_ `" "`.

**Example 1:**

**Input:** words = \[ "k ", "ki ", "kir ", "kira ",  "kiran "\]
**Output:**  "kiran "
**Explanation:**  "kiran " has prefixes  "kira ",  "kir ",  "ki ", and  "k ", and all of them appear in words.

**Example 2:**

**Input:** words = \[ "a ",  "banana ",  "app ",  "appl ",  "ap ",  "apply ",  "apple "\]
**Output:**  "apple "
**Explanation:** Both  "apple " and  "apply " have all their prefixes in words.
However,  "apple " is lexicographically smaller, so we return that.

**Example 3:**

**Input:** words = \[ "abc ",  "bc ",  "ab ",  "qwe "\]
**Output:**  " "

**Constraints:**

*   `1 <= words.length <= 105`
*   `1 <= words[i].length <= 105`
*   `1 <= sum(words[i].length) <= 105`

## A solution in Java

```java
public String maximumTime(String time) {
    char[] result = time.toCharArray();
    if (result[0] == '?') {
        result[0] = (result[1] == '?' || result[1] - '0' < 4) ? '2' : '1';
    }
    if (result[1] == '?') {
        result[1] = (result[0] == '2') ? '3' : '9';
    }
    if (result[3] == '?') {
        result[3] = '5';
    }
    if (result[4] == '?') {
        result[4] = '9';
    }
    return new String(result);
}
```
The algorithm checks the appearance of the '?' character in each position (0, 1, 3, and 4) in the time string, replacing it with the maximum possible valid digit based on the constraints.

1. If the first character of the hour is '?' and the second character is either '?' or less than 4, replace it with '2', otherwise replace it with '1'.
2. Based on the first character, if the second character is '?', replace it with either '3' or '9'.
3. If the character in the minutes' left position is '?', replace it with a '5' since this is the maximum valid digit.
4. If the character in the minutes' right position is '?', replace it with a '9'.

Finally, join the characters back into a string (if applicable) and return the result.

## A solution in C++

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

string maximumTime(string time) {
    if (time[0] == '?') {
        time[0] = (time[1] == '?' || time[1] - '0' < 4) ? '2' : '1';
    }
    if (time[1] == '?') {
        time[1] = (time[0] == '2') ? '3' : '9';
    }
    if (time[3] == '?') {
        time[3] = '5';
    }
    if (time[4] == '?') {
        time[4] = '9';
    }
    return time;
}
```
The algorithm checks the appearance of the '?' character in each position (0, 1, 3, and 4) in the time string, replacing it with the maximum possible valid digit based on the constraints.

1. If the first character of the hour is '?' and the second character is either '?' or less than 4, replace it with '2', otherwise replace it with '1'.
2. Based on the first character, if the second character is '?', replace it with either '3' or '9'.
3. If the character in the minutes' left position is '?', replace it with a '5' since this is the maximum valid digit.
4. If the character in the minutes' right position is '?', replace it with a '9'.

Finally, join the characters back into a string (if applicable) and return the result.

## A solution in Python

```python
def maximum_time(time: str) -> str:
    time = list(time)
    if time[0] == "?":
        time[0] = "2" if time[1] == "?" or int(time[1]) < 4 else "1"
    if time[1] == "?":
        time[1] = "3" if time[0] == "2" else "9"
    if time[3] == "?":
        time[3] = "5"
    if time[4] == "?":
        time[4] = "9"
    return "".join(time)
```
The algorithm checks the appearance of the '?' character in each position (0, 1, 3, and 4) in the time string, replacing it with the maximum possible valid digit based on the constraints.

1. If the first character of the hour is '?' and the second character is either '?' or less than 4, replace it with '2', otherwise replace it with '1'.
2. Based on the first character, if the second character is '?', replace it with either '3' or '9'.
3. If the character in the minutes' left position is '?', replace it with a '5' since this is the maximum valid digit.
4. If the character in the minutes' right position is '?', replace it with a '9'.

Finally, join the characters back into a string (if applicable) and return the result.

## A solution in Javascript

```javascript
function maximumTime(time) {
    let result = time.split('');
    if (result[0] === '?') {
        result[0] = (result[1] === '?' || parseInt(result[1]) < 4) ? '2' : '1';
    }
    if (result[1] === '?') {
        result[1] = (result[0] === '2') ? '3' : '9';
    }
    if (result[3] === '?') {
        result[3] = '5';
    }
    if (result[4] === '?') {
        result[4] = '9';
    }
    return result.join('');
}
```
The algorithm checks the appearance of the '?' character in each position (0, 1, 3, and 4) in the time string, replacing it with the maximum possible valid digit based on the constraints.

1. If the first character of the hour is '?' and the second character is either '?' or less than 4, replace it with '2', otherwise replace it with '1'.
2. Based on the first character, if the second character is '?', replace it with either '3' or '9'.
3. If the character in the minutes' left position is '?', replace it with a '5' since this is the maximum valid digit.
4. If the character in the minutes' right position is '?', replace it with a '9'.

Finally, join the characters back into a string (if applicable) and return the result.


# Sorting the Sentence

- slug: sorting-the-sentence
- difficulty: Easy

A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.

A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence.

*   For example, the sentence `"This is a sentence "` can be shuffled as `"sentence4 a3 is2 This1 "` or `"is2 sentence4 This1 a3 "`.

Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_.

**Example 1:**

**Input:** s =  "is2 sentence4 This1 a3 "
**Output:**  "This is a sentence "
**Explanation:** Sort the words in s to their original positions  "This1 is2 a3 sentence4 ", then remove the numbers.

**Example 2:**

**Input:** s =  "Myself2 Me1 I4 and3 "
**Output:**  "Me Myself and I "
**Explanation:** Sort the words in s to their original positions  "Me1 Myself2 and3 I4 ", then remove the numbers.

**Constraints:**

*   `2 <= s.length <= 200`
*   `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`.
*   The number of words in `s` is between `1` and `9`.
*   The words in `s` are separated by a single space.
*   `s` contains no leading or trailing spaces.

1\. All characters in a are strictly less than those in b (i.e., a\[i\] < b\[i\] for all i). 2. All characters in b are strictly less than those in a (i.e., a\[i\] > b\[i\] for all i). 3. All characters in a and b are the same (i.e., a\[i\] = b\[i\] for all i).

## A solution in Java

```java
int minOperationsToSatisfyConditions(String a, String b) {
    int same = 0, less = 0, greater = 0;

    for (int i = 0; i < a.length(); i++) {
        if (a.charAt(i) == b.charAt(i)) same++;
        else if (a.charAt(i) < b.charAt(i)) less++;
        else greater++;
    }

    return Math.min(same + Math.max(less, greater), Math.min(less, greater));
}
```
The algorithm keeps track of three counts: 'same', 'less', and 'greater'. These counts store the number of characters that are the same, less, and greater in string a compared to string b, respectively. Iterate through the characters in a and b simultaneously, comparing each character and updating the counts accordingly. The minimum number of operations needed to satisfy one of the three conditions is then calculated as the minimum of the sum of 'same' and the maximum of 'less' and 'greater', as well as 'less' and 'greater' individually. This is because you can either change all 'same' characters and one of 'less' or 'greater', or change only one of 'less' or 'greater' while keeping the other characters in the same order.

The time complexity of the algorithm is O(n) where n is the length of input strings a and b, as it iterates through each character pair in the strings once.

## A solution in C++

```cpp
int minOperationsToSatisfyConditions(std::string a, std::string b) {
    int same = 0, less = 0, greater = 0;

    for (size_t i = 0; i < a.length(); ++i) {
        if (a[i] == b[i]) same++;
        else if (a[i] < b[i]) less++;
        else greater++;
    }

    return std::min({same + std::max(less, greater), less, greater});
}
```
The algorithm keeps track of three counts: 'same', 'less', and 'greater'. These counts store the number of characters that are the same, less, and greater in string a compared to string b, respectively. Iterate through the characters in a and b simultaneously, comparing each character and updating the counts accordingly. The minimum number of operations needed to satisfy one of the three conditions is then calculated as the minimum of the sum of 'same' and the maximum of 'less' and 'greater', as well as 'less' and 'greater' individually. This is because you can either change all 'same' characters and one of 'less' or 'greater', or change only one of 'less' or 'greater' while keeping the other characters in the same order.

The time complexity of the algorithm is O(n) where n is the length of input strings a and b, as it iterates through each character pair in the strings once.

## A solution in Python

```python
def min_operations_to_satisfy_conditions(a: str, b: str) -> int:
    same, less, greater = 0, 0, 0

    for i in range(len(a)):
        if a[i] == b[i]:
            same += 1
        elif a[i] < b[i]:
            less += 1
        else:
            greater += 1

    return min(same + max(less, greater), less, greater)
```
The algorithm keeps track of three counts: 'same', 'less', and 'greater'. These counts store the number of characters that are the same, less, and greater in string a compared to string b, respectively. Iterate through the characters in a and b simultaneously, comparing each character and updating the counts accordingly. The minimum number of operations needed to satisfy one of the three conditions is then calculated as the minimum of the sum of 'same' and the maximum of 'less' and 'greater', as well as 'less' and 'greater' individually. This is because you can either change all 'same' characters and one of 'less' or 'greater', or change only one of 'less' or 'greater' while keeping the other characters in the same order.

The time complexity of the algorithm is O(n) where n is the length of input strings a and b, as it iterates through each character pair in the strings once.

## A solution in Javascript

```javascript
function minOperationsToSatisfyConditions(a, b) {
    let same = 0, less = 0, greater = 0;

    for (let i = 0; i < a.length; i++) {
        if (a[i] === b[i]) same++;
        else if (a[i] < b[i]) less++;
        else greater++;
    }

    return Math.min(same + Math.max(less, greater), Math.min(less, greater));
}
```
The algorithm keeps track of three counts: 'same', 'less', and 'greater'. These counts store the number of characters that are the same, less, and greater in string a compared to string b, respectively. Iterate through the characters in a and b simultaneously, comparing each character and updating the counts accordingly. The minimum number of operations needed to satisfy one of the three conditions is then calculated as the minimum of the sum of 'same' and the maximum of 'less' and 'greater', as well as 'less' and 'greater' individually. This is because you can either change all 'same' characters and one of 'less' or 'greater', or change only one of 'less' or 'greater' while keeping the other characters in the same order.

The time complexity of the algorithm is O(n) where n is the length of input strings a and b, as it iterates through each character pair in the strings once.