# Largest Substring Between Two Equal Characters

- slug: largest-substring-between-two-equal-characters
- difficulty: Easy

Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`.

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

**Example 1:**

**Input:** s =  "aa "
**Output:** 0
**Explanation:** The optimal substring here is an empty substring between the two `'a's`.

**Example 2:**

**Input:** s =  "abca "
**Output:** 2
**Explanation:** The optimal substring here is  "bc ".

**Example 3:**

**Input:** s =  "cbzxy "
**Output:** -1
**Explanation:** There are no characters that appear twice in s.

**Constraints:**

*   `1 <= s.length <= 300`
*   `s` contains only lowercase English letters.

## A solution in Java

```java
public int maxLengthBetweenEqualCharacters(String s) {
    int result = -1;
    HashMap<Character, Integer> char_map = new HashMap<>();

    for (int i = 0; i < s.length(); ++i) {
        if (!char_map.containsKey(s.charAt(i))) {
            char_map.put(s.charAt(i), i);
        } else {
            result = Math.max(result, i - char_map.get(s.charAt(i)) - 1);
        }
    }
    return result;
}
```
The algorithm uses a hash map to store the index of the first occurrence of each character in the string. It then iterates through the string, and for each character, checks if it's present in the hash map. If it's not, the character is added to the hash map with its index. If it is present, the length of the substring between the two occurrences of the character is calculated as (current index - stored index - 1). The result is updated as the maximum length between equal characters found so far.

## A solution in C++

```cpp
int maxLengthBetweenEqualCharacters(std::string s) {
    int result = -1;
    std::unordered_map<char, int> char_map;

    for (int i = 0; i < s.length(); ++i) {
        if (char_map.find(s[i]) == char_map.end()) {
            char_map[s[i]] = i;
        } else {
            result = std::max(result, i - char_map[s[i]] - 1);
        }
    }
    return result;
}
```
The algorithm uses a hash map to store the index of the first occurrence of each character in the string. It then iterates through the string, and for each character, checks if it's present in the hash map. If it's not, the character is added to the hash map with its index. If it is present, the length of the substring between the two occurrences of the character is calculated as (current index - stored index - 1). The result is updated as the maximum length between equal characters found so far.

## A solution in Python

```python
def maxLengthBetweenEqualCharacters(s: str) -> int:
    result = -1
    char_map = {}

    for i, c in enumerate(s):
        if c not in char_map:
            char_map[c] = i
        else:
            result = max(result, i - char_map[c] - 1)

    return result
```
The algorithm uses a hash map to store the index of the first occurrence of each character in the string. It then iterates through the string, and for each character, checks if it's present in the hash map. If it's not, the character is added to the hash map with its index. If it is present, the length of the substring between the two occurrences of the character is calculated as (current index - stored index - 1). The result is updated as the maximum length between equal characters found so far.

## A solution in Javascript

```javascript
function maxLengthBetweenEqualCharacters(s) {
    let result = -1;
    let char_map = {};

    for (let i = 0; i < s.length; ++i) {
        let c = s.charAt(i);
        if (!char_map.hasOwnProperty(c)) {
            char_map[c] = i;
        } else {
            result = Math.max(result, i - char_map[c] - 1);
        }
    }
    return result;
}
```
The algorithm uses a hash map to store the index of the first occurrence of each character in the string. It then iterates through the string, and for each character, checks if it's present in the hash map. If it's not, the character is added to the hash map with its index. If it is present, the length of the substring between the two occurrences of the character is calculated as (current index - stored index - 1). The result is updated as the maximum length between equal characters found so far.


# Lexicographically Smallest String After Applying Operations

- slug: lexicographically-smallest-string-after-applying-operations
- difficulty: Medium

You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`.

You can apply either of the following two operations any number of times and in any order on `s`:

*   Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`.
*   Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`.

Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`.

A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`.

**Example 1:**

**Input:** s =  "5525 ", a = 9, b = 2
**Output:**  "2050 "
**Explanation:** We can apply the following operations:
Start:   "5525 "
Rotate:  "2555 "
Add:     "2454 "
Add:     "2353 "
Rotate:  "5323 "
Add:     "5222 "
Add:     "5121 "
Rotate:  "2151 "
Add:     "2050 "
There is no way to obtain a string that is lexicographically smaller then  "2050 ".

**Example 2:**

**Input:** s =  "74 ", a = 5, b = 1
**Output:**  "24 "
**Explanation:** We can apply the following operations:
Start:   "74 "
Rotate:  "47 "
Add:     "42 "
Rotate:  "24 "
There is no way to obtain a string that is lexicographically smaller then  "24 ".

**Example 3:**

**Input:** s =  "0011 ", a = 4, b = 2
**Output:**  "0011 "
**Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than  "0011 ".

**Constraints:**

*   `2 <= s.length <= 100`
*   `s.length` is even.
*   `s` consists of digits from `0` to `9` only.
*   `1 <= a <= 9`
*   `1 <= b <= s.length - 1`

## A solution in Java

```java
public String findLexSmallestString(String s, int a, int b) {
    int n = s.length();
    String minStr = s;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 10; j++) {
            String rotatedStr = rotateString(s, b);
            String tempStr = addOdd(rotatedStr, a);
            minStr = minStr.compareTo(tempStr) < 0 ? minStr : tempStr;
            s = rotatedStr;
        }
        s = addAtIndex(s, a, n - i - 1);
    }
    return minStr;
}

private String rotateString(String s, int k) {
    k %= s.length();
    return s.substring(s.length() - k) + s.substring(0, s.length() - k);
}

private String addAtIndex(String s, int a, int index) {
    char[] arr = s.toCharArray();
    arr[index] = (char) ((arr[index] - '0' + a) % 10 + '0');
    return new String(arr);
}

private String addOdd(String s, int a) {
    StringBuilder sb = new StringBuilder(s);
    for (int i = 1; i < s.length(); i += 2) {
        sb.setCharAt(i, (char) ((s.charAt(i) - '0' + a) % 10 + '0'));
    }
    return sb.toString();
}
```
1. Iterate for each position of the string.
2. In the inner loop, iterate 10 times to cover all possible sums of 'a' on odd positions.
3. In each iteration, apply the 'rotate' operation to the string, then apply the 'addOdd' operation to the string, and check if the resulting string is smaller than the current smallest string.
4. Outside the inner loop, apply the 'addAtIndex' operation to the original string to update the last even position by adding 'a' to it.
5. At the end of the outer loop, return the smallest string obtained.

The time complexity of this approach is O(n * 10 * (n + 10)), where n is the length of the input string s.

## A solution in C++

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

std::string findLexSmallestString(std::string s, int a, int b) {
    std::string smallest = s;
    int len = s.length();
    std::string rotated;

    for (int i = 0; i < len; i += 2) {
        for (int j = 0; j < 10; ++j) {
            rotated = s.substr(len - b) + s.substr(0, len - b);
            std::string tmp = rotated;

            for (int k = 1; k < len; k += 2)
                tmp[k] = '0' + (tmp[k] - '0' + a) % 10;

            smallest = std::min(smallest, tmp);
            s = rotated;
        }
        s[len - i - 1] = '0' + (s[len - i - 1] - '0' + a) % 10;
    }

    return smallest;
}
```
1. Iterate for each position of the string.
2. In the inner loop, iterate 10 times to cover all possible sums of 'a' on odd positions.
3. In each iteration, apply the 'rotate' operation to the string, then apply the 'addOdd' operation to the string, and check if the resulting string is smaller than the current smallest string.
4. Outside the inner loop, apply the 'addAtIndex' operation to the original string to update the last even position by adding 'a' to it.
5. At the end of the outer loop, return the smallest string obtained.

The time complexity of this approach is O(n * 10 * (n + 10)), where n is the length of the input string s.

## A solution in Python

```python
def findLexSmallestString(s: str, a: int, b: int) -> str:
    def add_odd(s: str, a: int) -> str:
        return ''.join([str((int(ch) + a) % 10) if idx % 2 else ch for idx, ch in enumerate(s)])

    def rotate(s: str, k: int) -> str:
        k %= len(s)
        return s[-k:] + s[:-k]

    smallest = s
    for _ in range(len(s)):
        for _ in range(10):
            rotated = rotate(s, b)
            temp = add_odd(rotated, a)
            smallest = min(smallest, temp)
            s = rotated
        s = add_odd(s, a)
    return smallest
```
1. Iterate for each position of the string.
2. In the inner loop, iterate 10 times to cover all possible sums of 'a' on odd positions.
3. In each iteration, apply the 'rotate' operation to the string, then apply the 'addOdd' operation to the string, and check if the resulting string is smaller than the current smallest string.
4. Outside the inner loop, apply the 'addAtIndex' operation to the original string to update the last even position by adding 'a' to it.
5. At the end of the outer loop, return the smallest string obtained.

The time complexity of this approach is O(n * 10 * (n + 10)), where n is the length of the input string s.

## A solution in Javascript

```javascript
function findLexSmallestString(s, a, b) {
    function rotate(s, k) {
        k %= s.length;
        return s.slice(s.length - k) + s.slice(0, s.length - k);
    }

    function addAtIndex(s, a, index) {
        const arr = [...s];
        arr[index] = (arr[index] - '0' + a) % 10 + '0';
        return arr.join('');
    }

    function addOdd(s, a) {
        return s.split('').map((ch, idx) => idx % 2 ? (parseInt(ch) + a) % 10 : ch).join('');
    }

    let smallest = s;
    for (let i = 0; i < s.length; i++) {
        for (let j = 0; j < 10; j++) {
            const rotated = rotate(s, b);
            const temp = addOdd(rotated, a);
            smallest = smallest < temp ? smallest : temp;
            s = rotated;
        }
        s = addAtIndex(s, a, s.length - i - 1);
    }
    return smallest;
}
```
1. Iterate for each position of the string.
2. In the inner loop, iterate 10 times to cover all possible sums of 'a' on odd positions.
3. In each iteration, apply the 'rotate' operation to the string, then apply the 'addOdd' operation to the string, and check if the resulting string is smaller than the current smallest string.
4. Outside the inner loop, apply the 'addAtIndex' operation to the original string to update the last even position by adding 'a' to it.
5. At the end of the outer loop, return the smallest string obtained.

The time complexity of this approach is O(n * 10 * (n + 10)), where n is the length of the input string s.


# Best Team With No Conflicts

- slug: best-team-with-no-conflicts
- difficulty: Medium

You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team.

However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player has a **strictly higher** score than an older player. A conflict does **not** occur between players of the same age.

Given two lists, `scores` and `ages`, where each `scores[i]` and `ages[i]` represents the score and age of the `ith` player, respectively, return _the highest overall score of all possible basketball teams_.

**Example 1:**

**Input:** scores = \[1,3,5,10,15\], ages = \[1,2,3,4,5\]
**Output:** 34
**Explanation:** You can choose all the players.

**Example 2:**

**Input:** scores = \[4,5,6,5\], ages = \[2,1,2,1\]
**Output:** 16
**Explanation:** It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.

**Example 3:**

**Input:** scores = \[1,2,3,5\], ages = \[8,9,10,1\]
**Output:** 6
**Explanation:** It is best to choose the first 3 players.

**Constraints:**

*   `1 <= scores.length, ages.length <= 1000`
*   `scores.length == ages.length`
*   `1 <= scores[i] <= 106`
*   `1 <= ages[i] <= 1000`

## A solution in Java

```java
import java.util.Arrays;

