# Number of Valid Move Combinations On Chessboard

- slug: number-of-valid-move-combinations-on-chessboard
- difficulty: Hard

There is an `8 x 8` chessboard containing `n` pieces (rooks, queens, or bishops). You are given a string array `pieces` of length `n`, where `pieces[i]` describes the type (rook, queen, or bishop) of the `ith` piece. In addition, you are given a 2D integer array `positions` also of length `n`, where `positions[i] = [ri, ci]` indicates that the `ith` piece is currently at the **1-based** coordinate `(ri, ci)` on the chessboard.

When making a **move** for a piece, you choose a **destination** square that the piece will travel toward and stop on.

*   A rook can only travel **horizontally or vertically** from `(r, c)` to the direction of `(r+1, c)`, `(r-1, c)`, `(r, c+1)`, or `(r, c-1)`.
*   A queen can only travel **horizontally, vertically, or diagonally** from `(r, c)` to the direction of `(r+1, c)`, `(r-1, c)`, `(r, c+1)`, `(r, c-1)`, `(r+1, c+1)`, `(r+1, c-1)`, `(r-1, c+1)`, `(r-1, c-1)`.
*   A bishop can only travel **diagonally** from `(r, c)` to the direction of `(r+1, c+1)`, `(r+1, c-1)`, `(r-1, c+1)`, `(r-1, c-1)`.

You must make a **move** for every piece on the board simultaneously. A **move combination** consists of all the **moves** performed on all the given pieces. Every second, each piece will instantaneously travel **one square** towards their destination if they are not already at it. All pieces start traveling at the `0th` second. A move combination is **invalid** if, at a given time, **two or more** pieces occupy the same square.

Return _the number of **valid** move combinations_.

**Notes:**

*   **No two pieces** will start in the **same** square.
*   You may choose the square a piece is already on as its **destination**.
*   If two pieces are **directly adjacent** to each other, it is valid for them to **move past each other** and swap positions in one second.

**Example 1:**

**Input:** pieces = \[ "rook "\], positions = \[\[1,1\]\]
**Output:** 15
**Explanation:** The image above shows the possible squares the piece can move to.

**Example 2:**

**Input:** pieces = \[ "queen "\], positions = \[\[1,1\]\]
**Output:** 22
**Explanation:** The image above shows the possible squares the piece can move to.

**Example 3:**

**Input:** pieces = \[ "bishop "\], positions = \[\[4,3\]\]
**Output:** 12
**Explanation:** The image above shows the possible squares the piece can move to.

**Constraints:**

*   `n == pieces.length`
*   `n == positions.length`
*   `1 <= n <= 4`
*   `pieces` only contains the strings `"rook "`, `"queen "`, and `"bishop "`.
*   There will be at most one queen on the chessboard.
*   `1 <= xi, yi <= 8`
*   Each `positions[i]` is distinct.

## A solution in Java

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

public int countValidCombos(List<String> pieces, List<List<Integer>> positions, int index) {
    if (index == pieces.size()) { return 1; }

    int r = positions.get(index).get(0), c = positions.get(index).get(1);
    int[] dr = {0, 1, 0, -1, 1, 1, -1, -1};
    int[] dc = {1, 0, -1, 0, 1, -1, 1, -1};
    int valids = 0;

    for (int x = 0; x < 8; ++x) {
        if (pieces.get(index).equals("bishop") && x < 4) continue;
        if (pieces.get(index).equals("rook") && x >= 4) break;

        for (int dist = 1; dist <= 8; dist++) {
            int nr = r + dr[x] * dist;
            int nc = c + dc[x] * dist;
            if (nr < 1 || nr > 8 || nc < 1 || nc > 8) break;
            if (nr == r && nc == c) continue;

            boolean valid = true;
            for (int other = 0; other < positions.size(); ++other) {
                if (other == index) continue;
                int orr = positions.get(other).get(0), occ = positions.get(other).get(1);
                if (orr == nr && occ == nc) { valid = false; break; }
                if (orr + occ == nr + nc || orr - occ == nr - nc) { valid = false; break; }
                if (orr == nr || occ == nc) { valid = false; break; }
            }

            if (valid) {
                List<Integer> tmp = new ArrayList<>();
                tmp.add(nr);
                tmp.add(nc);
                positions.set(index, tmp);
                valids += countValidCombos(pieces, positions, index + 1);
                positions.set(index, List.of(r, c));
            }
        }
    }

    return valids;
}
```
For each piece, go through all possible moves considering their type (queens, rooks, and bishops). Then, for each reachable position, check if it conflicts with other pieces' position. If it does not conflict, update the current position and check the moves for the next piece recursively. When all pieces are checked, add the valid combinations.

Then, in each of the four languages (C++, Java, Python, and JavaScript), implement the algorithm by translating the algorithm to each language-specific code style and syntax.

## A solution in C++

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

int countValidCombos(vector<string>& pieces, vector<vector<int>>& positions, int index = 0) {
    if (index == pieces.size()) { return 1; }

    int r = positions[index][0], c = positions[index][1];
    int dr[] = {0, 1, 0, -1, 1, 1, -1, -1};
    int dc[] = {1, 0, -1, 0, 1, -1, 1, -1};
    int valids = 0;

    for (int x = 0; x < 8; ++x) {
        if (pieces[index] == "bishop" && x < 4) continue;
        if (pieces[index] == "rook" && x >= 4) break;

        for (int dist = 1; dist <= 8; dist++) {
            int nr = r + dr[x] * dist;
            int nc = c + dc[x] * dist;
            if (nr < 1 || nr > 8 || nc < 1 || nc > 8) break;
            if (nr == r && nc == c) continue;

            bool valid = true;
            for (int other = 0; other < positions.size(); ++other) {
                if (other == index) continue;
                int orr = positions[other][0], occ = positions[other][1];
                if (orr == nr && occ == nc) { valid = false; break; }
                if (orr + occ == nr + nc || orr - occ == nr - nc) { valid = false; break; }
                if (orr == nr || occ == nc) { valid = false; break; }
            }

            if (valid) {
                vector<int> tmp = {nr, nc};
                positions[index] = tmp;
                valids += countValidCombos(pieces, positions, index + 1);
                positions[index] = {r, c};
            }
        }
    }

    return valids;
}
```
For each piece, go through all possible moves considering their type (queens, rooks, and bishops). Then, for each reachable position, check if it conflicts with other pieces' position. If it does not conflict, update the current position and check the moves for the next piece recursively. When all pieces are checked, add the valid combinations.

Then, in each of the four languages (C++, Java, Python, and JavaScript), implement the algorithm by translating the algorithm to each language-specific code style and syntax.

## A solution in Python

```python
def count_valid_combos(pieces, positions, index=0):
    if index == len(pieces):
        return 1

    r, c = positions[index]
    dr = [0, 1, 0, -1, 1, 1, -1, -1]
    dc = [1, 0, -1, 0, 1, -1, 1, -1]
    valids = 0

    for x in range(8):
        if pieces[index] == "bishop" and x < 4:
            continue
        if pieces[index] == "rook" and x >= 4:
            break

        for dist in range(1, 9):
            nr, nc = r + dr[x] * dist, c + dc[x] * dist
            if nr < 1 or nr > 8 or nc < 1 or nc > 8:
                break
            if nr == r and nc == c:
                continue

            valid = True
            for other in range(len(positions)):
                if other == index:
                    continue
                orr, occ = positions[other]
                if orr == nr and occ == nc:
                    valid = False
                    break
                if orr + occ == nr + nc or orr - occ == nr - nc:
                    valid = False
                    break
                if orr == nr or occ == nc:
                    valid = False
                    break

            if valid:
                positions[index] = [nr, nc]
                valids += count_valid_combos(pieces, positions, index + 1)
                positions[index] = [r, c]

    return valids
```
For each piece, go through all possible moves considering their type (queens, rooks, and bishops). Then, for each reachable position, check if it conflicts with other pieces' position. If it does not conflict, update the current position and check the moves for the next piece recursively. When all pieces are checked, add the valid combinations.

Then, in each of the four languages (C++, Java, Python, and JavaScript), implement the algorithm by translating the algorithm to each language-specific code style and syntax.

## A solution in Javascript

```javascript
function countValidCombos(pieces, positions, index=0) {
    if (index === pieces.length) { return 1; }

    let r = positions[index][0], c = positions[index][1];
    let dr = [0, 1, 0, -1, 1, 1, -1, -1];
    let dc = [1, 0, -1, 0, 1, -1, 1, -1];
    let valids = 0;

    for (let x = 0; x < 8; ++x) {
        if (pieces[index] === "bishop" && x < 4) continue;
        if (pieces[index] === "rook" && x >= 4) break;

        for (let dist = 1; dist <= 8; dist++) {
            let nr = r + dr[x] * dist;
            let nc = c + dc[x] * dist;
            if (nr < 1 || nr > 8 || nc < 1 || nc > 8) break;
            if (nr === r && nc === c) continue;

            let valid = true;
            for (let other = 0; other < positions.length; ++other) {
                if (other === index) continue;
                let orr = positions[other][0], occ = positions[other][1];
                if (orr === nr && occ === nc) { valid = false; break; }
                if (orr + occ === nr + nc || orr - occ === nr - nc) { valid = false; break; }
                if (orr === nr || occ === nc) { valid = false; break; }
            }

            if (valid) {
                positions[index] = [nr, nc];
                valids += countValidCombos(pieces, positions, index + 1);
                positions[index] = [r, c];
            }
        }
    }

    return valids;
}
```
For each piece, go through all possible moves considering their type (queens, rooks, and bishops). Then, for each reachable position, check if it conflicts with other pieces' position. If it does not conflict, update the current position and check the moves for the next piece recursively. When all pieces are checked, add the valid combinations.

Then, in each of the four languages (C++, Java, Python, and JavaScript), implement the algorithm by translating the algorithm to each language-specific code style and syntax.


# Smallest Index With Equal Value

- slug: smallest-index-with-equal-value
- difficulty: Easy

Given a **0-indexed** integer array `nums`, return _the **smallest** index_ `i` _of_ `nums` _such that_ `i mod 10 == nums[i]`_, or_ `-1` _if such index does not exist_.

`x mod y` denotes the **remainder** when `x` is divided by `y`.

**Example 1:**

**Input:** nums = \[0,1,2\]
**Output:** 0
**Explanation:**
i=0: 0 mod 10 = 0 == nums\[0\].
i=1: 1 mod 10 = 1 == nums\[1\].
i=2: 2 mod 10 = 2 == nums\[2\].
All indices have i mod 10 == nums\[i\], so we return the smallest index 0.

**Example 2:**