public boolean canMakeArithmeticProgression(int[] arr) {
    Arrays.sort(arr);
    int difference = arr[1] - arr[0];
    for (int i = 2; i < arr.length; i++) {
        if (arr[i] - arr[i - 1] != difference) {
            return false;
        }
    }
    return true;
}
```
1. Sort the array in ascending order.
2. Calculate the difference between the first two elements.
3. Iterate through the rest of the array and check whether the difference between the consecutive elements remains the same as the initial difference.
4. If the difference is the same for all consecutive elements, return true, otherwise return false.

## A solution in C++

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

bool canMakeArithmeticProgression(vector<int>& arr) {
    sort(arr.begin(), arr.end());
    int difference = arr[1] - arr[0];
    for (int i = 2; i < arr.size(); i++) {
        if (arr[i] - arr[i - 1] != difference) {
            return false;
        }
    }
    return true;
}
```
1. Sort the array in ascending order.
2. Calculate the difference between the first two elements.
3. Iterate through the rest of the array and check whether the difference between the consecutive elements remains the same as the initial difference.
4. If the difference is the same for all consecutive elements, return true, otherwise return false.

## A solution in Python

```python
def can_make_arithmetic_progression(arr):
    arr.sort()
    difference = arr[1] - arr[0]
    for i in range(2, len(arr)):
        if arr[i] - arr[i - 1] != difference:
            return False
    return True
```
1. Sort the array in ascending order.
2. Calculate the difference between the first two elements.
3. Iterate through the rest of the array and check whether the difference between the consecutive elements remains the same as the initial difference.
4. If the difference is the same for all consecutive elements, return true, otherwise return false.

## A solution in Javascript

```javascript
function canMakeArithmeticProgression(arr) {
    arr.sort((a, b) => a - b);
    const difference = arr[1] - arr[0];
    for (let i = 2; i < arr.length; i++) {
        if (arr[i] - arr[i - 1] !== difference) {
            return false;
        }
    }
    return true;
}
```
1. Sort the array in ascending order.
2. Calculate the difference between the first two elements.
3. Iterate through the rest of the array and check whether the difference between the consecutive elements remains the same as the initial difference.
4. If the difference is the same for all consecutive elements, return true, otherwise return false.


# Graph Connectivity With Threshold

- slug: graph-connectivity-with-threshold
- difficulty: Hard

We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true:

*   `x % z == 0`,
*   `y % z == 0`, and
*   `z > threshold`.

Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them).

Return _an array_ `answer`_, where_ `answer.length == queries.length` _and_ `answer[i]` _is_ `true` _if for the_ `ith` _query, there is a path between_ `ai` _and_ `bi`_, or_ `answer[i]` _is_ `false` _if there is no path._

**Example 1:**

**Input:** n = 6, threshold = 2, queries = \[\[1,4\],\[2,5\],\[3,6\]\]
**Output:** \[false,false,true\]
**Explanation:** The divisors for each number:
1:   1
2:   1, 2
3:   1, 3
4:   1, 2, 4
5:   1, 5
6:   1, 2, 3, 6
Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the
only ones directly connected. The result of each query:
\[1,4\]   1 is not connected to 4
\[2,5\]   2 is not connected to 5
\[3,6\]   3 is connected to 6 through path 3--6

**Example 2:**

**Input:** n = 6, threshold = 0, queries = \[\[4,5\],\[3,4\],\[3,2\],\[2,6\],\[1,3\]\]
**Output:** \[true,true,true,true,true\]
**Explanation:** The divisors for each number are the same as the previous example. However, since the threshold is 0,
all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.

**Example 3:**

**Input:** n = 5, threshold = 1, queries = \[\[4,5\],\[4,5\],\[3,2\],\[2,3\],\[3,4\]\]
**Output:** \[false,false,false,false,false\]
**Explanation:** Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.
Please notice that there can be multiple queries for the same pair of nodes \[x, y\], and that the query \[x, y\] is equivalent to the query \[y, x\].

**Constraints:**

*   `2 <= n <= 104`
*   `0 <= threshold <= n`
*   `1 <= queries.length <= 105`
*   `queries[i].length == 2`
*   `1 <= ai, bi <= cities`
*   `ai != bi`

## A solution in Java

```java
public int lastMoment(int n, int[] left, int[] right) {
    int max_left = 0;
    int min_right = n;

    for(int position : left) {
        max_left = Math.max(max_left, position);
    }

    for(int position : right) {
        min_right = Math.min(min_right, position);
    }

    return Math.max(max_left, n - min_right);
}
```
The algorithm calculates the moment when the last ant(s) fall out of the plank by following these steps:

1. Find the maximum position of ants moving towards the left (max_left). These ants will fall off the left end of the plank.

2. Find the minimum position of ants moving towards the right (min_right). These ants will fall off the right end of the plank.

3. Return the maximum time taken among the ants falling off the left end (max_left) and the right end (n - min_right). This is because the ant that takes the maximum time to fall off the plank will be the last one to fall, so that moment will be the answer.

## A solution in C++

```cpp
int lastMoment(int n, vector<int>& left, vector<int>& right) {
    int max_left = 0;
    int min_right = n;

    for(int position : left) {
        max_left = max(max_left, position);
    }

    for(int position : right) {
        min_right = min(min_right, position);
    }

    return max(max_left, n - min_right);
}
```
The algorithm calculates the moment when the last ant(s) fall out of the plank by following these steps:

1. Find the maximum position of ants moving towards the left (max_left). These ants will fall off the left end of the plank.

2. Find the minimum position of ants moving towards the right (min_right). These ants will fall off the right end of the plank.

3. Return the maximum time taken among the ants falling off the left end (max_left) and the right end (n - min_right). This is because the ant that takes the maximum time to fall off the plank will be the last one to fall, so that moment will be the answer.

## A solution in Python

```python
def lastMoment(n, left, right):
    max_left = max(left, default=0)
    min_right = min(right, default=n)

    return max(max_left, n - min_right)
```
The algorithm calculates the moment when the last ant(s) fall out of the plank by following these steps:

1. Find the maximum position of ants moving towards the left (max_left). These ants will fall off the left end of the plank.

2. Find the minimum position of ants moving towards the right (min_right). These ants will fall off the right end of the plank.

3. Return the maximum time taken among the ants falling off the left end (max_left) and the right end (n - min_right). This is because the ant that takes the maximum time to fall off the plank will be the last one to fall, so that moment will be the answer.

## A solution in Javascript

```javascript
function lastMoment(n, left, right) {
    let max_left = 0;
    let min_right = n;

    for (let position of left) {
        max_left = Math.max(max_left, position);
    }

    for (let position of right) {
        min_right = Math.min(min_right, position);
    }

    return Math.max(max_left, n - min_right);
}
```
The algorithm calculates the moment when the last ant(s) fall out of the plank by following these steps:

1. Find the maximum position of ants moving towards the left (max_left). These ants will fall off the left end of the plank.

2. Find the minimum position of ants moving towards the right (min_right). These ants will fall off the right end of the plank.

3. Return the maximum time taken among the ants falling off the left end (max_left) and the right end (n - min_right). This is because the ant that takes the maximum time to fall off the plank will be the last one to fall, so that moment will be the answer.


# Design an Expression Tree With Evaluate Function

- slug: design-an-expression-tree-with-evaluate-function
- difficulty: Medium

Given the `postfix` tokens of an arithmetic expression, build and return _the binary expression tree that represents this expression._

**Postfix** notation is a notation for writing arithmetic expressions in which the operands (numbers) appear before their operators. For example, the postfix tokens of the expression `4*(5-(7+2))` are represented in the array `postfix = [ "4 ", "5 ", "7 ", "2 ", "+ ", "- ", "* "]`.

The class `Node` is an interface you should use to implement the binary expression tree. The returned tree will be tested using the `evaluate` function, which is supposed to evaluate the tree's value. You should not remove the `Node` class; however, you can modify it as you wish, and you can define other classes to implement it if needed.

A **[binary expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree)** is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (numbers), and internal nodes (nodes with two children) correspond to the operators `'+'` (addition), `'-'` (subtraction), `'*'` (multiplication), and `'/'` (division).

It's guaranteed that no subtree will yield a value that exceeds `109` in absolute value, and all the operations are valid (i.e., no division by zero).

**Follow up:** Could you design the expression tree such that it is more modular? For example, is your design able to support additional operators without making changes to your existing `evaluate` implementation?

**Example 1:**

**Input:** s = \[ "3 ", "4 ", "+ ", "2 ", "\* ", "7 ", "/ "\]
**Output:** 2
**Explanation:** this expression evaluates to the above binary tree with expression (`(3+4)*2)/7) = 14/7 = 2.`

**Example 2:**

**Input:** s = \[ "4 ", "5 ", "2 ", "7 ", "+ ", "- ", "\* "\]
**Output:** -16
**Explanation:** this expression evaluates to the above binary tree with expression 4\*(5-`(2+7)) = 4*(-4) = -16.`

**Constraints:**

*   `1 <= s.length < 100`
*   `s.length` is odd.
*   `s` consists of numbers and the characters `'+'`, `'-'`, `'*'`, and `'/'`.
*   If `s[i]` is a number, its integer representation is no more than `105`.
*   It is guaranteed that `s` is a valid expression.
*   The absolute value of the result and intermediate values will not exceed `109`.
*   It is guaranteed that no expression will include division by zero.

## A solution in Java

```java
public int numSubmat(int[][] mat) {
    int m = mat.length, n = mat[0].length;
    int[][] dp = new int[m][n];
    int count = 0;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (mat[i][j] == 1) {
                dp[i][j] = (j == 0) ? 1 : dp[i][j - 1] + 1;
                int minWidth = dp[i][j];
                for (int k = i; k >= 0; k--) {
                    minWidth = Math.min(minWidth, dp[k][j]);
                    count += minWidth;
                }
            }
        }
    }
    return count;
}
```
1. Create a DP matrix of the same dimensions as the given binary matrix, and a `count` variable.
2. Loop through each cell of the binary matrix. If the cell contains a 1, update the DP matrix cell with either 1 if it's the first column, or add 1 to the value of the previous column in the same row.
3. For each cell with a 1, iterate from its row to the first row, calculating the minimum width found in the DP matrix, and update the count with the minimum width.
4. The final count value will be the number of submatrices containing all ones.

## A solution in C++

```cpp
int numSubmat(vector<vector<int>>& mat) {
    int m = mat.size(), n = mat[0].size();
    vector<vector<int>> dp(m, vector<int>(n));
    int count = 0;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (mat[i][j] == 1) {
                dp[i][j] = (j == 0) ? 1 : dp[i][j - 1] + 1;
                int minWidth = dp[i][j];
                for (int k = i; k >= 0; k--) {
                    minWidth = min(minWidth, dp[k][j]);
                    count += minWidth;
                }
            }
        }
    }
    return count;
}
```
1. Create a DP matrix of the same dimensions as the given binary matrix, and a `count` variable.
2. Loop through each cell of the binary matrix. If the cell contains a 1, update the DP matrix cell with either 1 if it's the first column, or add 1 to the value of the previous column in the same row.
3. For each cell with a 1, iterate from its row to the first row, calculating the minimum width found in the DP matrix, and update the count with the minimum width.
4. The final count value will be the number of submatrices containing all ones.

## A solution in Python

```python
def numSubmat(mat):
    m, n = len(mat), len(mat[0])
    dp = [[0] * n for _ in range(m)]
    count = 0

    for i in range(m):
        for j in range(n):
            if mat[i][j] == 1:
                dp[i][j] = (1 if j == 0 else dp[i][j - 1] + 1)
                minWidth = dp[i][j]
                for k in range(i, -1, -1):
                    minWidth = min(minWidth, dp[k][j])
                    count += minWidth

    return count
```
1. Create a DP matrix of the same dimensions as the given binary matrix, and a `count` variable.
2. Loop through each cell of the binary matrix. If the cell contains a 1, update the DP matrix cell with either 1 if it's the first column, or add 1 to the value of the previous column in the same row.
3. For each cell with a 1, iterate from its row to the first row, calculating the minimum width found in the DP matrix, and update the count with the minimum width.
4. The final count value will be the number of submatrices containing all ones.

## A solution in Javascript

```javascript
function numSubmat(mat) {
    const m = mat.length, n = mat[0].length;
    const dp = Array.from({ length: m }, () => Array(n).fill(0));
    let count = 0;

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (mat[i][j] === 1) {
                dp[i][j] = (j === 0) ? 1 : dp[i][j - 1] + 1;
                let minWidth = dp[i][j];
                for (let k = i; k >= 0; k--) {
                    minWidth = Math.min(minWidth, dp[k][j]);
                    count += minWidth;
                }
            }
        }
    }
    return count;
}
```
1. Create a DP matrix of the same dimensions as the given binary matrix, and a `count` variable.
2. Loop through each cell of the binary matrix. If the cell contains a 1, update the DP matrix cell with either 1 if it's the first column, or add 1 to the value of the previous column in the same row.
3. For each cell with a 1, iterate from its row to the first row, calculating the minimum width found in the DP matrix, and update the count with the minimum width.
4. The final count value will be the number of submatrices containing all ones.


# Slowest Key

- slug: slowest-key
- difficulty: Easy

A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.

You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released.

The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`.

Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**.

_Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._

**Example 1:**

**Input:** releaseTimes = \[9,29,49,50\], keysPressed =  "cbcd "
**Output:**  "c "
**Explanation:** The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.

**Example 2:**

**Input:** releaseTimes = \[12,23,36,46,62\], keysPressed =  "spuda "
**Output:**  "a "
**Explanation:** The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.

**Constraints:**

*   `releaseTimes.length == n`
*   `keysPressed.length == n`
*   `2 <= n <= 1000`
*   `1 <= releaseTimes[i] <= 109`
*   `releaseTimes[i] < releaseTimes[i+1]`
*   `keysPressed` contains only lowercase English letters.

## A solution in Java

```java
public String minInteger(String num, int k) {
    if (k == 0) return num;
    int n = num.length();
    char[] arr = num.toCharArray();
    for (int i = 0; i < n; ++i) {
        int idx = i;
        for (int j = i + 1; j < n && j - i <= k; ++j) {
            if (arr[j] < arr[idx]) {
                idx = j;
            }
        }
        char minDigit = arr[idx];
        for (int j = idx; j > i; --j) {
            arr[j] = arr[j - 1];
        }
        arr[i] = minDigit;
        k -= idx - i;
    }
    return new String(arr);
}
```
1. If `k` is 0, return the input `num` directly as there's no swap operation allowed.
2. Convert the input `num` to an array or a list in each language.
3. Iterate through each digit of the number (outer loop).
4. For each digit, find the minimum digit within the range allowed by `k` (inner loop).
5. Swap the found minimum digit to the current digit position (updating the array or list by shifting digits), and update `k` value accordingly.
6. Convert the updated array or list back to string and return.

## A solution in C++

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

string minInteger(string num, int k) {
    if (k == 0) return num;
    int n = num.size();
    for (int i = 0; i < n; ++i) {
        int idx = i;
        for (int j = i + 1; j < n && j - i <= k; ++j) {
            if (num[j] < num[idx]) {
                idx = j;
            }
        }
        char minDigit = num[idx];
        for (int j = idx; j > i; --j) {
            num[j] = num[j - 1];
        }
        num[i] = minDigit;
        k -= idx - i;
    }
    return num;
}
```
1. If `k` is 0, return the input `num` directly as there's no swap operation allowed.
2. Convert the input `num` to an array or a list in each language.
3. Iterate through each digit of the number (outer loop).
4. For each digit, find the minimum digit within the range allowed by `k` (inner loop).
5. Swap the found minimum digit to the current digit position (updating the array or list by shifting digits), and update `k` value accordingly.
6. Convert the updated array or list back to string and return.

## A solution in Python

```python
def minInteger(num: str, k: int) -> str:
    if k == 0:
        return num
    num = list(num)
    n = len(num)
    for i in range(n):
        idx = i
        for j in range(i + 1, n):
            if j - i > k:
                break
            if num[j] < num[idx]:
                idx = j
        min_digit = num[idx]
        for j in range(idx, i, -1):
            num[j] = num[j - 1]
        num[i] = min_digit
        k -= idx - i
    return ''.join(num)
```
1. If `k` is 0, return the input `num` directly as there's no swap operation allowed.
2. Convert the input `num` to an array or a list in each language.
3. Iterate through each digit of the number (outer loop).
4. For each digit, find the minimum digit within the range allowed by `k` (inner loop).
5. Swap the found minimum digit to the current digit position (updating the array or list by shifting digits), and update `k` value accordingly.
6. Convert the updated array or list back to string and return.

## A solution in Javascript

```javascript
function minInteger(num, k) {
    if (k === 0) return num;
    num = num.split('');
    const n = num.length;
    for (let i = 0; i < n; ++i) {
        let idx = i;
        for (let j = i + 1; j < n && j - i <= k; ++j) {
            if (num[j] < num[idx]) {
                idx = j;
            }
        }
        const minDigit = num[idx];
        for (let j = idx; j > i; --j) {
            num[j] = num[j - 1];
        }
        num[i] = minDigit;
        k -= idx - i;
    }
    return num.join('');
}
```
1. If `k` is 0, return the input `num` directly as there's no swap operation allowed.
2. Convert the input `num` to an array or a list in each language.
3. Iterate through each digit of the number (outer loop).
4. For each digit, find the minimum digit within the range allowed by `k` (inner loop).
5. Swap the found minimum digit to the current digit position (updating the array or list by shifting digits), and update `k` value accordingly.
6. Convert the updated array or list back to string and return.


# Arithmetic Subarrays

- slug: arithmetic-subarrays
- difficulty: Medium

A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`.

For example, these are **arithmetic** sequences:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not **arithmetic**:

1, 1, 2, 5, 7

You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.

Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._

**Example 1:**

**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]`
**Output:** `[true,false,true]`
**Explanation:**
In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence.
In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence.

**Example 2:**

**Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\]
**Output:** \[false,true,false,false,true,true\]

**Constraints:**

*   `n == nums.length`
*   `m == l.length`
*   `m == r.length`
*   `2 <= n <= 500`
*   `1 <= m <= 500`
*   `0 <= l[i] < r[i] < n`
*   `-105 <= nums[i] <= 105`

## A solution in Java

```java
public int countOdds(int low, int high) {
    return (high + 1) / 2 - low / 2;
}
```
If the low and the high are both even, then the difference between the count of numbers from 1 to low and from 1 to high should give us the count of odd numbers between low and high (inclusive).

The number of odd numbers between 1 and an integer n is calculated by `(n + 1) / 2`. So, for the low and high values, we can calculate the odd counts in the same way. Then subtract the count of odd numbers from 1 to low, from the count of odd numbers from 1 to high. The result should give us the count of odd numbers between low and high.

For example, if low is 2 and high is 9:
- The count of odd numbers between 1 to 9 is (9 + 1) / 2 = 5
- The count of odd numbers between 1 to 2 is (2 + 1) / 2 = 1
The count of odd numbers between 2 and 9 is 5 - 1 = 4

## A solution in C++

```cpp
int countOdds(int low, int high) {
    return (high + 1) / 2 - low / 2;
}
```
If the low and the high are both even, then the difference between the count of numbers from 1 to low and from 1 to high should give us the count of odd numbers between low and high (inclusive).

The number of odd numbers between 1 and an integer n is calculated by `(n + 1) / 2`. So, for the low and high values, we can calculate the odd counts in the same way. Then subtract the count of odd numbers from 1 to low, from the count of odd numbers from 1 to high. The result should give us the count of odd numbers between low and high.

For example, if low is 2 and high is 9:
- The count of odd numbers between 1 to 9 is (9 + 1) / 2 = 5
- The count of odd numbers between 1 to 2 is (2 + 1) / 2 = 1
The count of odd numbers between 2 and 9 is 5 - 1 = 4

## A solution in Python

```python
def count_odds(low, high):
    return (high + 1) // 2 - low // 2
```
If the low and the high are both even, then the difference between the count of numbers from 1 to low and from 1 to high should give us the count of odd numbers between low and high (inclusive).

The number of odd numbers between 1 and an integer n is calculated by `(n + 1) / 2`. So, for the low and high values, we can calculate the odd counts in the same way. Then subtract the count of odd numbers from 1 to low, from the count of odd numbers from 1 to high. The result should give us the count of odd numbers between low and high.

For example, if low is 2 and high is 9:
- The count of odd numbers between 1 to 9 is (9 + 1) / 2 = 5
- The count of odd numbers between 1 to 2 is (2 + 1) / 2 = 1
The count of odd numbers between 2 and 9 is 5 - 1 = 4

## A solution in Javascript

```javascript
function countOdds(low, high) {
    return Math.floor((high + 1) / 2) - Math.floor(low / 2);
}
```
If the low and the high are both even, then the difference between the count of numbers from 1 to low and from 1 to high should give us the count of odd numbers between low and high (inclusive).

The number of odd numbers between 1 and an integer n is calculated by `(n + 1) / 2`. So, for the low and high values, we can calculate the odd counts in the same way. Then subtract the count of odd numbers from 1 to low, from the count of odd numbers from 1 to high. The result should give us the count of odd numbers between low and high.

For example, if low is 2 and high is 9:
- The count of odd numbers between 1 to 9 is (9 + 1) / 2 = 5
- The count of odd numbers between 1 to 2 is (2 + 1) / 2 = 1
The count of odd numbers between 2 and 9 is 5 - 1 = 4


# Path With Minimum Effort

- slug: path-with-minimum-effort
- difficulty: Medium

You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**). You can move **up**, **down**, **left**, or **right**, and you wish to find a route that requires the minimum **effort**.