**Input:** nums = \[4,3,2,1\]
**Output:** 2
**Explanation:**
i=0: 0 mod 10 = 0 != nums\[0\].
i=1: 1 mod 10 = 1 != nums\[1\].
i=2: 2 mod 10 = 2 == nums\[2\].
i=3: 3 mod 10 = 3 != nums\[3\].
2 is the only index which has i mod 10 == nums\[i\].

**Example 3:**

**Input:** nums = \[1,2,3,4,5,6,7,8,9,0\]
**Output:** -1
**Explanation:** No index satisfies i mod 10 == nums\[i\].

**Constraints:**

*   `1 <= nums.length <= 100`
*   `0 <= nums[i] <= 9`

## A solution in Java

```java
public int smallestIndex(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
        if (i % 10 == nums[i]) {
            return i;
        }
    }
    return -1;
}
```
The algorithm iterates through the elements of the input array (nums) and checks whether the current index (i) of the element satisfies the condition `i mod 10 == nums[i]`. If the condition is satisfied, it returns the index (i). If the loop finishes without finding an index that satisfies the condition, it returns -1.

The algorithm has a time complexity of O(n), where n is the length of the input array. This is because the algorithm iterates through the array once.

## A solution in C++

```cpp
int smallestIndex(std::vector<int>& nums) {
    for (size_t i = 0; i < nums.size(); ++i) {
        if (i % 10 == nums[i]) {
            return i;
        }
    }
    return -1;
}
```
The algorithm iterates through the elements of the input array (nums) and checks whether the current index (i) of the element satisfies the condition `i mod 10 == nums[i]`. If the condition is satisfied, it returns the index (i). If the loop finishes without finding an index that satisfies the condition, it returns -1.

The algorithm has a time complexity of O(n), where n is the length of the input array. This is because the algorithm iterates through the array once.

## A solution in Python

```python
def smallest_index(nums):
    for i, num in enumerate(nums):
        if i % 10 == num:
            return i
    return -1
```
The algorithm iterates through the elements of the input array (nums) and checks whether the current index (i) of the element satisfies the condition `i mod 10 == nums[i]`. If the condition is satisfied, it returns the index (i). If the loop finishes without finding an index that satisfies the condition, it returns -1.

The algorithm has a time complexity of O(n), where n is the length of the input array. This is because the algorithm iterates through the array once.

## A solution in Javascript

```javascript
function smallestIndex(nums) {
    for (let i = 0; i < nums.length; i++) {
        if (i % 10 === nums[i]) {
            return i;
        }
    }
    return -1;
}
```
The algorithm iterates through the elements of the input array (nums) and checks whether the current index (i) of the element satisfies the condition `i mod 10 == nums[i]`. If the condition is satisfied, it returns the index (i). If the loop finishes without finding an index that satisfies the condition, it returns -1.

The algorithm has a time complexity of O(n), where n is the length of the input array. This is because the algorithm iterates through the array once.


# Find the Minimum and Maximum Number of Nodes Between Critical Points

- slug: find-the-minimum-and-maximum-number-of-nodes-between-critical-points
- difficulty: Medium

A **critical point** in a linked list is defined as **either** a **local maxima** or a **local minima**.

A node is a **local maxima** if the current node has a value **strictly greater** than the previous node and the next node.

A node is a **local minima** if the current node has a value **strictly smaller** than the previous node and the next node.

Note that a node can only be a local maxima/minima if there exists **both** a previous node and a next node.

Given a linked list `head`, return _an array of length 2 containing_ `[minDistance, maxDistance]` _where_ `minDistance` _is the **minimum distance** between **any two distinct** critical points and_ `maxDistance` _is the **maximum distance** between **any two distinct** critical points. If there are **fewer** than two critical points, return_ `[-1, -1]`.

**Example 1:**

**Input:** head = \[3,1\]
**Output:** \[-1,-1\]
**Explanation:** There are no critical points in \[3,1\].

**Example 2:**

**Input:** head = \[5,3,1,2,5,1,2\]
**Output:** \[1,3\]
**Explanation:** There are three critical points:
- \[5,3,**1**,2,5,1,2\]: The third node is a local minima because 1 is less than 3 and 2.
- \[5,3,1,2,**5**,1,2\]: The fifth node is a local maxima because 5 is greater than 2 and 1.
- \[5,3,1,2,5,**1**,2\]: The sixth node is a local minima because 1 is less than 5 and 2.
The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.
The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.

**Example 3:**

**Input:** head = \[1,3,2,2,3,2,2,2,7\]
**Output:** \[3,3\]
**Explanation:** There are two critical points:
- \[1,**3**,2,2,3,2,2,2,7\]: The second node is a local maxima because 3 is greater than 1 and 2.
- \[1,3,2,2,**3**,2,2,2,7\]: The fifth node is a local maxima because 3 is greater than 2 and 2.
Both the minimum and maximum distances are between the second and the fifth node.
Thus, minDistance and maxDistance is 5 - 2 = 3.
Note that the last node is not considered a local maxima because it does not have a next node.

**Constraints:**

*   The number of nodes in the list is in the range `[2, 105]`.
*   `1 <= Node.val <= 105`

## A solution in Java

```java
public int[] getConcatenation(int[] nums) {
    int n = nums.length;
    int[] ans = new int[2 * n];
    for (int i = 0; i < n; i++) {
        ans[i] = nums[i];
        ans[i + n] = nums[i];
    }
    return ans;
}
```
The algorithm iterates through the input array `nums` from index 0 to index n-1 (inclusive). For each value at index i (`nums[i]`), the algorithm stores the value in the corresponding places in the `ans` array at indices i and i+n. This process effectively concatenates the input array `nums` to itself, creating and returning the desired output array `ans`. Time complexity is O(n) where n is the length of the input array.

## A solution in C++

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

vector<int> getConcatenation(vector<int>& nums) {
    int n = nums.size();
    vector<int> ans(2 * n);
    for (int i = 0; i < n; i++) {
        ans[i] = nums[i];
        ans[i + n] = nums[i];
    }
    return ans;}
```
The algorithm iterates through the input array `nums` from index 0 to index n-1 (inclusive). For each value at index i (`nums[i]`), the algorithm stores the value in the corresponding places in the `ans` array at indices i and i+n. This process effectively concatenates the input array `nums` to itself, creating and returning the desired output array `ans`. Time complexity is O(n) where n is the length of the input array.

## A solution in Python

```python
def get_concatenation(nums):
    n = len(nums)
    ans = [0] * (2 * n)
    for i in range(n):
        ans[i] = nums[i]
        ans[i + n] = nums[i]
    return ans
```
The algorithm iterates through the input array `nums` from index 0 to index n-1 (inclusive). For each value at index i (`nums[i]`), the algorithm stores the value in the corresponding places in the `ans` array at indices i and i+n. This process effectively concatenates the input array `nums` to itself, creating and returning the desired output array `ans`. Time complexity is O(n) where n is the length of the input array.

## A solution in Javascript

```javascript
function getConcatenation(nums) {
    const n = nums.length;
    const ans = new Array(2 * n);
    for (let i = 0; i < n; i++) {
        ans[i] = nums[i];
        ans[i + n] = nums[i];
    }
    return ans;
}
```
The algorithm iterates through the input array `nums` from index 0 to index n-1 (inclusive). For each value at index i (`nums[i]`), the algorithm stores the value in the corresponding places in the `ans` array at indices i and i+n. This process effectively concatenates the input array `nums` to itself, creating and returning the desired output array `ans`. Time complexity is O(n) where n is the length of the input array.


# Minimum Operations to Convert Number

- slug: minimum-operations-to-convert-number
- difficulty: Medium

You are given a **0-indexed** integer array `nums` containing **distinct** numbers, an integer `start`, and an integer `goal`. There is an integer `x` that is initially set to `start`, and you want to perform operations on `x` such that it is converted to `goal`. You can perform the following operation repeatedly on the number `x`:

If `0 <= x <= 1000`, then for any index `i` in the array (`0 <= i < nums.length`), you can set `x` to any of the following:

*   `x + nums[i]`
*   `x - nums[i]`
*   `x ^ nums[i]` (bitwise-XOR)

Note that you can use each `nums[i]` any number of times in any order. Operations that set `x` to be out of the range `0 <= x <= 1000` are valid, but no more operations can be done afterward.

Return _the **minimum** number of operations needed to convert_ `x = start` _into_ `goal`_, and_ `-1` _if it is not possible_.

**Example 1:**

**Input:** nums = \[2,4,12\], start = 2, goal = 12
**Output:** 2
**Explanation:** We can go from 2 -> 14 -> 12 with the following 2 operations.
- 2 + 12 = 14
- 14 - 2 = 12

**Example 2:**

**Input:** nums = \[3,5,7\], start = 0, goal = -4
**Output:** 2
**Explanation:** We can go from 0 -> 3 -> -4 with the following 2 operations.
- 0 + 3 = 3
- 3 - 7 = -4
Note that the last operation sets x out of the range 0 <= x <= 1000, which is valid.

**Example 3:**

**Input:** nums = \[2,8,16\], start = 0, goal = 1
**Output:** -1
**Explanation:** There is no way to convert 0 into 1.

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `-109 <= nums[i], goal <= 109`
*   `0 <= start <= 1000`
*   `start != goal`
*   All the integers in `nums` are distinct.

## A solution in Java

```java
public int countThreeCharPalindromes(String s) {
    int count = 0;
    HashMap<Character, Integer> freq = new HashMap<>();
    for (char ch : s.toCharArray()) {
        freq.put(ch, freq.getOrDefault(ch, 0) + 1);
    }
    for (int value : freq.values()) {
        count += value * (value - 1) / 2;
    }
    return count;
}
```
1. Create a hashmap to store the frequency of each character in the given string.
2. Iterate through the string and populate the frequency hashmap.
3. Iterate through the frequency hashmap.
4. For each character found in the hashmap, calculate the number of ways to create a palindrome of length 3 using the formula `n * (n - 1) / 2`, where `n` is the frequency of the character, and add this value to the counter.
5. Return the counter, which represents the number of unique palindromes of length 3 that are a subsequence of the input string.

## A solution in C++

```cpp
int countThreeCharPalindromes(const std::string &s) {
    int count = 0;
    std::unordered_map<char, int> freq;
    for (char ch : s) {
        if (freq.find(ch) != freq.end()) freq[ch]++;
        else freq[ch] = 1;
    }
    for (const auto &it : freq) {
        count += (it.second) * (it.second - 1) / 2;
    }
    return count;
}
```
1. Create a hashmap to store the frequency of each character in the given string.
2. Iterate through the string and populate the frequency hashmap.
3. Iterate through the frequency hashmap.
4. For each character found in the hashmap, calculate the number of ways to create a palindrome of length 3 using the formula `n * (n - 1) / 2`, where `n` is the frequency of the character, and add this value to the counter.
5. Return the counter, which represents the number of unique palindromes of length 3 that are a subsequence of the input string.

## A solution in Python

```python
def count_three_char_palindromes(s):
    count = 0
    freq = {}
    for ch in s:
        if ch in freq:
            freq[ch] += 1
        else:
            freq[ch] = 1
    for value in freq.values():
        count += value * (value - 1) // 2
    return count