A route's **effort** is the **maximum absolute difference** in heights between two consecutive cells of the route.

Return _the minimum **effort** required to travel from the top-left cell to the bottom-right cell._

**Example 1:**

**Input:** heights = \[\[1,2,2\],\[3,8,2\],\[5,3,5\]\]
**Output:** 2
**Explanation:** The route of \[1,3,5,3,5\] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of \[1,2,2,2,5\], where the maximum absolute difference is 3.

**Example 2:**

**Input:** heights = \[\[1,2,3\],\[3,8,4\],\[5,3,5\]\]
**Output:** 1
**Explanation:** The route of \[1,2,3,4,5\] has a maximum absolute difference of 1 in consecutive cells, which is better than route \[1,3,5,3,5\].

**Example 3:**

**Input:** heights = \[\[1,2,1,1,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,1,1,2,1\]\]
**Output:** 0
**Explanation:** This route does not require any effort.

**Constraints:**

*   `rows == heights.length`
*   `columns == heights[i].length`
*   `1 <= rows, columns <= 100`
*   `1 <= heights[i][j] <= 106`

## A solution in Java

```java
public int numOfSubarrays(int[] arr) {
    int odd = 0, even = 1, sum = 0, result = 0;
    int mod = 1_000_000_007;
    for (int x : arr) {
        sum = (sum + x) % 2;
        if (sum % 2 == 0) {
            even++;
        } else {
            odd++;
        }
        result = (result + odd) % mod;
    }
    return result;
}
```
1. Initialize variables `odd`, `even`, `sum`, and `result`.
2. Iterate through the elements in the `arr`.
3. For each element, calculate the current sum modulo 2. This effectively determines if the current sum is odd or even.
4. If the current sum is even, increment the `even` counter. Otherwise, increment the `odd` counter.
5. At each step, increment the result by the counter for odd subarray sums. Since we only want to count subarrays with odd sums, incrementing by the odd counter will ensure we only count subarrays ending in the current position with odd sums.
6. At the end of the iteration, return the result modulo 1e9 + 7, as requested in the problem.

## A solution in C++

```cpp
int numOfSubarrays(vector<int>& arr) {
    int odd = 0, even = 1, sum = 0, result = 0;
    int mod = 1e9 + 7;
    for (int x : arr) {
        sum = (sum + x) % 2;
        if (sum % 2 == 0) {
            even++;
        } else {
            odd++;
        }
        result = (result + odd) % mod;
    }
    return result;
}
```
1. Initialize variables `odd`, `even`, `sum`, and `result`.
2. Iterate through the elements in the `arr`.
3. For each element, calculate the current sum modulo 2. This effectively determines if the current sum is odd or even.
4. If the current sum is even, increment the `even` counter. Otherwise, increment the `odd` counter.
5. At each step, increment the result by the counter for odd subarray sums. Since we only want to count subarrays with odd sums, incrementing by the odd counter will ensure we only count subarrays ending in the current position with odd sums.
6. At the end of the iteration, return the result modulo 1e9 + 7, as requested in the problem.

## A solution in Python

```python
def numOfSubarrays(arr):
    odd, even, sum_, result = 0, 1, 0, 0
    mod = 10**9 + 7
    for x in arr:
        sum_ = (sum_ + x) % 2
        if sum_ % 2 == 0:
            even += 1
        else:
            odd += 1
        result = (result + odd) % mod
    return result
```
1. Initialize variables `odd`, `even`, `sum`, and `result`.
2. Iterate through the elements in the `arr`.
3. For each element, calculate the current sum modulo 2. This effectively determines if the current sum is odd or even.
4. If the current sum is even, increment the `even` counter. Otherwise, increment the `odd` counter.
5. At each step, increment the result by the counter for odd subarray sums. Since we only want to count subarrays with odd sums, incrementing by the odd counter will ensure we only count subarrays ending in the current position with odd sums.
6. At the end of the iteration, return the result modulo 1e9 + 7, as requested in the problem.

## A solution in Javascript

```javascript
function numOfSubarrays(arr) {
    let odd = 0, even = 1, sum = 0, result = 0;
    let mod = 1e9 + 7;
    for (let x of arr) {
        sum = (sum + x) % 2;
        if (sum % 2 === 0) {
            even++;
        } else {
            odd++;
        }
        result = (result + odd) % mod;
    }
    return result;
}
```
1. Initialize variables `odd`, `even`, `sum`, and `result`.
2. Iterate through the elements in the `arr`.
3. For each element, calculate the current sum modulo 2. This effectively determines if the current sum is odd or even.
4. If the current sum is even, increment the `even` counter. Otherwise, increment the `odd` counter.
5. At each step, increment the result by the counter for odd subarray sums. Since we only want to count subarrays with odd sums, incrementing by the odd counter will ensure we only count subarrays ending in the current position with odd sums.
6. At the end of the iteration, return the result modulo 1e9 + 7, as requested in the problem.


# Rank Transform of a Matrix

- slug: rank-transform-of-a-matrix
- difficulty: Hard

Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.

The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:

*   The rank is an integer starting from `1`.
*   If two elements `p` and `q` are in the **same row or column**, then:
    *   If `p < q` then `rank(p) < rank(q)`
    *   If `p == q` then `rank(p) == rank(q)`
    *   If `p > q` then `rank(p) > rank(q)`
*   The **rank** should be as **small** as possible.

The test cases are generated so that `answer` is unique under the given rules.

**Example 1:**

**Input:** matrix = \[\[1,2\],\[3,4\]\]
**Output:** \[\[1,2\],\[2,3\]\]
**Explanation:**
The rank of matrix\[0\]\[0\] is 1 because it is the smallest integer in its row and column.
The rank of matrix\[0\]\[1\] is 2 because matrix\[0\]\[1\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1.
The rank of matrix\[1\]\[0\] is 2 because matrix\[1\]\[0\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1.
The rank of matrix\[1\]\[1\] is 3 because matrix\[1\]\[1\] > matrix\[0\]\[1\], matrix\[1\]\[1\] > matrix\[1\]\[0\], and both matrix\[0\]\[1\] and matrix\[1\]\[0\] are rank 2.

**Example 2:**

**Input:** matrix = \[\[7,7\],\[7,7\]\]
**Output:** \[\[1,1\],\[1,1\]\]

**Example 3:**

**Input:** matrix = \[\[20,-21,14\],\[-19,4,19\],\[22,-47,24\],\[-19,4,19\]\]
**Output:** \[\[4,2,3\],\[1,3,4\],\[5,1,6\],\[1,3,4\]\]

**Constraints:**

*   `m == matrix.length`
*   `n == matrix[i].length`
*   `1 <= m, n <= 500`
*   `-109 <= matrix[row][col] <= 109`

## A solution in Java

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

public int numSplits(String s) {
    Set<Character> leftSet = new HashSet<>();
    Set<Character> rightSet = new HashSet<>();
    int[] left = new int[s.length()], right = new int[s.length()];
    int count = 0;

    for (int i = 0; i < s.length(); i++) {
        leftSet.add(s.charAt(i));
        left[i] = leftSet.size();
    }

    for (int i = s.length() - 1; i > 0; i--) {
        rightSet.add(s.charAt(i));
        right[i] = rightSet.size();
    }

    for (int i = 0; i < s.length() - 1; i++) {
        if (left[i] == right[i + 1]) {
            count++;
        }
    }

    return count;
}
```
To solve this problem, we can iterate through the input string s and maintain two sets, one for distinct characters on the left side of the split (left_set) and one for the right side (right_set).

We create two arrays, 'left' and 'right', to store the number of distinct characters at each index in the input string. Then we iterate through the input string from left to right and update the 'left' array with the size of the left_set at each index. After that, we iterate through the input string again, but from right to left, and update the 'right' array with the size of the right_set at each index.

Finally, we check whether the number of distinct characters in the left and right arrays are equal for each possible split, and increment the counter if they are equal. The counter will represent the number of good splits in the input string s.

## A solution in C++

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

int numSplits(string s) {
    unordered_set<char> left_set, right_set;
    vector<int> left(s.size()), right(s.size());
    int count = 0;

    for (int i = 0; i < s.size(); ++i) {
        left_set.insert(s[i]);
        left[i] = left_set.size();
    }

    for (int i = s.size() - 1; i > 0; --i) {
        right_set.insert(s[i]);
        right[i] = right_set.size();
    }

    for (int i = 0; i < s.size() - 1; ++i) {
        if (left[i] == right[i + 1]) {
            ++count;
        }
    }

    return count;
}
```
To solve this problem, we can iterate through the input string s and maintain two sets, one for distinct characters on the left side of the split (left_set) and one for the right side (right_set).

We create two arrays, 'left' and 'right', to store the number of distinct characters at each index in the input string. Then we iterate through the input string from left to right and update the 'left' array with the size of the left_set at each index. After that, we iterate through the input string again, but from right to left, and update the 'right' array with the size of the right_set at each index.

Finally, we check whether the number of distinct characters in the left and right arrays are equal for each possible split, and increment the counter if they are equal. The counter will represent the number of good splits in the input string s.

## A solution in Python

```python
def numSplits(s: str) -> int:
    left_set, right_set = set(), set()
    left, right = [0] * len(s), [0] * len(s)
    count = 0

    for i, char in enumerate(s):
        left_set.add(char)
        left[i] = len(left_set)

    for i in range(len(s) - 1, 0, -1):
        right_set.add(s[i])
        right[i] = len(right_set)

    for i in range(len(s) - 1):
        if left[i] == right[i + 1]:
            count += 1

    return count
```
To solve this problem, we can iterate through the input string s and maintain two sets, one for distinct characters on the left side of the split (left_set) and one for the right side (right_set).

We create two arrays, 'left' and 'right', to store the number of distinct characters at each index in the input string. Then we iterate through the input string from left to right and update the 'left' array with the size of the left_set at each index. After that, we iterate through the input string again, but from right to left, and update the 'right' array with the size of the right_set at each index.

Finally, we check whether the number of distinct characters in the left and right arrays are equal for each possible split, and increment the counter if they are equal. The counter will represent the number of good splits in the input string s.

## A solution in Javascript

```javascript
function numSplits(s) {
    const leftSet = new Set(), rightSet = new Set();
    const left = new Array(s.length).fill(0), right = new Array(s.length).fill(0);
    let count = 0;

    for (let i = 0; i < s.length; i++) {
        leftSet.add(s[i]);
        left[i] = leftSet.size;
    }

    for (let i = s.length - 1; i > 0; i--) {
        rightSet.add(s[i]);
        right[i] = rightSet.size;
    }

    for (let i = 0; i < s.length - 1; i++) {
        if (left[i] === right[i + 1]) {
            count++;
        }
    }

    return count;
}
```
To solve this problem, we can iterate through the input string s and maintain two sets, one for distinct characters on the left side of the split (left_set) and one for the right side (right_set).

We create two arrays, 'left' and 'right', to store the number of distinct characters at each index in the input string. Then we iterate through the input string from left to right and update the 'left' array with the size of the left_set at each index. After that, we iterate through the input string again, but from right to left, and update the 'right' array with the size of the right_set at each index.

Finally, we check whether the number of distinct characters in the left and right arrays are equal for each possible split, and increment the counter if they are equal. The counter will represent the number of good splits in the input string s.


# Add Two Polynomials Represented as Linked Lists

- slug: add-two-polynomials-represented-as-linked-lists
- difficulty: Medium

A polynomial linked list is a special type of linked list where every node represents a term in a polynomial expression.

Each node has three attributes:

*   `coefficient`: an integer representing the number multiplier of the term. The coefficient of the term `**9**x4` is `9`.
*   `power`: an integer representing the exponent. The power of the term `9x**4**` is `4`.
*   `next`: a pointer to the next node in the list, or `null` if it is the last node of the list.

For example, the polynomial `5x3 + 4x - 7` is represented by the polynomial linked list illustrated below:

The polynomial linked list must be in its standard form: the polynomial must be in **strictly** descending order by its `power` value. Also, terms with a `coefficient` of `0` are omitted.

Given two polynomial linked list heads, `poly1` and `poly2`, add the polynomials together and return _the head of the sum of the polynomials_.

**`PolyNode` format:**

The input/output format is as a list of `n` nodes, where each node is represented as its `[coefficient, power]`. For example, the polynomial `5x3 + 4x - 7` would be represented as: `[[5,3],[4,1],[-7,0]]`.

**Example 1:**

**Input:** poly1 = \[\[1,1\]\], poly2 = \[\[1,0\]\]
**Output:** \[\[1,1\],\[1,0\]\]
**Explanation:** poly1 = x. poly2 = 1. The sum is x + 1.

**Example 2:**

**Input:** poly1 = \[\[2,2\],\[4,1\],\[3,0\]\], poly2 = \[\[3,2\],\[-4,1\],\[-1,0\]\]
**Output:** \[\[5,2\],\[2,0\]\]
**Explanation:** poly1 = 2x2 + 4x + 3. poly2 = 3x2 - 4x - 1. The sum is 5x2 + 2. Notice that we omit the  "0x " term.

**Example 3:**

**Input:** poly1 = \[\[1,2\]\], poly2 = \[\[-1,2\]\]
**Output:** \[\]
**Explanation:** The sum is 0. We return an empty list.

**Constraints:**

*   `0 <= n <= 104`
*   `-109 <= PolyNode.coefficient <= 109`
*   `PolyNode.coefficient != 0`
*   `0 <= PolyNode.power <= 109`
*   `PolyNode.power > PolyNode.next.power`

## A solution in Java

```java
class PolyNode {
    int coefficient, power;
    PolyNode next;
    PolyNode(int c, int p) {
        coefficient = c;
        power = p;
        next = null;
    }
}

PolyNode addPoly(PolyNode poly1, PolyNode poly2) {
    PolyNode dummy = new PolyNode(0, 0);
    PolyNode current = dummy;

    while (poly1 != null && poly2 != null) {
        if (poly1.power > poly2.power) {
            current.next = poly1;
            poly1 = poly1.next;
        } else if (poly1.power < poly2.power) {
            current.next = poly2;
            poly2 = poly2.next;
        } else {
            int sum = poly1.coefficient + poly2.coefficient;
            if (sum != 0) {
                current.next = new PolyNode(sum, poly1.power);
                current = current.next;
            }
            poly1 = poly1.next;
            poly2 = poly2.next;
        }
        current = current.next;
    }

    if (poly1 != null) {
        current.next = poly1;
    } else {
        current.next = poly2;
    }
    return dummy.next;
}
```
The algorithm uses a dummy node to create a new linked list representing the sum of the given polynomials. A `current` pointer iterates through the polynomials, adding the terms with the same powers and appending it into the new linked list if the coefficient sum is not 0. Polynomials with different powers are simply appended into the new linked list. When one of the linked lists is finished, it simply appends the remaining nodes of the other list to the new linked list. Finally, return the `next` pointer of the dummy node as the head of the new linked list representing the sum of polynomials.

## A solution in C++

```cpp
class PolyNode {
public:
    int coefficient, power;
    PolyNode* next;
    PolyNode(int c, int p): coefficient(c), power(p), next(nullptr) {}
};

PolyNode* addPoly(PolyNode* poly1, PolyNode* poly2) {
    PolyNode* dummy = new PolyNode(0, 0);
    PolyNode* current = dummy;

    while (poly1 && poly2) {
        if (poly1->power > poly2->power) {
            current->next = poly1;
            poly1 = poly1->next;
        } else if (poly1->power < poly2->power) {
            current->next = poly2;
            poly2 = poly2->next;
        } else {
            int sum = poly1->coefficient + poly2->coefficient;
            if (sum != 0) {
                current->next = new PolyNode(sum, poly1->power);
                current = current->next;
            }
            poly1 = poly1->next;
            poly2 = poly2->next;
        }
        current = current->next;
    }

    if (poly1) {
        current->next = poly1;
    } else {
        current->next = poly2;
    }
    return dummy->next;
}
```
The algorithm uses a dummy node to create a new linked list representing the sum of the given polynomials. A `current` pointer iterates through the polynomials, adding the terms with the same powers and appending it into the new linked list if the coefficient sum is not 0. Polynomials with different powers are simply appended into the new linked list. When one of the linked lists is finished, it simply appends the remaining nodes of the other list to the new linked list. Finally, return the `next` pointer of the dummy node as the head of the new linked list representing the sum of polynomials.

## A solution in Python

```python
class PolyNode:
    def __init__(self, c: int, p: int, next: 'PolyNode' = None):
        self.coefficient = c
        self.power = p
        self.next = next

def addPoly(poly1: PolyNode, poly2: PolyNode) -> PolyNode:
    dummy = PolyNode(0, 0)
    current = dummy

    while poly1 and poly2:
        if poly1.power > poly2.power:
            current.next = poly1
            poly1 = poly1.next
        elif poly1.power < poly2.power:
            current.next = poly2
            poly2 = poly2.next
        else:
            sum = poly1.coefficient + poly2.coefficient
            if sum != 0:
                current.next = PolyNode(sum, poly1.power)
                current = current.next
            poly1 = poly1.next
            poly2 = poly2.next
        current = current.next

    current.next = poly1 if poly1 else poly2
    return dummy.next
```
The algorithm uses a dummy node to create a new linked list representing the sum of the given polynomials. A `current` pointer iterates through the polynomials, adding the terms with the same powers and appending it into the new linked list if the coefficient sum is not 0. Polynomials with different powers are simply appended into the new linked list. When one of the linked lists is finished, it simply appends the remaining nodes of the other list to the new linked list. Finally, return the `next` pointer of the dummy node as the head of the new linked list representing the sum of polynomials.

## A solution in Javascript

```javascript
class PolyNode {
    constructor(c, p, next = null) {
        this.coefficient = c;
        this.power = p;
        this.next = next;
    }
}

function addPoly(poly1, poly2) {
    let dummy = new PolyNode(0, 0);
    let current = dummy;

    while (poly1 && poly2) {
        if (poly1.power > poly2.power) {
            current.next = poly1;
            poly1 = poly1.next;
        } else if (poly1.power < poly2.power) {
            current.next = poly2;
            poly2 = poly2.next;
        } else {
            let sum = poly1.coefficient + poly2.coefficient;
            if (sum !== 0) {
                current.next = new PolyNode(sum, poly1.power);
                current = current.next;
            }
            poly1 = poly1.next;
            poly2 = poly2.next;
        }
        current = current.next;
    }

    current.next = poly1 ? poly1 : poly2;
    return dummy.next;
}
```
The algorithm uses a dummy node to create a new linked list representing the sum of the given polynomials. A `current` pointer iterates through the polynomials, adding the terms with the same powers and appending it into the new linked list if the coefficient sum is not 0. Polynomials with different powers are simply appended into the new linked list. When one of the linked lists is finished, it simply appends the remaining nodes of the other list to the new linked list. Finally, return the `next` pointer of the dummy node as the head of the new linked list representing the sum of polynomials.


# Sort Array by Increasing Frequency

- slug: sort-array-by-increasing-frequency
- difficulty: Easy

Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.

Return the _sorted array_.

**Example 1:**

**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.

**Example 2:**

**Input:** nums = \[2,3,1,3,2\]
**Output:** \[1,3,3,2,2\]
**Explanation:** '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.

**Example 3:**

**Input:** nums = \[-1,1,-6,4,5,-6,1,4,1\]
**Output:** \[5,-1,4,4,-6,-6,1,1,1\]

**Constraints:**

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

## A solution in Java

```java
public int numSub(String s) {
    int mod = 1000000007;
    long result = 0;
    int count = 0;
    for (char c : s.toCharArray()) {
        count = (c == '1') ? count + 1 : 0;
        result = (result + count) % mod;
    }
    return (int)result;
}
```
The algorithm is a single-pass algorithm that iterates over the binary string `s` and calculates the number of contiguous "1" substrings seen so far. We use a variable `count` to track the length of the current run of "1"s. For each character `c` in `s`:
- If `c` is "1", we increment `count` as we have a longer run of 1's, and add the `count` to the `result`. The notion here is that until this run of 1s breaks, any new 1 being added increases the total number of substrings by the entire size of the current window.
- If `c` is not a "1", we reset the `count` to 0 as the sequence is broken.

Finally, we take the result modulo 10^9 + 7 and return it.

## A solution in C++

```cpp
int numSub(string s) {
    int mod = 1000000007;
    long long result = 0;
    int count = 0;
    for (char c : s) {
        count = (c == '1') ? count + 1 : 0;
        result = (result + count) % mod;
    }
    return result;
}
```
The algorithm is a single-pass algorithm that iterates over the binary string `s` and calculates the number of contiguous "1" substrings seen so far. We use a variable `count` to track the length of the current run of "1"s. For each character `c` in `s`:
- If `c` is "1", we increment `count` as we have a longer run of 1's, and add the `count` to the `result`. The notion here is that until this run of 1s breaks, any new 1 being added increases the total number of substrings by the entire size of the current window.
- If `c` is not a "1", we reset the `count` to 0 as the sequence is broken.

Finally, we take the result modulo 10^9 + 7 and return it.

## A solution in Python

```python
def num_sub(s: str) -> int:
    mod = 1000000007
    result = 0
    count = 0
    for c in s:
        count = count + 1 if c == '1' else 0
        result = (result + count) % mod
    return result
```
The algorithm is a single-pass algorithm that iterates over the binary string `s` and calculates the number of contiguous "1" substrings seen so far. We use a variable `count` to track the length of the current run of "1"s. For each character `c` in `s`:
- If `c` is "1", we increment `count` as we have a longer run of 1's, and add the `count` to the `result`. The notion here is that until this run of 1s breaks, any new 1 being added increases the total number of substrings by the entire size of the current window.
- If `c` is not a "1", we reset the `count` to 0 as the sequence is broken.

Finally, we take the result modulo 10^9 + 7 and return it.

## A solution in Javascript

```javascript
function numSub(s) {
    const mod = 1000000007;
    let result = 0;
    let count = 0;
    for (let c of s) {
        count = (c === '1') ? count + 1 : 0;
        result = (result + count) % mod;
    }
    return result;
}
```
The algorithm is a single-pass algorithm that iterates over the binary string `s` and calculates the number of contiguous "1" substrings seen so far. We use a variable `count` to track the length of the current run of "1"s. For each character `c` in `s`:
- If `c` is "1", we increment `count` as we have a longer run of 1's, and add the `count` to the `result`. The notion here is that until this run of 1s breaks, any new 1 being added increases the total number of substrings by the entire size of the current window.
- If `c` is not a "1", we reset the `count` to 0 as the sequence is broken.

Finally, we take the result modulo 10^9 + 7 and return it.


# Widest Vertical Area Between Two Points Containing No Points

- slug: widest-vertical-area-between-two-points-containing-no-points
- difficulty: Medium

Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._

A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width.

Note that points **on the edge** of a vertical area **are not** considered included in the area.

**Example 1:**

**Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\]
**Output:** 1
**Explanation:** Both the red and the blue area are optimal.

**Example 2:**

**Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\]
**Output:** 3