```
1. Create a hashmap to store the frequency of each character in the given string.
2. Iterate through the string and populate the frequency hashmap.
3. Iterate through the frequency hashmap.
4. For each character found in the hashmap, calculate the number of ways to create a palindrome of length 3 using the formula `n * (n - 1) / 2`, where `n` is the frequency of the character, and add this value to the counter.
5. Return the counter, which represents the number of unique palindromes of length 3 that are a subsequence of the input string.

## A solution in Javascript

```javascript
function countThreeCharPalindromes(s) {
    let count = 0;
    let freq = {};
    for (let ch of s) {
        if (ch in freq) {
            freq[ch]++;
        } else {
            freq[ch] = 1;
        }
    }
    for (let value of Object.values(freq)) {
        count += value * (value - 1) / 2;
    }
    return count;
}
```
1. Create a hashmap to store the frequency of each character in the given string.
2. Iterate through the string and populate the frequency hashmap.
3. Iterate through the frequency hashmap.
4. For each character found in the hashmap, calculate the number of ways to create a palindrome of length 3 using the formula `n * (n - 1) / 2`, where `n` is the frequency of the character, and add this value to the counter.
5. Return the counter, which represents the number of unique palindromes of length 3 that are a subsequence of the input string.


# Check if an Original String Exists Given Two Encoded Strings

- slug: check-if-an-original-string-exists-given-two-encoded-strings
- difficulty: Hard

An original string, consisting of lowercase English letters, can be encoded by the following steps:

*   Arbitrarily **split** it into a **sequence** of some number of **non-empty** substrings.
*   Arbitrarily choose some elements (possibly none) of the sequence, and **replace** each with **its length** (as a numeric string).
*   **Concatenate** the sequence as the encoded string.

For example, **one way** to encode an original string `"abcdefghijklmnop "` might be:

*   Split it as a sequence: `[ "ab ", "cdefghijklmn ", "o ", "p "]`.
*   Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes `[ "ab ", "12 ", "1 ", "p "]`.
*   Concatenate the elements of the sequence to get the encoded string: `"ab121p "`.

Given two encoded strings `s1` and `s2`, consisting of lowercase English letters and digits `1-9` (inclusive), return `true` _if there exists an original string that could be encoded as **both**_ `s1` _and_ `s2`_. Otherwise, return_ `false`.

**Note**: The test cases are generated such that the number of consecutive digits in `s1` and `s2` does not exceed `3`.

**Example 1:**

**Input:** s1 =  "internationalization ", s2 =  "i18n "
**Output:** true
**Explanation:** It is possible that  "internationalization " was the original string.
-  "internationalization "
  -> Split:       \[ "internationalization "\]
  -> Do not replace any element
  -> Concatenate:   "internationalization ", which is s1.
-  "internationalization "
  -> Split:       \[ "i ",  "nternationalizatio ",  "n "\]
  -> Replace:     \[ "i ",  "18 ",                  "n "\]
  -> Concatenate:   "i18n ", which is s2

**Example 2:**

**Input:** s1 =  "l123e ", s2 =  "44 "
**Output:** true
**Explanation:** It is possible that  "leetcode " was the original string.
-  "leetcode "
  -> Split:      \[ "l ",  "e ",  "et ",  "cod ",  "e "\]
  -> Replace:    \[ "l ",  "1 ",  "2 ",   "3 ",    "e "\]
  -> Concatenate:  "l123e ", which is s1.
-  "leetcode "
  -> Split:      \[ "leet ",  "code "\]
  -> Replace:    \[ "4 ",     "4 "\]
  -> Concatenate:  "44 ", which is s2.

**Example 3:**

**Input:** s1 =  "a5b ", s2 =  "c5b "
**Output:** false
**Explanation:** It is impossible.
- The original string encoded as s1 must start with the letter 'a'.
- The original string encoded as s2 must start with the letter 'c'.

**Constraints:**

*   `1 <= s1.length, s2.length <= 40`
*   `s1` and `s2` consist of digits `1-9` (inclusive), and lowercase English letters only.
*   The number of consecutive digits in `s1` and `s2` does not exceed `3`.

## A solution in Java

```java
public TreeNode mergeTrees(List<TreeNode> trees) {
    while (trees.size() > 1) {
        TreeNode tree1 = trees.remove(trees.size() - 1);
        TreeNode tree2 = trees.remove(trees.size() - 1);

        if (tree1.val < tree2.val) {
            tree1.right = tree2;
            trees.add(tree1);
        } else {
            tree2.right = tree1;
            trees.add(tree2);
        }
    }
    return trees.isEmpty() ? null : trees.get(0);
}
```
The algorithm works by repeatedly merging the last two trees from the input list until there is only one tree left, or the list is empty. In each iteration, the function takes the last two trees from the list, compares their root values, and appends the tree with the smaller value's right child to the tree with the larger value. If the tree with the smaller value doesn't have the right subtree already, the resulting tree still holds the BST property. Then, the resultant tree is pushed back to the list. This operation will be performed n - 1 times. If we can make a valid BST, at the end there will be only one tree left in the list and we return its root. Otherwise, we return null.

## A solution in C++

```cpp
TreeNode* mergeTrees(vector<TreeNode*>& trees) {
    while (trees.size() > 1) {
        TreeNode* tree1 = trees.back(); trees.pop_back();
        TreeNode* tree2 = trees.back(); trees.pop_back();

        if (tree1->val < tree2->val) {
            tree1->right = tree2;
            trees.push_back(tree1);
        } else {
            tree2->right = tree1;
            trees.push_back(tree2);
        }
    }
    return trees.empty() ? nullptr : trees[0];
}
```
The algorithm works by repeatedly merging the last two trees from the input list until there is only one tree left, or the list is empty. In each iteration, the function takes the last two trees from the list, compares their root values, and appends the tree with the smaller value's right child to the tree with the larger value. If the tree with the smaller value doesn't have the right subtree already, the resulting tree still holds the BST property. Then, the resultant tree is pushed back to the list. This operation will be performed n - 1 times. If we can make a valid BST, at the end there will be only one tree left in the list and we return its root. Otherwise, we return null.

## A solution in Python

```python
def merge_trees(trees):
    while len(trees) > 1:
        tree1 = trees.pop()
        tree2 = trees.pop()

        if tree1.val < tree2.val:
            tree1.right = tree2
            trees.append(tree1)
        else:
            tree2.right = tree1
            trees.append(tree2)
    return None if not trees else trees[0]
```
The algorithm works by repeatedly merging the last two trees from the input list until there is only one tree left, or the list is empty. In each iteration, the function takes the last two trees from the list, compares their root values, and appends the tree with the smaller value's right child to the tree with the larger value. If the tree with the smaller value doesn't have the right subtree already, the resulting tree still holds the BST property. Then, the resultant tree is pushed back to the list. This operation will be performed n - 1 times. If we can make a valid BST, at the end there will be only one tree left in the list and we return its root. Otherwise, we return null.

## A solution in Javascript

```javascript
function mergeTrees(trees) {
    while (trees.length > 1) {
        let tree1 = trees.pop();
        let tree2 = trees.pop();

        if (tree1.val < tree2.val) {
            tree1.right = tree2;
            trees.push(tree1);
        } else {
            tree2.right = tree1;
            trees.push(tree2);
        }
    }
    return trees.length === 0 ? null : trees[0];
}
```
The algorithm works by repeatedly merging the last two trees from the input list until there is only one tree left, or the list is empty. In each iteration, the function takes the last two trees from the list, compares their root values, and appends the tree with the smaller value's right child to the tree with the larger value. If the tree with the smaller value doesn't have the right subtree already, the resulting tree still holds the BST property. Then, the resultant tree is pushed back to the list. This operation will be performed n - 1 times. If we can make a valid BST, at the end there will be only one tree left in the list and we return its root. Otherwise, we return null.


# Number of Spaces Cleaning Robot Cleaned

- slug: number-of-spaces-cleaning-robot-cleaned
- difficulty: Medium

A room is represented by a **0-indexed** 2D binary matrix `room` where a `0` represents an **empty** space and a `1` represents a space with an **object**. The top left corner of the room will be empty in all test cases.

A cleaning robot starts at the top left corner of the room and is facing right. The robot will continue heading straight until it reaches the edge of the room or it hits an object, after which it will turn 90 degrees **clockwise** and repeat this process. The starting space and all spaces that the robot visits are **cleaned** by it.

Return _the number of **clean** spaces in the room if the robot runs indefinetely._

**Example 1:**

**Input:** room = \[\[0,0,0\],\[1,1,0\],\[0,0,0\]\]
**Output:** 7
**Explanation:**
The robot cleans the spaces at (0, 0), (0, 1), and (0, 2).
The robot is at the edge of the room, so it turns 90 degrees clockwise and now faces down.
The robot cleans the spaces at (1, 2), and (2, 2).
The robot is at the edge of the room, so it turns 90 degrees clockwise and now faces left.
The robot cleans the spaces at (2, 1), and (2, 0).
The robot has cleaned all 7 empty spaces, so return 7.

**Example 2:**

**Input:** room = \[\[0,1,0\],\[1,0,0\],\[0,0,0\]\]
**Output:** 1
**Explanation:**
The robot cleans the space at (0, 0).
The robot hits an object, so it turns 90 degrees clockwise and now faces down.
The robot hits an object, so it turns 90 degrees clockwise and now faces left.
The robot is at the edge of the room, so it turns 90 degrees clockwise and now faces up.
The robot is at the edge of the room, so it turns 90 degrees clockwise and now faces right.
The robot is back at its starting position.
The robot has cleaned 1 space, so return 1.

**Constraints:**

*   `m == room.length`
*   `n == room[r].length`
*   `1 <= m, n <= 300`
*   `room[r][c]` is either `0` or `1`.
*   `room[0][0] == 0`

## A solution in Java

```java
public int colorTheGrid(int m, int n) {
    long mod = 1000000007;
    long[] dp = {6, 6};
    long[] dpf = {3, 3};

    for (int i = 2; i <= Math.max(m, n); ++i) {
        long temp = dp[1];
        dp[1] = (dpf[1] * 2) % mod;
        dp[0] = temp;
        dpf[1] = (dpf[1] + dpf[0]) % mod;
        dpf[0] = (dpf[0] + temp) % mod;
    }

    return (int)((dp[m == 1 ? 0 : 1] * dpf[n == 1 ? 0 : 1]) % mod);
}
```
The problem can be solved by dynamic programming. We can use two DP arrays, dp and dpf. The dp array is used to store the number of ways to fill the first i columns, where dp[0] represents filling the first i columns with 3-cell components, and dp[1] represents filling with 2-cell components. The dpf array is similar, but it's used for the vertical direction.

In each iteration of the loop from 2 to max(m, n), we calculate the number of ways to fill the first i columns for both 2-cell and 3-cell components and update the dp and dpf arrays accordingly.

After the loop, the result is the multiplication of the values corresponding to m and n, modulo 10^9 + 7.

## A solution in C++

```cpp
int colorTheGrid(int m, int n) {
    long long int mod = 1e9 + 7;
    long long int dp[2] = {6, 6}, dpf[2] = {3, 3};

    for (int i = 2; i <= max(m, n); ++i) {
        long long int temp = dp[1];
        dp[1] = (dpf[1] * 2) % mod;
        dp[0] = temp;
        dpf[1] = (dpf[1] + dpf[0]) % mod;
        dpf[0] = (dpf[0] + temp) % mod;
    }

    return (dp[m == 1] * dpf[n == 1]) % mod;
}
```
The problem can be solved by dynamic programming. We can use two DP arrays, dp and dpf. The dp array is used to store the number of ways to fill the first i columns, where dp[0] represents filling the first i columns with 3-cell components, and dp[1] represents filling with 2-cell components. The dpf array is similar, but it's used for the vertical direction.

In each iteration of the loop from 2 to max(m, n), we calculate the number of ways to fill the first i columns for both 2-cell and 3-cell components and update the dp and dpf arrays accordingly.

After the loop, the result is the multiplication of the values corresponding to m and n, modulo 10^9 + 7.

## A solution in Python

```python
def colorTheGrid(m, n):
    mod = 10**9 + 7
    dp = [6, 6]
    dpf = [3, 3]

    for _ in range(2, max(m, n) + 1):
        temp = dp[1]
        dp[1] = (dpf[1] * 2) % mod
        dp[0] = temp
        dpf[1] = (dpf[1] + dpf[0]) % mod
        dpf[0] = (dpf[0] + temp) % mod

    return (dp[0 if m == 1 else 1] * dpf[0 if n == 1 else 1]) % mod