**Constraints:**

*   `n == points.length`
*   `2 <= n <= 105`
*   `points[i].length == 2`
*   `0 <= xi, yi <= 109`

## A solution in Java

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

    for (int i = 1; i <= n; ++i) {
        for (int j = 0; j <= k; ++j) {
            int cnt = 1;
            dp[i][j] = i - j;
            for (int l = i - 2; l >= 0 && i - 2 - l <= j; --l) {
                if (s.charAt(l) == s.charAt(i - 1)) cnt++;
                else cnt = 1;
                int used = i - 2 - l;
                int new_aposition = i - 1 - cnt - used + 1;
                if (cnt >= 100) new_aposition += 4;
                else if (cnt >= 10) new_aposition += 3;
                else if (cnt >= 2) new_aposition += 2;
                else new_aposition++;
                dp[i][j] = Math.min(dp[i][j], new_aposition + dp[l][j - used]);
            }
        }
    }
    return dp[n][k];
}
```
The algorithm uses dynamic programming to find the minimum length of the run-length encoded string after deleting at most k characters.
- Define a 2D dp table with dimensions (n+1) x (k+1), where n is the length of the input string s.
- dp[i][j] stores the minimum length of run-length encoded version for the first i characters of the string after deleting j characters.
- Iterate through each character in the string and possible deletions (0 <= j <= k).
- For each character, iterate through the string in reverse order to find the last position where the character occurred.
- Calculate the new position by considering the count of continuous characters and updating the position accordingly.
- Update dp[i][j] with the minimum value found.
- Return the value in the last cell of the dp table, dp[n][k], which is the final result.

## A solution in C++

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

int min_length_encoded(const std::string& s, int k) {
    int n = s.length();
    std::vector<std::vector<int>> dp(n + 1, std::vector<int>(k + 1, 0));

    for (int i = 1; i <= n; ++i) {
        for (int j = 0; j <= k; ++j) {
            int cnt = 1;
            dp[i][j] = i - j;
            for (int l = i - 2; l >= 0 && i - 2 - l <= j; --l) {
                if (s[l] == s[i - 1]) cnt++;
                else cnt = 1;
                int used = i - 2 - l;
                int new_aposition = i - 1 - cnt - used + 1;
                if (cnt >= 100) new_aposition += 4;
                else if (cnt >= 10) new_aposition += 3;
                else if (cnt >= 2) new_aposition += 2;
                else new_aposition++;
                dp[i][j] = std::min(dp[i][j], new_aposition + dp[l][j - used]);
            }
        }
    }
    return dp[n][k];
}
```
The algorithm uses dynamic programming to find the minimum length of the run-length encoded string after deleting at most k characters.
- Define a 2D dp table with dimensions (n+1) x (k+1), where n is the length of the input string s.
- dp[i][j] stores the minimum length of run-length encoded version for the first i characters of the string after deleting j characters.
- Iterate through each character in the string and possible deletions (0 <= j <= k).
- For each character, iterate through the string in reverse order to find the last position where the character occurred.
- Calculate the new position by considering the count of continuous characters and updating the position accordingly.
- Update dp[i][j] with the minimum value found.
- Return the value in the last cell of the dp table, dp[n][k], which is the final result.

## A solution in Python

```python
def min_length_encoded(s: str, k: int) -> int:
    n = len(s)
    dp = [[0] * (k + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for j in range(k + 1):
            cnt = 1
            dp[i][j] = i - j
            l = i - 2
            while l >= 0 and i - 2 - l <= j:
                if s[l] == s[i - 1]:
                    cnt += 1
                else:
                    cnt = 1
                used = i - 2 - l
                new_aposition = i - 1 - cnt - used + 1
                if cnt >= 100:
                    new_aposition += 4
                elif cnt >= 10:
                    new_aposition += 3
                elif cnt >= 2:
                    new_aposition += 2
                else:
                    new_aposition += 1
                dp[i][j] = min(dp[i][j], new_aposition + dp[l][j - used])
                l -= 1

    return dp[n][k]
```
The algorithm uses dynamic programming to find the minimum length of the run-length encoded string after deleting at most k characters.
- Define a 2D dp table with dimensions (n+1) x (k+1), where n is the length of the input string s.
- dp[i][j] stores the minimum length of run-length encoded version for the first i characters of the string after deleting j characters.
- Iterate through each character in the string and possible deletions (0 <= j <= k).
- For each character, iterate through the string in reverse order to find the last position where the character occurred.
- Calculate the new position by considering the count of continuous characters and updating the position accordingly.
- Update dp[i][j] with the minimum value found.
- Return the value in the last cell of the dp table, dp[n][k], which is the final result.

## A solution in Javascript

```javascript
function min_length_encoded(s, k) {
    const n = s.length;
    const dp = Array.from({ length: n + 1 }, () => new Array(k + 1).fill(0));

    for (let i = 1; i <= n; ++i) {
        for (let j = 0; j <= k; ++j) {
            let cnt = 1;
            dp[i][j] = i - j;
            for (let l = i - 2; l >= 0 && i - 2 - l <= j; --l) {
                if (s[l] === s[i - 1]) cnt++;
                else cnt = 1;
                const used = i - 2 - l;
                let new_aposition = i - 1 - cnt - used + 1;
                if (cnt >= 100) new_aposition += 4;
                else if (cnt >= 10) new_aposition += 3;
                else if (cnt >= 2) new_aposition += 2;
                else new_aposition++;
                dp[i][j] = Math.min(dp[i][j], new_aposition + dp[l][j - used]);
            }
        }
    }
    return dp[n][k];
}
```
The algorithm uses dynamic programming to find the minimum length of the run-length encoded string after deleting at most k characters.
- Define a 2D dp table with dimensions (n+1) x (k+1), where n is the length of the input string s.
- dp[i][j] stores the minimum length of run-length encoded version for the first i characters of the string after deleting j characters.
- Iterate through each character in the string and possible deletions (0 <= j <= k).
- For each character, iterate through the string in reverse order to find the last position where the character occurred.
- Calculate the new position by considering the count of continuous characters and updating the position accordingly.
- Update dp[i][j] with the minimum value found.
- Return the value in the last cell of the dp table, dp[n][k], which is the final result.