```
The problem can be solved by dynamic programming. We can use two DP arrays, dp and dpf. The dp array is used to store the number of ways to fill the first i columns, where dp[0] represents filling the first i columns with 3-cell components, and dp[1] represents filling with 2-cell components. The dpf array is similar, but it's used for the vertical direction.

In each iteration of the loop from 2 to max(m, n), we calculate the number of ways to fill the first i columns for both 2-cell and 3-cell components and update the dp and dpf arrays accordingly.

After the loop, the result is the multiplication of the values corresponding to m and n, modulo 10^9 + 7.

## A solution in Javascript

```javascript
function colorTheGrid(m, n) {
    const mod = 1000000007;
    const dp = [6, 6];
    const dpf = [3, 3];

    for (let i = 2; i <= Math.max(m, n); ++i) {
        const temp = dp[1];
        dp[1] = (dpf[1] * 2) % mod;
        dp[0] = temp;
        dpf[1] = (dpf[1] + dpf[0]) % mod;
        dpf[0] = (dpf[0] + temp) % mod;
    }

    return (dp[m === 1 ? 0 : 1] * dpf[n === 1 ? 0 : 1]) % mod;
}
```
The problem can be solved by dynamic programming. We can use two DP arrays, dp and dpf. The dp array is used to store the number of ways to fill the first i columns, where dp[0] represents filling the first i columns with 3-cell components, and dp[1] represents filling with 2-cell components. The dpf array is similar, but it's used for the vertical direction.

In each iteration of the loop from 2 to max(m, n), we calculate the number of ways to fill the first i columns for both 2-cell and 3-cell components and update the dp and dpf arrays accordingly.

After the loop, the result is the multiplication of the values corresponding to m and n, modulo 10^9 + 7.


# Count Vowel Substrings of a String

- slug: count-vowel-substrings-of-a-string
- difficulty: Easy

A **substring** is a contiguous (non-empty) sequence of characters within a string.

A **vowel substring** is a substring that **only** consists of vowels (`'a'`, `'e'`, `'i'`, `'o'`, and `'u'`) and has **all five** vowels present in it.

Given a string `word`, return _the number of **vowel substrings** in_ `word`.

**Example 1:**

**Input:** word =  "aeiouu "
**Output:** 2
**Explanation:** The vowel substrings of word are as follows (underlined):
-  "**aeiou**u "
-  "**aeiouu** "

**Example 2:**

**Input:** word =  "unicornarihan "
**Output:** 0
**Explanation:** Not all 5 vowels are present, so there are no vowel substrings.

**Example 3:**

**Input:** word =  "cuaieuouac "
**Output:** 7
**Explanation:** The vowel substrings of word are as follows (underlined):
-  "c**uaieuo**uac "
-  "c**uaieuou**ac "
-  "c**uaieuoua**c "
-  "cu**aieuo**uac "
-  "cu**aieuou**ac "
-  "cu**aieuoua**c "
-  "cua**ieuoua**c "

**Constraints:**

*   `1 <= word.length <= 100`
*   `word` consists of lowercase English letters only.

## A solution in Java

```java
int countVowelSubstrings(String word) {
    int count = 0, a = 0, e = 0, i = 0, o = 0, u = 0;
    for (char c : word.toCharArray()) {
        if (c == 'a') a++;
        else if (c == 'e') e = a + e;
        else if (c == 'i') i = e + i;
        else if (c == 'o') o = i + o;
        else if (c == 'u') u = o + u;
    }
    return u;
}
```
The algorithm counts the number of vowel substrings in the given input `word`. The basic idea is to maintain separate counter variables for each vowel `a`, `e`, `i`, `o`, and `u`. When iterating through the characters of the input string, the algorithm increases or updates the respective counter variables based on whether a character is a given type of vowel. The updated counter variables keep track of the number of vowel substrings. Once the iteration is completed, the result can be obtained from the counter variable of last vowel `u`. This solution has a time complexity of O(N), where N is the length of the input string `word`.

## A solution in C++

```cpp
int countVowelSubstrings(string word) {
    int count = 0, a = 0, e = 0, i = 0, o = 0, u = 0;
    for (char c : word) {
        if (c == 'a') a++;
        else if (c == 'e') e = a + e;
        else if (c == 'i') i = e + i;
        else if (c == 'o') o = i + o;
        else if (c == 'u') u = o + u;
    }
    return u;
}
```
The algorithm counts the number of vowel substrings in the given input `word`. The basic idea is to maintain separate counter variables for each vowel `a`, `e`, `i`, `o`, and `u`. When iterating through the characters of the input string, the algorithm increases or updates the respective counter variables based on whether a character is a given type of vowel. The updated counter variables keep track of the number of vowel substrings. Once the iteration is completed, the result can be obtained from the counter variable of last vowel `u`. This solution has a time complexity of O(N), where N is the length of the input string `word`.

## A solution in Python

```python
def count_vowel_substrings(word: str) -> int:
    count, a, e, i, o, u = 0, 0, 0, 0, 0, 0
    for c in word:
        if c == 'a': a += 1
        elif c == 'e': e = a + e
        elif c == 'i': i = e + i
        elif c == 'o': o = i + o
        elif c == 'u': u = o + u
    return u
```
The algorithm counts the number of vowel substrings in the given input `word`. The basic idea is to maintain separate counter variables for each vowel `a`, `e`, `i`, `o`, and `u`. When iterating through the characters of the input string, the algorithm increases or updates the respective counter variables based on whether a character is a given type of vowel. The updated counter variables keep track of the number of vowel substrings. Once the iteration is completed, the result can be obtained from the counter variable of last vowel `u`. This solution has a time complexity of O(N), where N is the length of the input string `word`.

## A solution in Javascript

```javascript
function countVowelSubstrings(word) {
    let count = 0, a = 0, e = 0, i = 0, o = 0, u = 0;
    for (let c of word) {
        if (c === 'a') a++;
        else if (c === 'e') e = a + e;
        else if (c === 'i') i = e + i;
        else if (c === 'o') o = i + o;
        else if (c === 'u') u = o + u;
    }
    return u;
}
```
The algorithm counts the number of vowel substrings in the given input `word`. The basic idea is to maintain separate counter variables for each vowel `a`, `e`, `i`, `o`, and `u`. When iterating through the characters of the input string, the algorithm increases or updates the respective counter variables based on whether a character is a given type of vowel. The updated counter variables keep track of the number of vowel substrings. Once the iteration is completed, the result can be obtained from the counter variable of last vowel `u`. This solution has a time complexity of O(N), where N is the length of the input string `word`.


# Vowels of All Substrings

- slug: vowels-of-all-substrings
- difficulty: Medium

Given a string `word`, return _the **sum of the number of vowels** (_`'a'`, `'e'`_,_ `'i'`_,_ `'o'`_, and_ `'u'`_)_ _in every substring of_ `word`.

A **substring** is a contiguous (non-empty) sequence of characters within a string.

**Note:** Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.

**Example 1:**

**Input:** word =  "aba "
**Output:** 6
**Explanation:**
All possible substrings are:  "a ",  "ab ",  "aba ",  "b ",  "ba ", and  "a ".
-  "b " has 0 vowels in it
-  "a ",  "ab ",  "ba ", and  "a " have 1 vowel each
-  "aba " has 2 vowels in it
Hence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6.

**Example 2:**

**Input:** word =  "abc "
**Output:** 3
**Explanation:**
All possible substrings are:  "a ",  "ab ",  "abc ",  "b ",  "bc ", and  "c ".
-  "a ",  "ab ", and  "abc " have 1 vowel each
-  "b ",  "bc ", and  "c " have 0 vowels each
Hence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.

**Example 3:**

**Input:** word =  "ltcd "
**Output:** 0
**Explanation:** There are no vowels in any substring of  "ltcd ".

**Constraints:**

*   `1 <= word.length <= 105`
*   `word` consists of lowercase English letters.

## A solution in Java

```java
public long countVowels(CharSequence word) {
    long sum = 0;
    int count = 0;
    for (int i = 0; i < word.length(); i++) {
        if (word.charAt(i) == 'a' || word.charAt(i) == 'e' || word.charAt(i) == 'i' || word.charAt(i) == 'o' || word.charAt(i) == 'u') {
            count++;
        }
        sum += count;
    }
    return sum;
}

public long countVowelsInSubstrings(String word) {
    return countVowels(word);
}
```
For each position `i` in the string `word`, we calculate the number of vowels in that position. To achieve this, we maintain a `count` variable that increments by 1 every time a vowel is encountered. For each position, this `count` variable holds the total number of vowels found so far, including the current position if the character is a vowel. We accumulate this count onto a `sum` variable, which will store the sum of the number of vowels in all possible substrings ending at the current position. To find the sum of all vowels in all possible substrings of the entire `word`, we just iterate through each character and accumulate the count into the `sum` variable. This algorithm has a linear time complexity of O(n) where n is the length of the input string `word`.

## A solution in C++

```cpp
#include <string>

long long count_vowels(const std::string& word) {
    long long sum = 0;
    int count = 0;
    for (int i = 0; i < word.length(); i++) {
        if (word[i] == 'a' || word[i] == 'e' || word[i] == 'i' || word[i] == 'o' || word[i] == 'u') {
            count++;
        }
        sum += count;
    }
    return sum;
}

long long count_vowels_in_substrings(std::string word) {
    return count_vowels(word);
}
```
For each position `i` in the string `word`, we calculate the number of vowels in that position. To achieve this, we maintain a `count` variable that increments by 1 every time a vowel is encountered. For each position, this `count` variable holds the total number of vowels found so far, including the current position if the character is a vowel. We accumulate this count onto a `sum` variable, which will store the sum of the number of vowels in all possible substrings ending at the current position. To find the sum of all vowels in all possible substrings of the entire `word`, we just iterate through each character and accumulate the count into the `sum` variable. This algorithm has a linear time complexity of O(n) where n is the length of the input string `word`.

## A solution in Python

```python
def count_vowels(word):
    sum = 0
    count = 0
    for letter in word:
        if letter in "aeiou":
            count += 1
        sum += count
    return sum

def count_vowels_in_substrings(word):
    return count_vowels(word)
```
For each position `i` in the string `word`, we calculate the number of vowels in that position. To achieve this, we maintain a `count` variable that increments by 1 every time a vowel is encountered. For each position, this `count` variable holds the total number of vowels found so far, including the current position if the character is a vowel. We accumulate this count onto a `sum` variable, which will store the sum of the number of vowels in all possible substrings ending at the current position. To find the sum of all vowels in all possible substrings of the entire `word`, we just iterate through each character and accumulate the count into the `sum` variable. This algorithm has a linear time complexity of O(n) where n is the length of the input string `word`.

## A solution in Javascript

```javascript
function countVowels(word) {
    let sum = 0;
    let count = 0;
    for (let i = 0; i < word.length; i++) {
        if (word[i] === 'a' || word[i] === 'e' || word[i] === 'i' || word[i] === 'o' || word[i] === 'u') {
            count++;
        }
        sum += count;
    }
    return sum;
}

function countVowelsInSubstrings(word) {
    return countVowels(word);
}
```
For each position `i` in the string `word`, we calculate the number of vowels in that position. To achieve this, we maintain a `count` variable that increments by 1 every time a vowel is encountered. For each position, this `count` variable holds the total number of vowels found so far, including the current position if the character is a vowel. We accumulate this count onto a `sum` variable, which will store the sum of the number of vowels in all possible substrings ending at the current position. To find the sum of all vowels in all possible substrings of the entire `word`, we just iterate through each character and accumulate the count into the `sum` variable. This algorithm has a linear time complexity of O(n) where n is the length of the input string `word`.


# Minimized Maximum of Products Distributed to Any Store

- slug: minimized-maximum-of-products-distributed-to-any-store
- difficulty: Medium

You are given an integer `n` indicating there are `n` specialty retail stores. There are `m` product types of varying amounts, which are given as a **0-indexed** integer array `quantities`, where `quantities[i]` represents the number of products of the `ith` product type.

You need to distribute **all products** to the retail stores following these rules:

*   A store can only be given **at most one product type** but can be given **any** amount of it.
*   After distribution, each store will have been given some number of products (possibly `0`). Let `x` represent the maximum number of products given to any store. You want `x` to be as small as possible, i.e., you want to **minimize** the **maximum** number of products that are given to any store.

Return _the minimum possible_ `x`.

**Example 1:**

**Input:** n = 6, quantities = \[11,6\]
**Output:** 3
**Explanation:** One optimal way is:
- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3
- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3
The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.

**Example 2:**

**Input:** n = 7, quantities = \[15,10,10\]
**Output:** 5
**Explanation:** One optimal way is:
- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5
- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5
- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5
The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.

**Example 3:**

**Input:** n = 1, quantities = \[100000\]
**Output:** 100000
**Explanation:** The only optimal way is:
- The 100000 products of type 0 are distributed to the only store.
The maximum number of products given to any store is max(100000) = 100000.

**Constraints:**

*   `m == quantities.length`
*   `1 <= m <= n <= 105`
*   `1 <= quantities[i] <= 105`

## A solution in Java

```java
public int minimum_maximum(int n, int[] quantities) {
    int sum_products = 0;
    for (int q : quantities) {
        sum_products += q;
    }

    int x = (sum_products + n - 1) / n;
    int remaining_stores = n;
    for (int q : quantities) {
        remaining_stores -= (q + x - 1) / x;
        if (remaining_stores < 0) {
            x = (sum_products + remaining_stores) / (n + remaining_stores);
            remaining_stores = n;
        }
    }
    return x;
}
```
- Calculate the sum of all products to be distributed.
- Calculate an initial estimate for x by dividing the total number of products by the number of stores.
- Initialize a remaining_stores variable to store the stores that have not been assigned products yet.
- Iterate through each product type:
  - Decrease remaining_stores by the number of stores needed to distribute the current product type with the current value of x.
  - If remaining_stores becomes negative, it means x is too small. Recalculate x using the current remaining_stores and start over with remaining_stores equal to the number of stores.
- Return x when there's no need for further adjustment.

## A solution in C++

```cpp
int minimum_maximum(int n, vector<int>& quantities) {
    int sum_products = 0;
    for (int q : quantities) {
        sum_products += q;
    }

    int x = (sum_products + n - 1) / n;
    int remaining_stores = n;
    for (int q : quantities) {
        remaining_stores -= (q + x - 1) / x;
        if (remaining_stores < 0) {
            x = (sum_products + remaining_stores) / (n + remaining_stores);
            remaining_stores = n;
        }
    }
    return x;
}
```
- Calculate the sum of all products to be distributed.
- Calculate an initial estimate for x by dividing the total number of products by the number of stores.
- Initialize a remaining_stores variable to store the stores that have not been assigned products yet.
- Iterate through each product type:
  - Decrease remaining_stores by the number of stores needed to distribute the current product type with the current value of x.
  - If remaining_stores becomes negative, it means x is too small. Recalculate x using the current remaining_stores and start over with remaining_stores equal to the number of stores.
- Return x when there's no need for further adjustment.

## A solution in Python

```python
def minimum_maximum(n, quantities):
    sum_products = sum(quantities)
    x = (sum_products + n - 1) // n
    remaining_stores = n
    for q in quantities:
        remaining_stores -= (q + x - 1) // x
        if remaining_stores < 0:
            x = (sum_products + remaining_stores) // (n + remaining_stores)
            remaining_stores = n
    return x
```
- Calculate the sum of all products to be distributed.
- Calculate an initial estimate for x by dividing the total number of products by the number of stores.
- Initialize a remaining_stores variable to store the stores that have not been assigned products yet.
- Iterate through each product type:
  - Decrease remaining_stores by the number of stores needed to distribute the current product type with the current value of x.
  - If remaining_stores becomes negative, it means x is too small. Recalculate x using the current remaining_stores and start over with remaining_stores equal to the number of stores.
- Return x when there's no need for further adjustment.

## A solution in Javascript

```javascript
function minimum_maximum(n, quantities) {
    let sum_products = quantities.reduce((a, b) => a + b, 0);

    let x = Math.floor((sum_products + n - 1) / n);
    let remaining_stores = n;
    for (let q of quantities) {
        remaining_stores -= Math.floor((q + x - 1) / x);
        if (remaining_stores < 0) {
            x = Math.floor((sum_products + remaining_stores) / (n + remaining_stores));
            remaining_stores = n;
        }
    }
    return x;
}
```
- Calculate the sum of all products to be distributed.
- Calculate an initial estimate for x by dividing the total number of products by the number of stores.
- Initialize a remaining_stores variable to store the stores that have not been assigned products yet.
- Iterate through each product type:
  - Decrease remaining_stores by the number of stores needed to distribute the current product type with the current value of x.
  - If remaining_stores becomes negative, it means x is too small. Recalculate x using the current remaining_stores and start over with remaining_stores equal to the number of stores.
- Return x when there's no need for further adjustment.


# Maximum Path Quality of a Graph

- slug: maximum-path-quality-of-a-graph
- difficulty: Hard

There is an **undirected** graph with `n` nodes numbered from `0` to `n - 1` (**inclusive**). You are given a **0-indexed** integer array `values` where `values[i]` is the **value** of the `ith` node. You are also given a **0-indexed** 2D integer array `edges`, where each `edges[j] = [uj, vj, timej]` indicates that there is an undirected edge between the nodes `uj` and `vj`, and it takes `timej` seconds to travel between the two nodes. Finally, you are given an integer `maxTime`.

A **valid** **path** in the graph is any path that starts at node `0`, ends at node `0`, and takes **at most** `maxTime` seconds to complete. You may visit the same node multiple times. The **quality** of a valid path is the **sum** of the values of the **unique nodes** visited in the path (each node's value is added **at most once** to the sum).

Return _the **maximum** quality of a valid path_.

**Note:** There are **at most four** edges connected to each node.

**Example 1:**

**Input:** values = \[0,32,10,43\], edges = \[\[0,1,10\],\[1,2,15\],\[0,3,10\]\], maxTime = 49
**Output:** 75
**Explanation:**
One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.
The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.

**Example 2:**

**Input:** values = \[5,10,15,20\], edges = \[\[0,1,10\],\[1,2,10\],\[0,3,10\]\], maxTime = 30
**Output:** 25
**Explanation:**
One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.
The nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.

**Example 3:**

**Input:** values = \[1,2,3,4\], edges = \[\[0,1,10\],\[1,2,11\],\[2,3,12\],\[1,3,13\]\], maxTime = 50
**Output:** 7
**Explanation:**
One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.
The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.

**Constraints:**

*   `n == values.length`
*   `1 <= n <= 1000`
*   `0 <= values[i] <= 108`
*   `0 <= edges.length <= 2000`
*   `edges[j].length == 3`
*   `0 <= uj < vj <= n - 1`
*   `10 <= timej, maxTime <= 100`
*   All the pairs `[uj, vj]` are **unique**.
*   There are **at most four** edges connected to each node.
*   The graph may not be connected.

## A solution in Java

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

public int maxQuality_dfs(int node, int time_left, int[] visited, int[] values, List<List<int[]>> neighbors) {
    int acc = 0;
    for (int[] edge : neighbors.get(node)) {
        int neighbor = edge[0], cost = edge[1];
        if (time_left >= cost && visited[neighbor] == 0) {
            visited[neighbor] = 1;
            acc = Math.max(acc, values[neighbor] + maxQuality_dfs(neighbor, time_left - cost, visited, values, neighbors));
            visited[neighbor] = 0;
        }
    }
    return acc;
}

public int maxQuality(int[] values, int[][] edges, int maxTime) {
    List<List<int[]>> neighbors = new ArrayList<>();
    for (int i = 0; i < values.length; i++) {
        neighbors.add(new ArrayList<>());
    }
    for (int[] edge : edges) {
        neighbors.get(edge[0]).add(new int[]{edge[1], edge[2]});
        neighbors.get(edge[1]).add(new int[]{edge[0], edge[2]});
    }
    int[] visited = new int[values.length];
    return maxQuality_dfs(0, maxTime, visited, values, neighbors);
}
```
The algorithm consists of doing a DFS traversal in the graph, starting from the node 0. It maintains an array `visited` and a `time_left` to store which nodes are visited and the remaining time, respectively. Then, for each neighbor the DFS goes to the neighbor if it hasn't been visited and there's enough time to visit it, updating the visited array and the remaining time. It visits the entire graph and returns the highest possible sum of unique node values that can be visited within `maxTime`. This approach takes advantage of the constraint that there are at most four edges connected to each node which allows the algorithm to be efficient enough to work within the given time limit.