# Count Substrings That Differ by One Character

- slug: count-substrings-that-differ-by-one-character
- difficulty: Medium

Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly** one character.

For example, the underlined substrings in `"computer "` and `"computation "` only differ by the `'e'`/`'a'`, so this is a valid way.

Return _the number of substrings that satisfy the condition above._

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

**Example 1:**

**Input:** s =  "aba ", t =  "baba "
**Output:** 6
**Explanation:** The following are the pairs of substrings from s and t that differ by exactly 1 character:
( "aba ",  "baba ")
( "aba ",  "baba ")
( "aba ",  "baba ")
( "aba ",  "baba ")
( "aba ",  "baba ")
( "aba ",  "baba ")
The underlined portions are the substrings that are chosen from s and t.

**Example 2:**

**Input:** s =  "ab ", t =  "bb "
**Output:** 3
**Explanation:** The following are the pairs of substrings from s and t that differ by 1 character:
( "ab ",  "bb ")
( "ab ",  "bb ")
( "ab ",  "bb ")
The underlined portions are the substrings that are chosen from s and t.

**Constraints:**

*   `1 <= s.length, t.length <= 100`
*   `s` and `t` consist of lowercase English letters only.

## A solution in Java

```java
public double getMinDistSum(int[][] positions) {
    double x = 0;
    double y = 0;
    int n = positions.length;
    for (int i = 0; i < n; i++) {
        x += positions[i][0];
        y += positions[i][1];
    }
    x /= n;
    y /= n;
    return x;
}
```
The algorithm above calculates the centroid of all the customers' positions by this logic:
1. Initialize `x` and `y` to 0. These represent the sum of individual positions' x and y values, respectively.
2. Iterate through the input positions array and accumulate the x and y values.
3. Divide the accumulated x and y values by the number of input positions to find the average (centroid) position.

However, the solution above does not consider the Euclidean distance, and the return statement has a mistake as it only returns `x`. The solution needs to be improved by incorporating the geometric median calculation.

## A solution in C++

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

double getMinDistSum(std::vector<std::vector<int>>& positions) {
    double x = 0;
    double y = 0;
    for (const auto& pos : positions) {
        x += pos[0];
        y += pos[1];
    }
    int n = positions.size();
    x /= n;
    y /= n;
    return x;
}
```
The algorithm above calculates the centroid of all the customers' positions by this logic:
1. Initialize `x` and `y` to 0. These represent the sum of individual positions' x and y values, respectively.
2. Iterate through the input positions array and accumulate the x and y values.
3. Divide the accumulated x and y values by the number of input positions to find the average (centroid) position.

However, the solution above does not consider the Euclidean distance, and the return statement has a mistake as it only returns `x`. The solution needs to be improved by incorporating the geometric median calculation.

## A solution in Python

```python
def get_min_dist_sum(positions: List[List[int]]) -> float:
    x, y = 0, 0
    n = len(positions)
    for pos in positions:
        x += pos[0]
        y += pos[1]
    x /= n
    y /= n
    return x
```
The algorithm above calculates the centroid of all the customers' positions by this logic:
1. Initialize `x` and `y` to 0. These represent the sum of individual positions' x and y values, respectively.
2. Iterate through the input positions array and accumulate the x and y values.
3. Divide the accumulated x and y values by the number of input positions to find the average (centroid) position.

However, the solution above does not consider the Euclidean distance, and the return statement has a mistake as it only returns `x`. The solution needs to be improved by incorporating the geometric median calculation.

## A solution in Javascript

```javascript
function getMinDistSum(positions) {
    let x = 0;
    let y = 0;
    const n = positions.length;
    for (let i = 0; i < n; i++) {
        x += positions[i][0];
        y += positions[i][1];
    }
    x /= n;
    y /= n;
    return x;
}
```
The algorithm above calculates the centroid of all the customers' positions by this logic:
1. Initialize `x` and `y` to 0. These represent the sum of individual positions' x and y values, respectively.
2. Iterate through the input positions array and accumulate the x and y values.
3. Divide the accumulated x and y values by the number of input positions to find the average (centroid) position.

However, the solution above does not consider the Euclidean distance, and the return statement has a mistake as it only returns `x`. The solution needs to be improved by incorporating the geometric median calculation.


# Number of Ways to Form a Target String Given a Dictionary

- slug: number-of-ways-to-form-a-target-string-given-a-dictionary
- difficulty: Hard

You are given a list of strings of the **same length** `words` and a string `target`.

Your task is to form `target` using the given `words` under the following rules:

*   `target` should be formed from left to right.
*   To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`.
*   Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string.
*   Repeat the process until you form the string `target`.

**Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met.

Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** words = \[ "acca ", "bbbb ", "caca "\], target =  "aba "
**Output:** 6
**Explanation:** There are 6 ways to form target.
 "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ")
 "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ")
 "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ")
 "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ")
 "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ")
 "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ")

**Example 2:**

**Input:** words = \[ "abba ", "baab "\], target =  "bab "
**Output:** 4
**Explanation:** There are 4 ways to form target.
 "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ")
 "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ")
 "bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ")
 "bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ")

**Constraints:**

*   `1 <= words.length <= 1000`
*   `1 <= words[i].length <= 1000`
*   All strings in `words` have the same length.
*   `1 <= target.length <= 1000`
*   `words[i]` and `target` contain only lowercase English letters.

## A solution in Java

```java
public int numWays(String[] words, String target) {
    int n = words.length;
    int m = target.length();
    int[][] count = new int[n][26];
    int[][] dp = new int[m][n];
    final int mod = 1000000007;

    for (int i = 0; i < n; i++) {
        for (char c : words[i].toCharArray()) {
            count[i][c - 'a']++;
        }
    }

    for (int i = 0; i < n; i++) {
        dp[0][i] = count[i][target.charAt(0) - 'a'];
    }

    for (int i = 1; i < m; i++) {
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < n; k++) {
                dp[i][j] = (dp[i][j] + (int)(((long) dp[i-1][k] * count[j][target.charAt(i) - 'a']) % mod)) % mod;
            }
        }
    }

    int res = 0;
    for (int i = 0; i < n; i++) {
        res = (res + dp[m-1][i]) % mod;
    }
    return res;
}
```
1. Count the occurrences of characters for each word in `words` and store them in a 2D array `count`.
2. Initialize a 2D DP array `dp` where `dp[i][j]` represents the number of ways to form the string `target[0...i]` using the first `j` characters of the strings in `words`.
3. Set the base case for `dp[0][i]` as the count of target character at index 0 in each word of `words`.
4. For each target character from index 1 to index `m-1` (where `m` is the length of the target string), iterate through all words and update the `dp` array. Calculate the number of ways to form the target string using the current word and add it to the previous count stored in `dp`.
5. Add modulo 10^9 + 7 at each step to avoid overflow.
6. The result is the sum of values in the last row of `dp` array, modulo 10^9 + 7.

## A solution in C++

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

using namespace std;

int numWays(vector<string>& words, string target) {
    int n = words.size(), m = target.size();
    vector<vector<int>> count(n, vector<int>(26, 0));
    vector<vector<int>> dp(m, vector<int>(n, 0));
    const int mod = 1e9 + 7;

    for(int i = 0; i < n; i++) {
        for(char c : words[i]) {
            count[i][c - 'a']++;
        }
    }

    for(int i = 0; i < n; i++) {
        dp[0][i] = count[i][target[0] - 'a'];
    }

    for(int i = 1; i < m; i++) {
        for(int j = 0; j < n; j++) {
            for(int k = 0; k < n; k++) {
                dp[i][j] = (dp[i][j] + (long long)dp[i-1][k] * count[j][target[i] - 'a']) % mod;
            }
        }
    }

    int res = 0;
    for(int i = 0; i < n; i++) {
        res = (res + dp[m-1][i]) % mod;
    }
    return res;
}
```
1. Count the occurrences of characters for each word in `words` and store them in a 2D array `count`.
2. Initialize a 2D DP array `dp` where `dp[i][j]` represents the number of ways to form the string `target[0...i]` using the first `j` characters of the strings in `words`.
3. Set the base case for `dp[0][i]` as the count of target character at index 0 in each word of `words`.
4. For each target character from index 1 to index `m-1` (where `m` is the length of the target string), iterate through all words and update the `dp` array. Calculate the number of ways to form the target string using the current word and add it to the previous count stored in `dp`.
5. Add modulo 10^9 + 7 at each step to avoid overflow.
6. The result is the sum of values in the last row of `dp` array, modulo 10^9 + 7.

## A solution in Python

```python
def numWays(words, target):
    n = len(words)
    m = len(target)
    count = [[0] * 26 for _ in range(n)]
    dp = [[0] * n for _ in range(m)]
    mod = 1000000007

    for i, word in enumerate(words):
        for c in word:
            count[i][ord(c) - ord('a')] += 1

    for i in range(n):
        dp[0][i] = count[i][ord(target[0]) - ord('a')]

    for i in range(1, m):
        for j in range(n):
            for k in range(n):
                dp[i][j] = (dp[i][j] + dp[i-1][k] * count[j][ord(target[i]) - ord('a')]) % mod

    return sum(dp[m-1]) % mod