## A solution in C++

```cpp
#include<vector>

int maxQuality_dfs(int node, int time_left, std::vector<int>& visited, std::vector<int>& values, std::vector<std::vector<int>>& neighbors) {
    int acc = 0;
    for (const auto& edge : neighbors[node]) {
        int neighbor = edge[0], cost = edge[1];
        if (time_left >= cost && visited[neighbor] == 0) {
            visited[neighbor] = 1;
            acc = std::max(acc, values[neighbor] + maxQuality_dfs(neighbor, time_left - cost, visited, values, neighbors));
            visited[neighbor] = 0;
        }
    }
    return acc;
}

int maxQuality(std::vector<int>& values, std::vector<std::vector<int>>& edges, int maxTime) {
    std::vector<std::vector<int>> neighbors(values.size());
    for (const auto& edge : edges) {
        neighbors[edge[0]].push_back({edge[1], edge[2]});
        neighbors[edge[1]].push_back({edge[0], edge[2]});
    }
    std::vector<int> visited(values.size(), 0);
    return maxQuality_dfs(0, maxTime, visited, values, neighbors);
}
```
The algorithm consists of doing a DFS traversal in the graph, starting from the node 0. It maintains an array `visited` and a `time_left` to store which nodes are visited and the remaining time, respectively. Then, for each neighbor the DFS goes to the neighbor if it hasn't been visited and there's enough time to visit it, updating the visited array and the remaining time. It visits the entire graph and returns the highest possible sum of unique node values that can be visited within `maxTime`. This approach takes advantage of the constraint that there are at most four edges connected to each node which allows the algorithm to be efficient enough to work within the given time limit.

## A solution in Python

```python
from collections import defaultdict

def maxQuality_dfs(node, time_left, visited, values, neighbors):
    acc = 0
    for neighbor, cost in neighbors[node]:
        if time_left >= cost and not visited[neighbor]:
            visited[neighbor] = 1
            acc = max(acc, values[neighbor] + maxQuality_dfs(neighbor, time_left - cost, visited, values, neighbors))
            visited[neighbor] = 0
    return acc

def maxQuality(values, edges, maxTime):
    neighbors = defaultdict(list)
    for u, v, cost in edges:
        neighbors[u].append((v, cost))
        neighbors[v].append((u, cost))
    visited = [0] * len(values)
    return maxQuality_dfs(0, maxTime, visited, values, neighbors)
```
The algorithm consists of doing a DFS traversal in the graph, starting from the node 0. It maintains an array `visited` and a `time_left` to store which nodes are visited and the remaining time, respectively. Then, for each neighbor the DFS goes to the neighbor if it hasn't been visited and there's enough time to visit it, updating the visited array and the remaining time. It visits the entire graph and returns the highest possible sum of unique node values that can be visited within `maxTime`. This approach takes advantage of the constraint that there are at most four edges connected to each node which allows the algorithm to be efficient enough to work within the given time limit.

## A solution in Javascript

```javascript
function maxQuality_dfs(node, time_left, visited, values, neighbors) {
  let acc = 0;
  for (let edge of neighbors[node]) {
    let neighbor = edge[0], cost = edge[1];
    if (time_left >= cost && visited[neighbor] === 0) {
      visited[neighbor] = 1;
      acc = Math.max(acc, values[neighbor] + maxQuality_dfs(neighbor, time_left - cost, visited, values, neighbors));
      visited[neighbor] = 0;
    }
  }
  return acc;
}

function maxQuality(values, edges, maxTime) {
  let neighbors = new Array(values.length).fill(null).map(() => []);
  for (let edge of edges) {
    neighbors[edge[0]].push([edge[1], edge[2]]);
    neighbors[edge[1]].push([edge[0], edge[2]]);
  }
  let visited = new Array(values.length).fill(0);
  return maxQuality_dfs(0, maxTime, visited, values, neighbors);
}
```
The algorithm consists of doing a DFS traversal in the graph, starting from the node 0. It maintains an array `visited` and a `time_left` to store which nodes are visited and the remaining time, respectively. Then, for each neighbor the DFS goes to the neighbor if it hasn't been visited and there's enough time to visit it, updating the visited array and the remaining time. It visits the entire graph and returns the highest possible sum of unique node values that can be visited within `maxTime`. This approach takes advantage of the constraint that there are at most four edges connected to each node which allows the algorithm to be efficient enough to work within the given time limit.


# Number of Equal Count Substrings

- slug: number-of-equal-count-substrings
- difficulty: Medium

You are given a **0-indexed** string `s` consisting of only lowercase English letters, and an integer `count`. A **substring** of `s` is said to be an **equal count substring** if, for each **unique** letter in the substring, it appears exactly `count` times in the substring.

Return _the number of **equal count substrings** in_ `s`.

A **substring** is a contiguous non-empty sequence of characters within a string.

**Example 1:**

**Input:** s =  "aaabcbbcc ", count = 3
**Output:** 3
**Explanation:**
The substring that starts at index 0 and ends at index 2 is  "aaa ".
The letter 'a' in the substring appears exactly 3 times.
The substring that starts at index 3 and ends at index 8 is  "bcbbcc ".
The letters 'b' and 'c' in the substring appear exactly 3 times.
The substring that starts at index 0 and ends at index 8 is  "aaabcbbcc ".
The letters 'a', 'b', and 'c' in the substring appear exactly 3 times.

**Example 2:**

**Input:** s =  "abcd ", count = 2
**Output:** 0
**Explanation:**
The number of times each letter appears in s is less than count.
Therefore, no substrings in s are equal count substrings, so return 0.

**Example 3:**

**Input:** s =  "a ", count = 5
**Output:** 0
**Explanation:**
The number of times each letter appears in s is less than count.
Therefore, no substrings in s are equal count substrings, so return 0

**Constraints:**

*   `1 <= s.length <= 3 * 104`
*   `1 <= count <= 3 * 104`
*   `s` consists only of lowercase English letters.

## A solution in Java

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

    for (int r = 1; r < m; r++) {
        for (int c = 0; c < n; c++) {
            int score = points[r][c];
            for (int c_prev = 0; c_prev < n; c_prev++) {
                dp[r][c] = Math.max(dp[r][c], dp[r - 1][c_prev] + score - Math.abs(c - c_prev));
            }
        }
    }

    int max = dp[m - 1][0];
    for (int i = 1; i < n; i++) {
        max = Math.max(max, dp[m - 1][i]);
    }
    return max;
}
```
The algorithm uses dynamic programming. The `dp` array has the same dimensions as the input matrix, `m` rows and `n` columns. The value `dp[r][c]` corresponds to the maximum score achievable when picking the cell at row `r` and column `c`.

At the start, the first row of `dp` is initialized with the values of the corresponding first row of the input `points` matrix because there's no previous row.

For each subsequent row `r`, iterate through all its columns `c`, and calculate the maximum score of picking the cell at (r, c) by iterating through all possible previous column positions `c_prev` and using the following formula:

`dp[r][c] = max(dp[r - 1][c_prev] + current score - abs(c - c_prev))`

Where `current score = points[r][c]`. After filling the entire `dp` array, the maximum score achievable is the maximum value in the last row of the `dp` array.

## A solution in C++

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

int maxScore(std::vector<std::vector<int>>& points) {
    int m = points.size(), n = points[0].size();
    std::vector<std::vector<int>> dp(m, std::vector<int>(n));
    dp[0] = points[0];

    for (int r = 1; r < m; r++) {
        for (int c = 0; c < n; c++) {
            int score = points[r][c];
            for (int c_prev = 0; c_prev < n; c_prev++) {
                dp[r][c] = std::max(dp[r][c], dp[r - 1][c_prev] + score - abs(c - c_prev));
            }
        }
    }

    return *std::max_element(dp[m - 1].begin(), dp[m - 1].end());
}
```
The algorithm uses dynamic programming. The `dp` array has the same dimensions as the input matrix, `m` rows and `n` columns. The value `dp[r][c]` corresponds to the maximum score achievable when picking the cell at row `r` and column `c`.

At the start, the first row of `dp` is initialized with the values of the corresponding first row of the input `points` matrix because there's no previous row.

For each subsequent row `r`, iterate through all its columns `c`, and calculate the maximum score of picking the cell at (r, c) by iterating through all possible previous column positions `c_prev` and using the following formula:

`dp[r][c] = max(dp[r - 1][c_prev] + current score - abs(c - c_prev))`

Where `current score = points[r][c]`. After filling the entire `dp` array, the maximum score achievable is the maximum value in the last row of the `dp` array.

## A solution in Python

```python
def maxScore(points):
    m, n = len(points), len(points[0])
    dp = [points[0]]

    for r in range(1, m):
        dp.append([0] * n)
        for c in range(n):
            score = points[r][c]
            dp[r][c] = max(dp[r - 1][c_prev] + score - abs(c - c_prev) for c_prev in range(n))

    return max(dp[m - 1])
```
The algorithm uses dynamic programming. The `dp` array has the same dimensions as the input matrix, `m` rows and `n` columns. The value `dp[r][c]` corresponds to the maximum score achievable when picking the cell at row `r` and column `c`.

At the start, the first row of `dp` is initialized with the values of the corresponding first row of the input `points` matrix because there's no previous row.

For each subsequent row `r`, iterate through all its columns `c`, and calculate the maximum score of picking the cell at (r, c) by iterating through all possible previous column positions `c_prev` and using the following formula:

`dp[r][c] = max(dp[r - 1][c_prev] + current score - abs(c - c_prev))`

Where `current score = points[r][c]`. After filling the entire `dp` array, the maximum score achievable is the maximum value in the last row of the `dp` array.

## A solution in Javascript

```javascript
function maxScore(points) {
    let m = points.length, n = points[0].length;
    let dp = [points[0]];

    for (let r = 1; r < m; r++) {
        dp.push(Array(n).fill(0));
        for (let c = 0; c < n; c++) {
            let score = points[r][c];
            for (let c_prev = 0; c_prev < n; c_prev++) {
                dp[r][c] = Math.max(dp[r][c], dp[r - 1][c_prev] + score - Math.abs(c - c_prev));
            }
        }
    }

    return Math.max(...dp[m - 1]);
}
```
The algorithm uses dynamic programming. The `dp` array has the same dimensions as the input matrix, `m` rows and `n` columns. The value `dp[r][c]` corresponds to the maximum score achievable when picking the cell at row `r` and column `c`.

At the start, the first row of `dp` is initialized with the values of the corresponding first row of the input `points` matrix because there's no previous row.

For each subsequent row `r`, iterate through all its columns `c`, and calculate the maximum score of picking the cell at (r, c) by iterating through all possible previous column positions `c_prev` and using the following formula:

`dp[r][c] = max(dp[r - 1][c_prev] + current score - abs(c - c_prev))`

Where `current score = points[r][c]`. After filling the entire `dp` array, the maximum score achievable is the maximum value in the last row of the `dp` array.


# Check Whether Two Strings are Almost Equivalent

- slug: check-whether-two-strings-are-almost-equivalent
- difficulty: Easy

Two strings `word1` and `word2` are considered **almost equivalent** if the differences between the frequencies of each letter from `'a'` to `'z'` between `word1` and `word2` is **at most** `3`.

Given two strings `word1` and `word2`, each of length `n`, return `true` _if_ `word1` _and_ `word2` _are **almost equivalent**, or_ `false` _otherwise_.

The **frequency** of a letter `x` is the number of times it occurs in the string.

**Example 1:**

**Input:** word1 =  "aaaa ", word2 =  "bccb "
**Output:** false
**Explanation:** There are 4 'a's in  "aaaa " but 0 'a's in  "bccb ".
The difference is 4, which is more than the allowed 3.

**Example 2:**

**Input:** word1 =  "abcdeef ", word2 =  "abaaacc "
**Output:** true
**Explanation:** The differences between the frequencies of each letter in word1 and word2 are at most 3:
- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.
- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.
- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.
- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.
- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.
- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1.

**Example 3:**

**Input:** word1 =  "cccddabba ", word2 =  "babababab "
**Output:** true
**Explanation:** The differences between the frequencies of each letter in word1 and word2 are at most 3:
- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.
- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.
- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.
- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2.

**Constraints:**

*   `n == word1.length == word2.length`
*   `1 <= n <= 100`
*   `word1` and `word2` consist only of lowercase English letters.

## A solution in Java

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

public class Solution {
    private static final int M = 17;
    private final List<List<Integer>> tr = new ArrayList<>();

    public int[] maxGeneticDifference(int[] parents, int[][] queries) {
        int n = parents.length;
        List<List<Integer>> edges = new ArrayList<>(n);
        for (int i = 0; i < n; ++i) {
            edges.add(new ArrayList<>());
        }
        int root = -1;
        for (int i = 0; i < n; ++i) {
            if (parents[i] == -1) {
                root = i;
            } else {
                edges.get(parents[i]).add(i);
            }
        }

        tr.add(new ArrayList<>(2));
        tr.get(0).add(0);
        tr.get(0).add(0);
        int[] ans = new int[n];
        dfs(root, 0, edges, ans);

        int[] result = new int[queries.length];
        for (int i = 0; i < queries.length; ++i) {
            result[i] = ans[queries[i][0]] ^ queries[i][1];
        }
        return result;
    }

    private void insert(int x) {
        int u = 0;
        for (int i = M - 1; i >= 0; --i) {
            int v = (x >> i) & 1;
            if (tr.get(u).get(v) == 0) {
                tr.get(u).set(v, tr.size());
                List<Integer> newRow = new ArrayList<>(2);
                newRow.add(0);
                newRow.add(0);
                tr.add(newRow);
            }
            u = tr.get(u).get(v);
        }
    }

    private int query(int x, int y) {
        int u = 0, ans = 0;
        for (int i = M - 1; i >= 0; --i) {
            int v = ((x >> i) & 1) ^ 1;
            if (tr.get(u).get(v) == 0) v ^= 1;
            ans |= (y = (y << 1) | v);
            u = tr.get(u).get(v);
        }
        return ans;
    }

    private void dfs(int u, int tree, List<List<Integer>> g, int[] ans) {
        insert(tree ^= u);
        ans[u] = query(tree);
        for (int v : g.get(u)) {
            dfs(v, tree, g, ans);
        }
    }
}
```
1. Initialize a trie as the data structure for holding our bitwise XOR results.
2. Define helper functions `insert`, `query`, and `dfs`.
3. In `insert`, add numbers to the trie. Each bit of the number represents the node connected to the root node.
4. In `query`, find the maximum genetic difference in the trie given a genetic value.
5. In `dfs`, traverse the tree and perform the `query` function for every node while inserting its genetic value.
6. First, find the root and initialize the graph of nodes using the given `parents` array.
7. Call the `dfs` function for the root node to populate the trie.
8. Lastly, iterate through `queries` and XOR the gene value with the result from the trie to find the maximum genetic difference.

## A solution in C++

```cpp
#include <vector>
#include <bitset>

using namespace std;

const int M = 17;
vector<int> tr[1 << M];

void insert(int x) {
    int u = 0;
    for (int i = M - 1; i >= 0; --i) {
        int v = (x >> i) & 1;
        if (!tr[u][v]) tr[u][v] = tr.size(), tr.emplace_back(2);
        u = tr[u][v];
    }
}

int query(int x, int y = 0) {
    int u = 0, ans = 0;
    for (int i = M - 1; i >= 0; --i) {
        int v = ((x >> i) & 1) ^ 1;
        if (!tr[u][v]) v ^= 1;
        ans |= (y = (y << 1) | v);
        u = tr[u][v];
    }
    return ans;
}

void dfs(int u, int tree = 0, vector<vector<int>>& g = {}, vector<int>& ans = {}) {
    insert(tree ^= u);
    ans[u] = query(tree);
    for (int v : g[u]) dfs(v, tree, g, ans);
}

vector<int> maxGeneticDifference(vector<int>& parents, vector<vector<int>>& queries) {
    int n = parents.size();
    vector<vector<int>> edges(n);
    int root;
    for (int i = 0; i < n; ++i) {
        if (parents[i] == -1) {
            root = i;
        } else {
            edges[parents[i]].push_back(i);
        }
    }
    vector<int> ans(n);
    dfs(root, 0, edges, ans);
    vector<int> result(queries.size());
    for (int i = 0; i < queries.size(); ++i) {
        result[i] = ans[queries[i][0]] ^ queries[i][1];
    }
    return result;
}
```
1. Initialize a trie as the data structure for holding our bitwise XOR results.
2. Define helper functions `insert`, `query`, and `dfs`.
3. In `insert`, add numbers to the trie. Each bit of the number represents the node connected to the root node.
4. In `query`, find the maximum genetic difference in the trie given a genetic value.
5. In `dfs`, traverse the tree and perform the `query` function for every node while inserting its genetic value.
6. First, find the root and initialize the graph of nodes using the given `parents` array.
7. Call the `dfs` function for the root node to populate the trie.
8. Lastly, iterate through `queries` and XOR the gene value with the result from the trie to find the maximum genetic difference.

## A solution in Python

```python
import collections

def maxGeneticDifference(parents, queries):
    M = 17
    tr = [0, 0]

    def insert(x):
        nonlocal tr
        u = 0
        for i in range(M - 1, -1, -1):
            v = (x >> i) & 1
            if not tr[u][v]:
                tr[u][v] = len(tr)
                tr.append([0, 0])
            u = tr[u][v]

    def query(x, y=0):
        u = 0
        ans = 0
        for i in range(M - 1, -1, -1):
            v = ((x >> i) & 1) ^ 1
            if not tr[u][v]:
                v ^= 1
            ans |= (y := (y << 1) | v)
            u = tr[u][v]
        return ans

    def dfs(u, tree=0, g=collections.defaultdict(list), ans=None):
        nonlocal tr
        insert(tree := tree ^ u)
        ans[u] = query(tree)
        for v in g[u]:
            dfs(v, tree, g, ans)

    n = len(parents)
    root = -1
    graph = collections.defaultdict(list)
    for i, parent in enumerate(parents):
        if parent != -1:
            graph[parent].append(i)
        else:
            root = i

    ans = [0] * n
    dfs(root, 0, graph, ans)
    result = [ans[node] ^ val for node, val in queries]
    return result
```
1. Initialize a trie as the data structure for holding our bitwise XOR results.
2. Define helper functions `insert`, `query`, and `dfs`.
3. In `insert`, add numbers to the trie. Each bit of the number represents the node connected to the root node.
4. In `query`, find the maximum genetic difference in the trie given a genetic value.
5. In `dfs`, traverse the tree and perform the `query` function for every node while inserting its genetic value.
6. First, find the root and initialize the graph of nodes using the given `parents` array.
7. Call the `dfs` function for the root node to populate the trie.
8. Lastly, iterate through `queries` and XOR the gene value with the result from the trie to find the maximum genetic difference.

## A solution in Javascript

```javascript
const M = 17;
const tr = [[0, 0]];

function insert(x) {
    let u = 0;
    for (let i = M - 1; i >= 0; --i) {
        const v = (x >> i) & 1;
        if (!tr[u][v]) {
            const idx = tr.length;
            tr[u][v] = idx;
            tr.push([0, 0]);
        }
        u = tr[u][v];
    }
}

function query(x, y = 0) {
    let u = 0;
    let ans = 0;
    for (let i = M - 1; i >= 0; --i) {
        let v = ((x >> i) & 1) ^ 1;
        if (!tr[u][v]) v ^= 1;
        ans |= (y = (y << 1) | v);
        u = tr[u][v];
    }
    return ans;
}