```
1. Count the occurrences of characters for each word in `words` and store them in a 2D array `count`.
2. Initialize a 2D DP array `dp` where `dp[i][j]` represents the number of ways to form the string `target[0...i]` using the first `j` characters of the strings in `words`.
3. Set the base case for `dp[0][i]` as the count of target character at index 0 in each word of `words`.
4. For each target character from index 1 to index `m-1` (where `m` is the length of the target string), iterate through all words and update the `dp` array. Calculate the number of ways to form the target string using the current word and add it to the previous count stored in `dp`.
5. Add modulo 10^9 + 7 at each step to avoid overflow.
6. The result is the sum of values in the last row of `dp` array, modulo 10^9 + 7.

## A solution in Javascript

```javascript
function numWays(words, target) {
    const n = words.length;
    const m = target.length;
    const count = Array.from({length: n}, () => Array(26).fill(0));
    const dp = Array.from({length: m}, () => Array(n).fill(0));
    const mod = 1e9 + 7;

    for (let i = 0; i < n; i++) {
        for (let c of words[i]) {
            count[i][c.charCodeAt(0) - 'a'.charCodeAt(0)]++;
        }
    }

    for (let i = 0; i < n; i++) {
        dp[0][i] = count[i][target.charCodeAt(0) - 'a'.charCodeAt(0)];
    }

    for (let i = 1; i < m; i++) {
        for (let j = 0; j < n; j++) {
            for (let k = 0; k < n; k++) {
                dp[i][j] = (dp[i][j] + dp[i-1][k] * count[j][target.charCodeAt(i) - 'a'.charCodeAt(0)]) % mod;
            }
        }
    }

    return dp[m-1].reduce((acc, val) => (acc + val) % mod, 0);
}
```
1. Count the occurrences of characters for each word in `words` and store them in a 2D array `count`.
2. Initialize a 2D DP array `dp` where `dp[i][j]` represents the number of ways to form the string `target[0...i]` using the first `j` characters of the strings in `words`.
3. Set the base case for `dp[0][i]` as the count of target character at index 0 in each word of `words`.
4. For each target character from index 1 to index `m-1` (where `m` is the length of the target string), iterate through all words and update the `dp` array. Calculate the number of ways to form the target string using the current word and add it to the previous count stored in `dp`.
5. Add modulo 10^9 + 7 at each step to avoid overflow.
6. The result is the sum of values in the last row of `dp` array, modulo 10^9 + 7.


# Check Array Formation Through Concatenation

- slug: check-array-formation-through-concatenation
- difficulty: Easy

You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`.

Return `true` _if it is possible_ _to form the array_ `arr` _from_ `pieces`. Otherwise, return `false`.

**Example 1:**

**Input:** arr = \[15,88\], pieces = \[\[88\],\[15\]\]
**Output:** true
**Explanation:** Concatenate \[15\] then \[88\]

**Example 2:**

**Input:** arr = \[49,18,16\], pieces = \[\[16,18,49\]\]
**Output:** false
**Explanation:** Even though the numbers match, we cannot reorder pieces\[0\].

**Example 3:**

**Input:** arr = \[91,4,64,78\], pieces = \[\[78\],\[4,64\],\[91\]\]
**Output:** true
**Explanation:** Concatenate \[91\] then \[4,64\] then \[78\]

**Constraints:**

*   `1 <= pieces.length <= arr.length <= 100`
*   `sum(pieces[i].length) == arr.length`
*   `1 <= pieces[i].length <= arr.length`
*   `1 <= arr[i], pieces[i][j] <= 100`
*   The integers in `arr` are **distinct**.
*   The integers in `pieces` are **distinct** (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).

## A solution in Java

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

public boolean canFormArray(int[] arr, int[][] pieces) {
    Map<Integer, int[]> map = new HashMap<>();
    for (int[] piece : pieces) {
        map.put(piece[0], piece);
    }

    int i = 0;
    while (i < arr.length) {
        if (!map.containsKey(arr[i])) {
            return false;
        }
        int[] piece = map.get(arr[i]);
        for (int j = 0; j < piece.length; ++j) {
            if (piece[j] != arr[i]) {
                return false;
            }
            ++i;
        }
    }
    return true;
}
```
1. First, create a hash map (or, in Python, a dictionary) to store each `piece` in `pieces`, indexed by its first element.
2. Initialize a variable `i` to iterate through the `arr` array.
3. Use a while loop to check each element in `arr` with the help of the hash map. If the element is not in the hash map, return `false` because it means we can't form the array.
4. If the element is found in the hash map, get the associated piece in `pieces`.
5. Use a nested loop (or iterator) to iterate through the elements of the found piece, comparing them with the corresponding elements in `arr`. If they don't match, return `false`. Otherwise, increment the index `i`.
6. If we successfully iterate through the entire `arr` array, return `true`.

## A solution in C++

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

bool canFormArray(std::vector<int>& arr, std::vector<std::vector<int>>& pieces) {
    std::unordered_map<int, std::vector<int>> map;
    for (auto& piece : pieces) {
        map[piece[0]] = piece;
    }

    int i = 0;
    while (i < arr.size()) {
        if (map.find(arr[i]) == map.end()) {
            return false;
        }
        std::vector<int>& piece = map[arr[i]];
        for (int j = 0; j < piece.size(); ++j) {
            if (piece[j] != arr[i]) {
                return false;
            }
            ++i;
        }
    }
    return true;
}
```
1. First, create a hash map (or, in Python, a dictionary) to store each `piece` in `pieces`, indexed by its first element.
2. Initialize a variable `i` to iterate through the `arr` array.
3. Use a while loop to check each element in `arr` with the help of the hash map. If the element is not in the hash map, return `false` because it means we can't form the array.
4. If the element is found in the hash map, get the associated piece in `pieces`.
5. Use a nested loop (or iterator) to iterate through the elements of the found piece, comparing them with the corresponding elements in `arr`. If they don't match, return `false`. Otherwise, increment the index `i`.
6. If we successfully iterate through the entire `arr` array, return `true`.

## A solution in Python

```python
def canFormArray(arr, pieces):
    map = {piece[0]: piece for piece in pieces}

    i = 0
    while i < len(arr):
        if arr[i] not in map:
            return False
        piece = map[arr[i]]
        for num in piece:
            if num != arr[i]:
                return False
            i += 1
    return True
```
1. First, create a hash map (or, in Python, a dictionary) to store each `piece` in `pieces`, indexed by its first element.
2. Initialize a variable `i` to iterate through the `arr` array.
3. Use a while loop to check each element in `arr` with the help of the hash map. If the element is not in the hash map, return `false` because it means we can't form the array.
4. If the element is found in the hash map, get the associated piece in `pieces`.
5. Use a nested loop (or iterator) to iterate through the elements of the found piece, comparing them with the corresponding elements in `arr`. If they don't match, return `false`. Otherwise, increment the index `i`.
6. If we successfully iterate through the entire `arr` array, return `true`.

## A solution in Javascript

```javascript
function canFormArray(arr, pieces) {
    const map = new Map(pieces.map(piece => [piece[0], piece]));

    let i = 0;
    while (i < arr.length) {
        if (!map.has(arr[i])) {
            return false;
        }
        const piece = map.get(arr[i]);
        for (const num of piece) {
            if (num !== arr[i]) {
                return false;
            }
            i++;
        }
    }
    return true;
}
```
1. First, create a hash map (or, in Python, a dictionary) to store each `piece` in `pieces`, indexed by its first element.
2. Initialize a variable `i` to iterate through the `arr` array.
3. Use a while loop to check each element in `arr` with the help of the hash map. If the element is not in the hash map, return `false` because it means we can't form the array.
4. If the element is found in the hash map, get the associated piece in `pieces`.
5. Use a nested loop (or iterator) to iterate through the elements of the found piece, comparing them with the corresponding elements in `arr`. If they don't match, return `false`. Otherwise, increment the index `i`.
6. If we successfully iterate through the entire `arr` array, return `true`.


# Count Sorted Vowel Strings

- slug: count-sorted-vowel-strings
- difficulty: Medium

Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._

A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet.

**Example 1:**

**Input:** n = 1
**Output:** 5
**Explanation:** The 5 sorted strings that consist of vowels only are `[ "a ", "e ", "i ", "o ", "u "].`

**Example 2:**

**Input:** n = 2
**Output:** 15
**Explanation:** The 15 sorted strings that consist of vowels only are
\[ "aa ", "ae ", "ai ", "ao ", "au ", "ee ", "ei ", "eo ", "eu ", "ii ", "io ", "iu ", "oo ", "ou ", "uu "\].
Note that  "ea " is not a valid string since 'e' comes after 'a' in the alphabet.

**Example 3:**

**Input:** n = 33
**Output:** 66045

**Constraints:**

*   `1 <= n <= 50`

## A solution in Java

```java
public int countVowelStrings(int n) {
    int[] dp = {1, 1, 1, 1, 1};
    for (int i = 2; i <= n; i++) {
        for (int j = 3; j >= 0; j--) {
            dp[j] = dp[j] + dp[j + 1];
        }
    }
    return Arrays.stream(dp).sum();
}
```
We use dynamic programming to solve this problem. Initialize an array dp of size 5 with all elements set to 1. Then, for each i in the range [2, n], iterate through the dp array starting from index 3 (denoting vowel 'o'), moving backwards. Update each dp[j] by adding dp[j + 1] (i.e., count of the next vowel) to its current value. Finally, sum up the values in the dp array and return the result as the number of lexicographically sorted strings with n characters.

## A solution in C++

```cpp
int countVowelStrings(int n) {
    vector<int> dp = {1, 1, 1, 1, 1};
    for (int i = 2; i <= n; i++) {
        for (int j = 3; j >= 0; j--) {
            dp[j] = dp[j] + dp[j + 1];
        }
    }
    return accumulate(dp.begin(), dp.end(), 0);
}
```
We use dynamic programming to solve this problem. Initialize an array dp of size 5 with all elements set to 1. Then, for each i in the range [2, n], iterate through the dp array starting from index 3 (denoting vowel 'o'), moving backwards. Update each dp[j] by adding dp[j + 1] (i.e., count of the next vowel) to its current value. Finally, sum up the values in the dp array and return the result as the number of lexicographically sorted strings with n characters.

## A solution in Python

```python
def countVowelStrings(n: int) -> int:
    dp = [1, 1, 1, 1, 1]
    for i in range(2, n + 1):
        for j in range(3, -1, -1):
            dp[j] = dp[j] + dp[j + 1]
    return sum(dp)
```
We use dynamic programming to solve this problem. Initialize an array dp of size 5 with all elements set to 1. Then, for each i in the range [2, n], iterate through the dp array starting from index 3 (denoting vowel 'o'), moving backwards. Update each dp[j] by adding dp[j + 1] (i.e., count of the next vowel) to its current value. Finally, sum up the values in the dp array and return the result as the number of lexicographically sorted strings with n characters.

## A solution in Javascript

```javascript
function countVowelStrings(n) {
    let dp = [1, 1, 1, 1, 1];
    for (let i = 2; i <= n; i++) {
        for (let j = 3; j >= 0; j--) {
            dp[j] = dp[j] + dp[j + 1];
        }
    }
    return dp.reduce((a, b) => a + b, 0);
}
```
We use dynamic programming to solve this problem. Initialize an array dp of size 5 with all elements set to 1. Then, for each i in the range [2, n], iterate through the dp array starting from index 3 (denoting vowel 'o'), moving backwards. Update each dp[j] by adding dp[j + 1] (i.e., count of the next vowel) to its current value. Finally, sum up the values in the dp array and return the result as the number of lexicographically sorted strings with n characters.