function dfs(u, tree = 0, g = [], ans = []) {
    insert(tree ^= u);
    ans[u] = query(tree);
    for (const v of g[u]) {
        dfs(v, tree, g, ans);
    }
}

function maxGeneticDifference(parents, queries) {
    const n = parents.length;
    const edges = Array.from({length: n}, () => []);
    let root = -1;
    for (let i = 0; i < n; ++i) {
        if (parents[i] === -1) {
            root = i;
        } else {
            edges[parents[i]].push(i);
        }
    }

    const ans = Array(n).fill(0);
    dfs(root, 0, edges, ans);

    const result = queries.map(([node, val]) => ans[node] ^ val);
    return result;
}
```
1. Initialize a trie as the data structure for holding our bitwise XOR results.
2. Define helper functions `insert`, `query`, and `dfs`.
3. In `insert`, add numbers to the trie. Each bit of the number represents the node connected to the root node.
4. In `query`, find the maximum genetic difference in the trie given a genetic value.
5. In `dfs`, traverse the tree and perform the `query` function for every node while inserting its genetic value.
6. First, find the root and initialize the graph of nodes using the given `parents` array.
7. Call the `dfs` function for the root node to populate the trie.
8. Lastly, iterate through `queries` and XOR the gene value with the result from the trie to find the maximum genetic difference.


# Walking Robot Simulation II

- slug: walking-robot-simulation-ii
- difficulty: Medium

A `width x height` grid is on an XY-plane with the **bottom-left** cell at `(0, 0)` and the **top-right** cell at `(width - 1, height - 1)`. The grid is aligned with the four cardinal directions ( `"North "`, `"East "`, `"South "`, and `"West "`). A robot is **initially** at cell `(0, 0)` facing direction `"East "`.

The robot can be instructed to move for a specific number of **steps**. For each step, it does the following.

1.  Attempts to move **forward one** cell in the direction it is facing.
2.  If the cell the robot is **moving to** is **out of bounds**, the robot instead **turns** 90 degrees **counterclockwise** and retries the step.

After the robot finishes moving the number of steps required, it stops and awaits the next instruction.

Implement the `Robot` class:

*   `Robot(int width, int height)` Initializes the `width x height` grid with the robot at `(0, 0)` facing `"East "`.
*   `void step(int num)` Instructs the robot to move forward `num` steps.
*   `int[] getPos()` Returns the current cell the robot is at, as an array of length 2, `[x, y]`.
*   `String getDir()` Returns the current direction of the robot, `"North "`, `"East "`, `"South "`, or `"West "`.

**Example 1:**

**Input**
\[ "Robot ",  "step ",  "step ",  "getPos ",  "getDir ",  "step ",  "step ",  "step ",  "getPos ",  "getDir "\]
\[\[6, 3\], \[2\], \[2\], \[\], \[\], \[2\], \[1\], \[4\], \[\], \[\]\]
**Output**
\[null, null, null, \[4, 0\],  "East ", null, null, null, \[1, 2\],  "West "\]

**Explanation**
Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.
robot.step(2);  // It moves two steps East to (2, 0), and faces East.
robot.step(2);  // It moves two steps East to (4, 0), and faces East.
robot.getPos(); // return \[4, 0\]
robot.getDir(); // return  "East "
robot.step(2);  // It moves one step East to (5, 0), and faces East.
                // Moving the next step East would be out of bounds, so it turns and faces North.
                // Then, it moves one step North to (5, 1), and faces North.
robot.step(1);  // It moves one step North to (5, 2), and faces **North** (not West).
robot.step(4);  // Moving the next step North would be out of bounds, so it turns and faces West.
                // Then, it moves four steps West to (1, 2), and faces West.
robot.getPos(); // return \[1, 2\]
robot.getDir(); // return  "West "

**Constraints:**

*   `2 <= width, height <= 100`
*   `1 <= num <= 105`
*   At most `104` calls **in total** will be made to `step`, `getPos`, and `getDir`.

## A solution in Java

```java
public class Robot {
    int width, height, x, y, dir;
    int[] dx = {1, 0, -1, 0};
    int[] dy = {0, 1, 0, -1};

    public Robot(int width, int height) {
        this.width = width;
        this.height = height;
        x = 0;
        y = 0;
        dir = 0;
    }

    public void step(int num) {
        while (num-- > 0) {
            int nx = x + dx[dir];
            int ny = y + dy[dir];
            if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
                x = nx;
                y = ny;
            } else {
                dir = (dir + 1) % 4;
                num++; // Retry the step
            }
        }
    }

    public int[] getPos() {
        return new int[]{x, y};
    }

    public String getDir() {
        switch(dir) {
            case 0: return "East";
            case 1: return "North";
            case 2: return "West";
            case 3: return "South";
        }
        return "";
    }
}
```
The Robot class consists of a constructor and three methods - step, getPos, and getDir. The constructor initializes the width and height of the grid, while also setting the initial position `(0, 0)` and direction (East). For the step method, it takes the specified number of steps and attempts to move. However, if the robot is about to move out of bounds, it rotates 90 degrees counterclockwise and retries the same step. The getPos method returns the current position of the robot as an `[x, y]` array, and the getDir method returns the current direction (North, East, South, West) as a string.

The algorithm uses an array `dx` and `dy` to represent the x and y direction changes corresponding to the four cardinal directions. The algorithm also uses a state variable `dir` to track the current direction of the robot. Using a loop to decrease the step number from the input value, the algorithm will then attempt to move the robot in the current direction by adding the corresponding `dx` and `dy` values to the current position. If the new position is out of bounds, the robot will rotate counterclockwise by incrementing the `dir` state by 1 modulo 4 (the number of directions). If the new position is in bounds, the robot's position will be updated.

## A solution in C++

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

class Robot {
    int width, height, x, y, dir;
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1};
public:
    Robot(int width, int height): width(width), height(height), x(0), y(0), dir(0) {}

    void step(int num) {
        while (num-- > 0) {
            int nx = x + dx[dir];
            int ny = y + dy[dir];
            if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
                x = nx;
                y = ny;
            } else {
                dir = (dir + 1) % 4;
                num++; // Retry the step
            }
        }
    }

    vector<int> getPos() {
        return {x, y};
    }

    string getDir() {
        switch(dir) {
            case 0: return "East";
            case 1: return "North";
            case 2: return "West";
            case 3: return "South";
        }
        return "";
    }
};
```
The Robot class consists of a constructor and three methods - step, getPos, and getDir. The constructor initializes the width and height of the grid, while also setting the initial position `(0, 0)` and direction (East). For the step method, it takes the specified number of steps and attempts to move. However, if the robot is about to move out of bounds, it rotates 90 degrees counterclockwise and retries the same step. The getPos method returns the current position of the robot as an `[x, y]` array, and the getDir method returns the current direction (North, East, South, West) as a string.

The algorithm uses an array `dx` and `dy` to represent the x and y direction changes corresponding to the four cardinal directions. The algorithm also uses a state variable `dir` to track the current direction of the robot. Using a loop to decrease the step number from the input value, the algorithm will then attempt to move the robot in the current direction by adding the corresponding `dx` and `dy` values to the current position. If the new position is out of bounds, the robot will rotate counterclockwise by incrementing the `dir` state by 1 modulo 4 (the number of directions). If the new position is in bounds, the robot's position will be updated.

## A solution in Python

```python
class Robot:

    def __init__(self, width: int, height: int):
        self.width = width
        self.height = height
        self.x, self.y = 0, 0
        self.dir = 0
        self.dx = [1, 0, -1, 0]
        self.dy = [0, 1, 0, -1]

    def step(self, num: int):
        while num > 0:
            nx, ny = self.x + self.dx[self.dir], self.y + self.dy[self.dir]
            if 0 <= nx < self.width and 0 <= ny < self.height:
                self.x, self.y = nx, ny
            else:
                self.dir = (self.dir + 1) % 4
                num += 1  # Retry the step
            num -= 1

    def getPos(self) -> list[int]:
        return [self.x, self.y]

    def getDir(self) -> str:
        return ["East", "North", "West", "South"][self.dir]
```
The Robot class consists of a constructor and three methods - step, getPos, and getDir. The constructor initializes the width and height of the grid, while also setting the initial position `(0, 0)` and direction (East). For the step method, it takes the specified number of steps and attempts to move. However, if the robot is about to move out of bounds, it rotates 90 degrees counterclockwise and retries the same step. The getPos method returns the current position of the robot as an `[x, y]` array, and the getDir method returns the current direction (North, East, South, West) as a string.

The algorithm uses an array `dx` and `dy` to represent the x and y direction changes corresponding to the four cardinal directions. The algorithm also uses a state variable `dir` to track the current direction of the robot. Using a loop to decrease the step number from the input value, the algorithm will then attempt to move the robot in the current direction by adding the corresponding `dx` and `dy` values to the current position. If the new position is out of bounds, the robot will rotate counterclockwise by incrementing the `dir` state by 1 modulo 4 (the number of directions). If the new position is in bounds, the robot's position will be updated.

## A solution in Javascript

```javascript
class Robot {
    constructor(width, height) {
        this.width = width;
        this.height = height;
        this.x = 0;
        this.y = 0;
        this.dir = 0;
        this.dx = [1, 0, -1, 0];
        this.dy = [0, 1, 0, -1];
    }

    step(num) {
        while (num-- > 0) {
            const nx = this.x + this.dx[this.dir];
            const ny = this.y + this.dy[this.dir];
            if (nx >= 0 && nx < this.width && ny >= 0 && ny < this.height) {
                this.x = nx;
                this.y = ny;
            } else {
                this.dir = (this.dir + 1) % 4;
                num++; // Retry the step
            }
        }
    }

    getPos() {
        return [this.x, this.y];
    }

    getDir() {
        const directions = ["East", "North", "West", "South"];
        return directions[this.dir];
    }
}
```
The Robot class consists of a constructor and three methods - step, getPos, and getDir. The constructor initializes the width and height of the grid, while also setting the initial position `(0, 0)` and direction (East). For the step method, it takes the specified number of steps and attempts to move. However, if the robot is about to move out of bounds, it rotates 90 degrees counterclockwise and retries the same step. The getPos method returns the current position of the robot as an `[x, y]` array, and the getDir method returns the current direction (North, East, South, West) as a string.

The algorithm uses an array `dx` and `dy` to represent the x and y direction changes corresponding to the four cardinal directions. The algorithm also uses a state variable `dir` to track the current direction of the robot. Using a loop to decrease the step number from the input value, the algorithm will then attempt to move the robot in the current direction by adding the corresponding `dx` and `dy` values to the current position. If the new position is out of bounds, the robot will rotate counterclockwise by incrementing the `dir` state by 1 modulo 4 (the number of directions). If the new position is in bounds, the robot's position will be updated.