# Push Dominoes

- slug: push-dominoes
- difficulty: Medium

There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.

After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.

When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.

For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.

You are given a string `dominoes` representing the initial state where:

*   `dominoes[i] = 'L'`, if the `ith` domino has been pushed to the left,
*   `dominoes[i] = 'R'`, if the `ith` domino has been pushed to the right, and
*   `dominoes[i] = '.'`, if the `ith` domino has not been pushed.

Return _a string representing the final state_.

**Example 1:**

**Input:** dominoes =  "RR.L "
**Output:**  "RR.L "
**Explanation:** The first domino expends no additional force on the second domino.

**Example 2:**

**Input:** dominoes =  ".L.R...LR..L.. "
**Output:**  "LL.RR.LLRRLL.. "

**Constraints:**

*   `n == dominoes.length`
*   `1 <= n <= 105`
*   `dominoes[i]` is either `'L'`, `'R'`, or `'.'`.

## A solution in Java

```java
public String pushDominoes(String dominoes) {
    int n = dominoes.length();
    int[] forces = new int[n];

    int force = 0;
    for (int i = 0; i < n; ++i) {
        if (dominoes.charAt(i) == 'R') force = n;
        else if (dominoes.charAt(i) == 'L') force = 0;
        else force = Math.max(force - 1, 0);
        forces[i] += force;
    }

    force = 0;
    for (int i = n - 1; i >= 0; --i) {
        if (dominoes.charAt(i) == 'L') force = n;
        else if (dominoes.charAt(i) == 'R') force = 0;
        else force = Math.max(force - 1, 0);
        forces[i] -= force;
    }

    StringBuilder result = new StringBuilder();
    for (int f : forces) {
        if (f > 0) result.append('R');
        else if (f < 0) result.append('L');
        else result.append('.');
    }

    return result.toString();
}
```
We will use two-pass mechanism:
1. Pass from left to right - calculate the force exerted by 'R' dominoes to 'L' dominoes.
2. Pass from right to left - calculate the force exerted by 'L' dominoes to 'R' dominoes and subtract it from the previous force (from pass 1)
3. Use the final force information to output the final state of dominoes:
    - if force > 0, it's 'R'
    - if force < 0, it's 'L'
    - if force == 0, it's '.'

## A solution in C++

```cpp
string pushDominoes(string dominoes) {
    int n = dominoes.size();
    vector<int> forces(n, 0);

    int force = 0;
    for (int i = 0; i < n; ++i) {
        if (dominoes[i] == 'R') force = n;
        else if (dominoes[i] == 'L') force = 0;
        else force = max(force - 1, 0);
        forces[i] += force;
    }

    force = 0;
    for (int i = n - 1; i >= 0; --i) {
        if (dominoes[i] == 'L') force = n;
        else if (dominoes[i] == 'R') force = 0;
        else force = max(force - 1, 0);
        forces[i] -= force;
    }

    string result = "";
    for (int force : forces) {
        if (force > 0) result += 'R';
        else if (force < 0) result += 'L';
        else result += '.';
    }

    return result;
}
```
We will use two-pass mechanism:
1. Pass from left to right - calculate the force exerted by 'R' dominoes to 'L' dominoes.
2. Pass from right to left - calculate the force exerted by 'L' dominoes to 'R' dominoes and subtract it from the previous force (from pass 1)
3. Use the final force information to output the final state of dominoes:
    - if force > 0, it's 'R'
    - if force < 0, it's 'L'
    - if force == 0, it's '.'

## A solution in Python

```python
def pushDominoes(dominoes: str) -> str:
    n = len(dominoes)
    forces = [0] * n

    force = 0
    for i in range(n):
        if dominoes[i] == 'R':
            force = n
        elif dominoes[i] == 'L':
            force = 0
        else:
            force = max(force - 1, 0)
        forces[i] += force

    force = 0
    for i in range(n - 1, -1, -1):
        if dominoes[i] == 'L':
            force = n
        elif dominoes[i] == 'R':
            force = 0
        else:
            force = max(force - 1, 0)
        forces[i] -= force

    return "".join(['R' if f > 0 else 'L' if f < 0 else '.' for f in forces])
```
We will use two-pass mechanism:
1. Pass from left to right - calculate the force exerted by 'R' dominoes to 'L' dominoes.
2. Pass from right to left - calculate the force exerted by 'L' dominoes to 'R' dominoes and subtract it from the previous force (from pass 1)
3. Use the final force information to output the final state of dominoes:
    - if force > 0, it's 'R'
    - if force < 0, it's 'L'
    - if force == 0, it's '.'

## A solution in Javascript

```javascript
function pushDominoes(dominoes) {
    const n = dominoes.length;
    const forces = new Array(n).fill(0);

    let force = 0;
    for (let i = 0; i < n; ++i) {
        if (dominoes[i] === 'R') force = n;
        else if (dominoes[i] === 'L') force = 0;
        else force = Math.max(force - 1, 0);
        forces[i] += force;
    }

    force = 0;
    for (let i = n - 1; i >= 0; --i) {
        if (dominoes[i] === 'L') force = n;
        else if (dominoes[i] === 'R') force = 0;
        else force = Math.max(force - 1, 0);
        forces[i] -= force;
    }

    return forces.map(f => f > 0 ? 'R' : f < 0 ? 'L' : '.').join('');
}
```
We will use two-pass mechanism:
1. Pass from left to right - calculate the force exerted by 'R' dominoes to 'L' dominoes.
2. Pass from right to left - calculate the force exerted by 'L' dominoes to 'R' dominoes and subtract it from the previous force (from pass 1)
3. Use the final force information to output the final state of dominoes:
    - if force > 0, it's 'R'
    - if force < 0, it's 'L'
    - if force == 0, it's '.'


# Similar String Groups

- slug: similar-string-groups
- difficulty: Hard

Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal.

For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "` is not similar to `"tars "`, `"rats "`, or `"arts "`.

Together, these form two connected groups by similarity: `{ "tars ", "rats ", "arts "}` and `{ "star "}`. Notice that `"tars "` and `"arts "` are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.

We are given a list `strs` of strings where every string in `strs` is an anagram of every other string in `strs`. How many groups are there?

**Example 1:**

**Input:** strs = \[ "tars ", "rats ", "arts ", "star "\]
**Output:** 2

**Example 2:**

**Input:** strs = \[ "omv ", "ovm "\]
**Output:** 1

**Constraints:**

*   `1 <= strs.length <= 300`
*   `1 <= strs[i].length <= 300`
*   `strs[i]` consists of lowercase letters only.
*   All words in `strs` have the same length and are anagrams of each other.

## A solution in Java

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

public int minimalLengthEncoding(String[] words) {
    Set<String> wordSet = new HashSet<>();
    for (String word : words) {
        wordSet.add(word);
    }

    for (String word : words) {
        for (int i = 1; i < word.length(); i++) {
            wordSet.remove(word.substring(i));
        }
    }

    int len = 0;
    for (String word : wordSet) {
        len += word.length() + 1;
    }
    return len;
}
```
The algorithm starts by initializing a set, `wordSet`, containing all unique words in the input array `words`. Next, for each word in the input array, we iterate over its suffixes (i.e., the substring from a given index to the end of the string) and remove them from the set.

At the end of the iterations, the set `wordSet` will contain only the shortest unique suffix of each word. We then calculate the total length of the elements in the set plus the special character ('#') that separates them, which results in the length of the shortest reference string.

The algorithm's time complexity is O(N * M²), where N is the number of words and M is the max length of a word, and its space complexity is O(N * M).

## A solution in C++

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

int minimal_length_encoding(const std::vector<std::string>& words) {
    std::unordered_set<std::string> word_set(words.begin(), words.end());

    for (const std::string& word : words) {
        for (int i = 1; i < word.size(); ++i) {
            word_set.erase(word.substr(i));
        }
    }

    int len = 0;
    for (const std::string& word : word_set) {
        len += word.size() + 1;
    }
    return len;
}
```
The algorithm starts by initializing a set, `wordSet`, containing all unique words in the input array `words`. Next, for each word in the input array, we iterate over its suffixes (i.e., the substring from a given index to the end of the string) and remove them from the set.

At the end of the iterations, the set `wordSet` will contain only the shortest unique suffix of each word. We then calculate the total length of the elements in the set plus the special character ('#') that separates them, which results in the length of the shortest reference string.

The algorithm's time complexity is O(N * M²), where N is the number of words and M is the max length of a word, and its space complexity is O(N * M).

## A solution in Python

```python
def minimal_length_encoding(words):
    word_set = set(words)

    for word in words:
        for i in range(1, len(word)):
            word_set.discard(word[i:])

    return sum(len(word) + 1 for word in word_set)
```
The algorithm starts by initializing a set, `wordSet`, containing all unique words in the input array `words`. Next, for each word in the input array, we iterate over its suffixes (i.e., the substring from a given index to the end of the string) and remove them from the set.

At the end of the iterations, the set `wordSet` will contain only the shortest unique suffix of each word. We then calculate the total length of the elements in the set plus the special character ('#') that separates them, which results in the length of the shortest reference string.

The algorithm's time complexity is O(N * M²), where N is the number of words and M is the max length of a word, and its space complexity is O(N * M).

## A solution in Javascript

```javascript
function minimalLengthEncoding(words) {
    const wordSet = new Set(words);

    for (const word of words) {
        for (let i = 1; i < word.length; i++) {
            wordSet.delete(word.slice(i));
        }
    }

    let len = 0;
    for (const word of wordSet) {
        len += word.length + 1;
    }
    return len;
}
```
The algorithm starts by initializing a set, `wordSet`, containing all unique words in the input array `words`. Next, for each word in the input array, we iterate over its suffixes (i.e., the substring from a given index to the end of the string) and remove them from the set.

At the end of the iterations, the set `wordSet` will contain only the shortest unique suffix of each word. We then calculate the total length of the elements in the set plus the special character ('#') that separates them, which results in the length of the shortest reference string.

The algorithm's time complexity is O(N * M²), where N is the number of words and M is the max length of a word, and its space complexity is O(N * M).


# Magic Squares In Grid

- slug: magic-squares-in-grid
- difficulty: Medium

A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum.

Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous).

**Example 1:**

**Input:** grid = \[\[4,3,8,4\],\[9,5,1,9\],\[2,7,6,2\]\]
**Output:** 1
**Explanation:**
The following subgrid is a 3 x 3 magic square:

while this one is not:

In total, there is only one magic square inside the given grid.

**Example 2:**

**Input:** grid = \[\[8\]\]
**Output:** 0

**Constraints:**

*   `row == grid.length`
*   `col == grid[i].length`
*   `1 <= row, col <= 10`
*   `0 <= grid[i][j] <= 15`

## A solution in Java

```java
public int numMagicSquaresInside(int[][] grid) {
    int count = 0;
    for (int i = 0; i < grid.length - 2; ++i) {
        for (int j = 0; j < grid[0].length - 2; ++j) {
            if (grid[i][j] <= 9 && grid[i + 1][j + 1] == 5 && isMagic(grid, i, j)) {
                count++;
            }
        }
    }
    return count;
}

private boolean isMagic(int[][] grid, int x, int y) {
    int[] temp = new int[16];
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            int num = grid[x + i][y + j];
            temp[num]++;
            if (num > 9 || temp[num] > 1) {
                return false;
            }
        }
    }
    int sum = grid[x][y] + grid[x][y+1] + grid[x][y+2];
    for (int i = 0; i < 3; ++i) {
        int rowSum = 0, colSum = 0;
        for (int j = 0; j < 3; ++j) {
            rowSum += grid[x + i][y + j];
            colSum += grid[x + j][y + i];
        }
        if (rowSum != sum || colSum != sum)
            return false;
    }
    if (grid[x][y] + grid[x + 1][y + 1] + grid[x + 2][y + 2] != sum)
        return false;
    if (grid[x][y + 2] + grid[x + 1][y + 1] + grid[x + 2][y] != sum)
        return false;

    return true;
}
```
1. Traverse the grid using nested loops, make sure the iterations will end before the boundaries.
2. Check the cell value at each position, if it satisfies the constraints and has a center of 5, otherwise it can't be the magic square.
3. Create a function to check if the subgrid is a magic square, it will check the sum of each row, col, and diagonal.
4. In the checking magic function, it will maintain a count array initialized with 16 zeros. Count and check the values for each cell in subgrid, if the value is less than or equal to 9 and count of the value is less than 2, otherwise return false.
5. Calculate the sum of each row and column and compare it with the pre-calculated sum. If any sum is not matching, return false.
6. Check the sums of both diagonals; if they don't match the pre-calculated sum, return false.
7. If all checks pass, return true.
8. For each subgrid, if it's a magic square, increment the count.
9. Return the count after traversing all subgrids.

## A solution in C++

```cpp
int numMagicSquaresInside(vector<vector<int>>& grid) {
    int count = 0;
    for (int i = 0; i < grid.size() - 2; ++i) {
        for (int j = 0; j < grid[0].size() - 2; ++j) {
            if (grid[i][j] <= 9 && grid[i + 1][j + 1] == 5 && isMagic(grid, i, j)) {
                count++;
            }
        }
    }
    return count;
}

bool isMagic(vector<vector<int>>& grid, int x, int y) {
    vector<int> temp(16, 0);
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            int num = grid[x + i][y + j];
            temp[num]++;
            if (num > 9 || temp[num] > 1) {
                return false;
            }
        }
    }
    int sum = grid[x][y] + grid[x][y+1] + grid[x][y+2];
    for (int i = 0; i < 3; ++i) {
        int rowSum = 0, colSum = 0;
        for (int j = 0; j < 3; ++j) {
            rowSum += grid[x + i][y + j];
            colSum += grid[x + j][y + i];
        }
        if (rowSum != sum || colSum != sum)
            return false;
    }
    if (grid[x][y] + grid[x + 1][y + 1] + grid[x + 2][y + 2] != sum)
        return false;
    if (grid[x][y + 2] + grid[x + 1][y + 1] + grid[x + 2][y] != sum)
        return false;

    return true;
}
```
1. Traverse the grid using nested loops, make sure the iterations will end before the boundaries.
2. Check the cell value at each position, if it satisfies the constraints and has a center of 5, otherwise it can't be the magic square.
3. Create a function to check if the subgrid is a magic square, it will check the sum of each row, col, and diagonal.
4. In the checking magic function, it will maintain a count array initialized with 16 zeros. Count and check the values for each cell in subgrid, if the value is less than or equal to 9 and count of the value is less than 2, otherwise return false.
5. Calculate the sum of each row and column and compare it with the pre-calculated sum. If any sum is not matching, return false.
6. Check the sums of both diagonals; if they don't match the pre-calculated sum, return false.
7. If all checks pass, return true.
8. For each subgrid, if it's a magic square, increment the count.
9. Return the count after traversing all subgrids.

## A solution in Python

```python
def numMagicSquaresInside(grid):
    count = 0
    for i in range(len(grid) - 2):
        for j in range(len(grid[0]) - 2):
            if grid[i][j] <= 9 and grid[i + 1][j + 1] == 5 and isMagic(grid, i, j):
                count += 1
    return count

def isMagic(grid, x, y):
    temp = [0] * 16
    for i in range(3):
        for j in range(3):
            num = grid[x + i][y + j]
            temp[num] += 1
            if num > 9 or temp[num] > 1:
                return False

    _sum = grid[x][y] + grid[x][y+1] + grid[x][y+2]
    for i in range(3):
        row_sum, col_sum = 0, 0
        for j in range(3):
            row_sum += grid[x + i][y + j]
            col_sum += grid[x + j][y + i]
        if row_sum != _sum or col_sum != _sum:
            return False

    if grid[x][y] + grid[x + 1][y + 1] + grid[x + 2][y + 2] != _sum:
        return False
    if grid[x][y + 2] + grid[x + 1][y + 1] + grid[x + 2][y] != _sum:
        return False

    return True
```
1. Traverse the grid using nested loops, make sure the iterations will end before the boundaries.
2. Check the cell value at each position, if it satisfies the constraints and has a center of 5, otherwise it can't be the magic square.
3. Create a function to check if the subgrid is a magic square, it will check the sum of each row, col, and diagonal.
4. In the checking magic function, it will maintain a count array initialized with 16 zeros. Count and check the values for each cell in subgrid, if the value is less than or equal to 9 and count of the value is less than 2, otherwise return false.
5. Calculate the sum of each row and column and compare it with the pre-calculated sum. If any sum is not matching, return false.
6. Check the sums of both diagonals; if they don't match the pre-calculated sum, return false.
7. If all checks pass, return true.
8. For each subgrid, if it's a magic square, increment the count.
9. Return the count after traversing all subgrids.

## A solution in Javascript

```javascript
var numMagicSquaresInside = function(grid) {
    let count = 0;
    for (let i = 0; i < grid.length - 2; ++i) {
        for (let j = 0; j < grid[0].length - 2; ++j) {
            if (grid[i][j] <= 9 && grid[i + 1][j + 1] === 5 && isMagic(grid, i, j)) {
                count++;
            }
        }
    }
    return count;
};

function isMagic(grid, x, y) {
    let temp = Array(16).fill(0);
    for (let i = 0; i < 3; ++i) {
        for (let j = 0; j < 3; ++j) {
            let num = grid[x + i][y + j];
            temp[num]++;
            if (num > 9 || temp[num] > 1) {
                return false;
            }
        }
    }
    let sum = grid[x][y] + grid[x][y+1] + grid[x][y+2];
    for (let i = 0; i < 3; ++i) {
        let rowSum = 0, colSum = 0;
        for (let j = 0; j < 3; ++j) {
            rowSum += grid[x + i][y + j];
            colSum += grid[x + j][y + i];
        }
        if (rowSum !== sum || colSum !== sum)
            return false;
    }
    if (grid[x][y] + grid[x + 1][y + 1] + grid[x + 2][y + 2] !== sum)
        return false;
    if (grid[x][y + 2] + grid[x + 1][y + 1] + grid[x + 2][y] !== sum)
        return false;

    return true;
}
```
1. Traverse the grid using nested loops, make sure the iterations will end before the boundaries.
2. Check the cell value at each position, if it satisfies the constraints and has a center of 5, otherwise it can't be the magic square.
3. Create a function to check if the subgrid is a magic square, it will check the sum of each row, col, and diagonal.
4. In the checking magic function, it will maintain a count array initialized with 16 zeros. Count and check the values for each cell in subgrid, if the value is less than or equal to 9 and count of the value is less than 2, otherwise return false.
5. Calculate the sum of each row and column and compare it with the pre-calculated sum. If any sum is not matching, return false.
6. Check the sums of both diagonals; if they don't match the pre-calculated sum, return false.
7. If all checks pass, return true.
8. For each subgrid, if it's a magic square, increment the count.
9. Return the count after traversing all subgrids.


# Keys and Rooms

- slug: keys-and-rooms
- difficulty: Medium

There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

Given an array `rooms` where `rooms[i]` is the set of keys that you can obtain if you visited room `i`, return `true` _if you can visit **all** the rooms, or_ `false` _otherwise_.

**Example 1:**

**Input:** rooms = \[\[1\],\[2\],\[3\],\[\]\]
**Output:** true
**Explanation:**
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.

**Example 2:**

**Input:** rooms = \[\[1,3\],\[3,0,1\],\[2\],\[0\]\]
**Output:** false
**Explanation:** We can not enter room number 2 since the only key that unlocks it is in that room.

**Constraints:**

*   `n == rooms.length`
*   `2 <= n <= 1000`
*   `0 <= rooms[i].length <= 1000`
*   `1 <= sum(rooms[i].length) <= 3000`
*   `0 <= rooms[i][j] < n`
*   All the values of `rooms[i]` are **unique**.

## A solution in Java

```java
public int[] shortestToChar(String s, char c) {
    int n = s.length();
    int[] result = new int[n];

    int pos = -n;
    for (int i = 0; i < n; ++i) {
        if (s.charAt(i) == c)
            pos = i;
        result[i] = i - pos;
    }

    for (int i = pos - 1; i >= 0; --i) {
        if (s.charAt(i) == c)
            pos = i;
        result[i] = Math.min(result[i], pos - i);
    }

    return result;
}
```
The algorithm for this problem consists of the following steps:

1. Initialize a vector/array with length equal to the length of the input string `s`. This will store the final output result.
2. Set an initial value for position `pos` as a negative of the length of the input string `s`. This value indicates the position of the character `c` found in the string.
3. Iterate over the string from left to right. If the current character is equal to the character `c`, update the position `pos`. Then, update the result vector/array with the distance between the current index and the position `pos`.
4. Iterate over the string from right to left. If the current character is equal to the character `c`, update the position `pos`. Then, update the result vector/array with the minimum of the current value and the distance between the position `pos` and the current index.
5. Return the result vector/array.

## A solution in C++

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

std::vector<int> shortestToChar(const std::string& s, char c) {
    int n = s.size();
    std::vector<int> result(n, n);

    int pos = -n;
    for (int i = 0; i < n; ++i) {
        if (s[i] == c)
            pos = i;
        result[i] = i - pos;
    }

    for (int i = pos - 1; i >= 0; --i) {
        if (s[i] == c)
            pos = i;
        result[i] = std::min(result[i], pos - i);
    }

    return result;
}
```
The algorithm for this problem consists of the following steps:

1. Initialize a vector/array with length equal to the length of the input string `s`. This will store the final output result.
2. Set an initial value for position `pos` as a negative of the length of the input string `s`. This value indicates the position of the character `c` found in the string.
3. Iterate over the string from left to right. If the current character is equal to the character `c`, update the position `pos`. Then, update the result vector/array with the distance between the current index and the position `pos`.
4. Iterate over the string from right to left. If the current character is equal to the character `c`, update the position `pos`. Then, update the result vector/array with the minimum of the current value and the distance between the position `pos` and the current index.
5. Return the result vector/array.

## A solution in Python

```python
def shortestToChar(s, c):
    n = len(s)
    result = [n for _ in range(n)]
    pos = -n

    for i in range(n):
        if s[i] == c:
            pos = i
        result[i] = i - pos

    for i in range(pos - 1, -1, -1):
        if s[i] == c:
            pos = i
        result[i] = min(result[i], pos - i)

    return result
```
The algorithm for this problem consists of the following steps:

1. Initialize a vector/array with length equal to the length of the input string `s`. This will store the final output result.
2. Set an initial value for position `pos` as a negative of the length of the input string `s`. This value indicates the position of the character `c` found in the string.
3. Iterate over the string from left to right. If the current character is equal to the character `c`, update the position `pos`. Then, update the result vector/array with the distance between the current index and the position `pos`.
4. Iterate over the string from right to left. If the current character is equal to the character `c`, update the position `pos`. Then, update the result vector/array with the minimum of the current value and the distance between the position `pos` and the current index.
5. Return the result vector/array.

## A solution in Javascript

```javascript
function shortestToChar(s, c) {
    const n = s.length;
    const result = new Array(n).fill(n);
    let pos = -n;

    for (let i = 0; i < n; ++i) {
        if (s.charAt(i) === c)
            pos = i;
        result[i] = i - pos;
    }

    for (let i = pos - 1; i >= 0; --i) {
        if (s.charAt(i) !== c)
            pos = i;
        result[i] = Math.min(result[i], pos - i);
    }

    return result;
}
```
The algorithm for this problem consists of the following steps:

1. Initialize a vector/array with length equal to the length of the input string `s`. This will store the final output result.
2. Set an initial value for position `pos` as a negative of the length of the input string `s`. This value indicates the position of the character `c` found in the string.
3. Iterate over the string from left to right. If the current character is equal to the character `c`, update the position `pos`. Then, update the result vector/array with the distance between the current index and the position `pos`.
4. Iterate over the string from right to left. If the current character is equal to the character `c`, update the position `pos`. Then, update the result vector/array with the minimum of the current value and the distance between the position `pos` and the current index.
5. Return the result vector/array.


# Split Array into Fibonacci Sequence

- slug: split-array-into-fibonacci-sequence
- difficulty: Medium

You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`.

Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that:

*   `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type),
*   `f.length >= 3`, and
*   `f[i] + f[i + 1] == f[i + 2]` for all `0 <= i < f.length - 2`.

Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number `0` itself.

Return any Fibonacci-like sequence split from `num`, or return `[]` if it cannot be done.

**Example 1:**

**Input:** num =  "1101111 "
**Output:** \[11,0,11,11\]
**Explanation:** The output \[110, 1, 111\] would also be accepted.

**Example 2:**

**Input:** num =  "112358130 "
**Output:** \[\]
**Explanation:** The task is impossible.

**Example 3:**

**Input:** num =  "0123 "
**Output:** \[\]
**Explanation:** Leading zeroes are not allowed, so  "01 ",  "2 ",  "3 " is not valid.

**Constraints:**

*   `1 <= num.length <= 200`
*   `num` contains only digits.

## A solution in Java

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

public int smallestGoodInteger(int[] fronts, int[] backs) {
    Set<Integer> notGood = new HashSet<>();
    int n = fronts.length;
    for (int i = 0; i < n; ++i)
        if (fronts[i] == backs[i]) notGood.add(fronts[i]);

    int result = Integer.MAX_VALUE;
    for (int i = 0; i < n; ++i) {
        if (!notGood.contains(fronts[i])) result = Math.min(result, fronts[i]);
        if (!notGood.contains(backs[i])) result = Math.min(result, backs[i]);
    }
    return result == Integer.MAX_VALUE ? 0 : result;
}
```
1. Create a set called "notGood" to store numbers that are not good according to the problem statement.
2. Iterate through both "fronts" and "backs" arrays. If an element in "fronts" is equal to the corresponding element in "backs", add the element to "notGood" set.
3. Initialize a variable "result" to store the smallest good integer found. Set its initial value to the maximum possible value of that data type.
4. Iterate through "fronts" and "backs" arrays again. Compare each element with the numbers in the "notGood" set. If an element is not in "notGood", update the "result" with the minimum value between the current "result" and the element.
5. Return the final "result" if it's not equal to the maximum possible value of that data type, otherwise return 0.

## A solution in C++

```cpp
#include <set>
#include <algorithm>

int smallestGoodInteger(std::vector<int>& fronts, std::vector<int>& backs) {
    std::set<int> notGood;
    int n = fronts.size();
    for (int i = 0; i < n; ++i)
        if (fronts[i] == backs[i]) notGood.insert(fronts[i]);

    int result = INT_MAX;
    for (int i = 0; i < n; ++i) {
        if (!notGood.count(fronts[i])) result = std::min(result, fronts[i]);
        if (!notGood.count(backs[i])) result = std::min(result, backs[i]);
    }
    return result == INT_MAX ? 0 : result;
}
```
1. Create a set called "notGood" to store numbers that are not good according to the problem statement.
2. Iterate through both "fronts" and "backs" arrays. If an element in "fronts" is equal to the corresponding element in "backs", add the element to "notGood" set.
3. Initialize a variable "result" to store the smallest good integer found. Set its initial value to the maximum possible value of that data type.
4. Iterate through "fronts" and "backs" arrays again. Compare each element with the numbers in the "notGood" set. If an element is not in "notGood", update the "result" with the minimum value between the current "result" and the element.
5. Return the final "result" if it's not equal to the maximum possible value of that data type, otherwise return 0.

## A solution in Python

```python
def smallest_good_integer(fronts, backs):
    not_good = {fronts[i] for i in range(len(fronts)) if fronts[i] == backs[i]}

    result = float('inf')
    for i in range(len(fronts)):
        if fronts[i] not in not_good:
            result = min(result, fronts[i])
        if backs[i] not in not_good:
            result = min(result, backs[i])

    return 0 if result == float('inf') else result
```
1. Create a set called "notGood" to store numbers that are not good according to the problem statement.
2. Iterate through both "fronts" and "backs" arrays. If an element in "fronts" is equal to the corresponding element in "backs", add the element to "notGood" set.
3. Initialize a variable "result" to store the smallest good integer found. Set its initial value to the maximum possible value of that data type.
4. Iterate through "fronts" and "backs" arrays again. Compare each element with the numbers in the "notGood" set. If an element is not in "notGood", update the "result" with the minimum value between the current "result" and the element.
5. Return the final "result" if it's not equal to the maximum possible value of that data type, otherwise return 0.

## A solution in Javascript

```javascript
function smallestGoodInteger(fronts, backs) {
    const notGood = new Set();
    const n = fronts.length;
    for (let i = 0; i < n; ++i)
        if (fronts[i] === backs[i]) notGood.add(fronts[i]);

    let result = Infinity;
    for (let i = 0; i < n; ++i) {
        if (!notGood.has(fronts[i])) result = Math.min(result, fronts[i]);
        if (!notGood.has(backs[i])) result = Math.min(result, backs[i]);
    }
    return result === Infinity ? 0 : result;
}
```
1. Create a set called "notGood" to store numbers that are not good according to the problem statement.
2. Iterate through both "fronts" and "backs" arrays. If an element in "fronts" is equal to the corresponding element in "backs", add the element to "notGood" set.
3. Initialize a variable "result" to store the smallest good integer found. Set its initial value to the maximum possible value of that data type.
4. Iterate through "fronts" and "backs" arrays again. Compare each element with the numbers in the "notGood" set. If an element is not in "notGood", update the "result" with the minimum value between the current "result" and the element.
5. Return the final "result" if it's not equal to the maximum possible value of that data type, otherwise return 0.


# Guess the Word

- slug: guess-the-word
- difficulty: Hard

You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word.

You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns:

*   `-1` if `word` is not from `words`, or
*   an integer representing the number of exact matches (value and position) of your guess to the secret word.

There is a parameter `allowedGuesses` for each test case where `allowedGuesses` is the maximum number of times you can call `Master.guess(word)`.

For each test case, you should call `Master.guess` with the secret word without exceeding the maximum number of allowed guesses. You will get:

*   **`"Either you took too many guesses, or you did not find the secret word. "`** if you called `Master.guess` more than `allowedGuesses` times or if you did not call `Master.guess` with the secret word, or
*   **`"You guessed the secret word correctly. "`** if you called `Master.guess` with the secret word with the number of calls to `Master.guess` less than or equal to `allowedGuesses`.

The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method).

**Example 1:**

**Input:** secret =  "acckzz ", words = \[ "acckzz ", "ccbazz ", "eiowzz ", "abcczz "\], allowedGuesses = 10
**Output:** You guessed the secret word correctly.
**Explanation:**
master.guess( "aaaaaa ") returns -1, because  "aaaaaa " is not in wordlist.
master.guess( "acckzz ") returns 6, because  "acckzz " is secret and has all 6 matches.
master.guess( "ccbazz ") returns 3, because  "ccbazz " has 3 matches.
master.guess( "eiowzz ") returns 2, because  "eiowzz " has 2 matches.
master.guess( "abcczz ") returns 4, because  "abcczz " has 4 matches.
We made 5 calls to master.guess, and one of them was the secret, so we pass the test case.

**Example 2:**

**Input:** secret =  "hamada ", words = \[ "hamada ", "khaled "\], allowedGuesses = 10
**Output:** You guessed the secret word correctly.
**Explanation:** Since there are two words, you can guess both.

**Constraints:**

*   `1 <= words.length <= 100`
*   `words[i].length == 6`
*   `words[i]` consist of lowercase English letters.
*   All the strings of `wordlist` are **unique**.
*   `secret` exists in `words`.
*   `10 <= allowedGuesses <= 30`

## A solution in Java

```java
public int numFactoredBinaryTrees(int[] arr) {
    int MOD = 1_000_000_007;
    int n = arr.length;
    Arrays.sort(arr);
    HashMap<Integer, Long> dp = new HashMap<>();
    for (int i = 0; i < n; ++i) {
        dp.put(arr[i], 1L);
        for (int j = 0; j < i; ++j) {
            if (arr[i] % arr[j] == 0 && dp.containsKey(arr[i] / arr[j]))
                dp.put(arr[i], (dp.get(arr[i]) + dp.get(arr[j]) * dp.get(arr[i] / arr[j])) % MOD);
        }
    }
    long ans = 0;
    for (Long value : dp.values()) ans = (ans + value) % MOD;
    return (int) ans;
}
```
To solve this problem, we use dynamic programming. The key insight is to recognize that the count of trees we can make with a certain root value is equal to the product of the count of trees using its possible children.

1. Sort the input array so that we can iterate through it in ascending order.
2. Initialize a hash map `dp` for dynamic programming, where the key is an element in the array and the value is the count of trees we can create using that element as root.
3. For each element `x` in the array, we start with a count of 1 because there's always a possibility of having a tree with just the root.
4. For each smaller element `y` in the array, if `x` is divisible by `y` (i.e., `x % y == 0`), we check if there's another element `z` in the array such that `y * z == x`. If so, we update the count of trees for `x` as `dp[x] + dp[y] * dp[z]` in a modulo manner.
5. The answer would be the sum of all counts in the `dp` hash map.

## A solution in C++

```cpp
int numFactoredBinaryTrees(vector<int>& arr) {
    long long MOD = 1e9 + 7;
    int n = arr.size();
    sort(arr.begin(), arr.end());
    unordered_map<int, long long> dp;
    for (int i = 0; i < n; ++i) {
        dp[arr[i]] = 1;
        for (int j = 0; j < i; ++j) {
            if (arr[i] % arr[j] == 0 && dp.count(arr[i] / arr[j]))
                dp[arr[i]] = (dp[arr[i]] + dp[arr[j]] * dp[arr[i] / arr[j]]) % MOD;
        }
    }
    long long ans = 0;
    for (const auto& it : dp) ans = (ans + it.second) % MOD;
    return ans;
}
```
To solve this problem, we use dynamic programming. The key insight is to recognize that the count of trees we can make with a certain root value is equal to the product of the count of trees using its possible children.

1. Sort the input array so that we can iterate through it in ascending order.
2. Initialize a hash map `dp` for dynamic programming, where the key is an element in the array and the value is the count of trees we can create using that element as root.
3. For each element `x` in the array, we start with a count of 1 because there's always a possibility of having a tree with just the root.
4. For each smaller element `y` in the array, if `x` is divisible by `y` (i.e., `x % y == 0`), we check if there's another element `z` in the array such that `y * z == x`. If so, we update the count of trees for `x` as `dp[x] + dp[y] * dp[z]` in a modulo manner.
5. The answer would be the sum of all counts in the `dp` hash map.

## A solution in Python

```python
def numFactoredBinaryTrees(arr):
    MOD = 10**9 + 7
    n = len(arr)
    arr.sort()
    dp = {}
    for i, x in enumerate(arr):
        dp[x] = 1
        for y in arr[:i]:
            if x % y == 0 and x // y in dp:
                dp[x] = (dp[x] + dp[y] * dp[x // y]) % MOD
    return sum(dp.values()) % MOD
```
To solve this problem, we use dynamic programming. The key insight is to recognize that the count of trees we can make with a certain root value is equal to the product of the count of trees using its possible children.

1. Sort the input array so that we can iterate through it in ascending order.
2. Initialize a hash map `dp` for dynamic programming, where the key is an element in the array and the value is the count of trees we can create using that element as root.
3. For each element `x` in the array, we start with a count of 1 because there's always a possibility of having a tree with just the root.
4. For each smaller element `y` in the array, if `x` is divisible by `y` (i.e., `x % y == 0`), we check if there's another element `z` in the array such that `y * z == x`. If so, we update the count of trees for `x` as `dp[x] + dp[y] * dp[z]` in a modulo manner.
5. The answer would be the sum of all counts in the `dp` hash map.

## A solution in Javascript

```javascript
function numFactoredBinaryTrees(arr) {
    const MOD = 1e9 + 7;
    const n = arr.length;
    arr.sort((a, b) => a - b);
    let dp = new Map();
    for (let i = 0; i < n; ++i) {
        dp.set(arr[i], 1);
        for (let j = 0; j < i; ++j) {
            if (arr[i] % arr[j] === 0 && dp.has(arr[i] / arr[j]))
                dp.set(arr[i], (dp.get(arr[i]) + dp.get(arr[j]) * dp.get(arr[i] / arr[j])) % MOD);
        }
    }
    let ans = 0;
    for (const value of dp.values()) ans = (ans + value) % MOD;
    return ans;
}
```
To solve this problem, we use dynamic programming. The key insight is to recognize that the count of trees we can make with a certain root value is equal to the product of the count of trees using its possible children.

1. Sort the input array so that we can iterate through it in ascending order.
2. Initialize a hash map `dp` for dynamic programming, where the key is an element in the array and the value is the count of trees we can create using that element as root.
3. For each element `x` in the array, we start with a count of 1 because there's always a possibility of having a tree with just the root.
4. For each smaller element `y` in the array, if `x` is divisible by `y` (i.e., `x % y == 0`), we check if there's another element `z` in the array such that `y * z == x`. If so, we update the count of trees for `x` as `dp[x] + dp[y] * dp[z]` in a modulo manner.
5. The answer would be the sum of all counts in the `dp` hash map.


# Backspace String Compare

- slug: backspace-string-compare
- difficulty: Easy

Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character.

Note that after backspacing an empty text, the text will continue empty.

**Example 1:**

**Input:** s =  "ab#c ", t =  "ad#c "
**Output:** true
**Explanation:** Both s and t become  "ac ".

**Example 2:**

**Input:** s =  "ab## ", t =  "c#d# "
**Output:** true
**Explanation:** Both s and t become  " ".

**Example 3:**

**Input:** s =  "a#c ", t =  "b "
**Output:** false
**Explanation:** s becomes  "c " while t becomes  "b ".

**Constraints:**

*   `1 <= s.length, t.length <= 200`
*   `s` and `t` only contain lowercase letters and `'#'` characters.

**Follow up:** Can you solve it in `O(n)` time and `O(1)` space?

## A solution in Java

```java
public boolean backspaceCompare(String s, String t) {
    int i = s.length() - 1, j = t.length() - 1;
    while (true) {
        int back;
        for (back = 0; i >= 0 && (back > 0 || s.charAt(i) == '#'); --i)
            back += s.charAt(i) == '#' ? 1 : -1;
        for (back = 0; j >= 0 && (back > 0 || t.charAt(j) == '#'); --j)
            back += t.charAt(j) == '#' ? 1 : -1;
        if (i >= 0 && j >= 0 && s.charAt(i) == t.charAt(j))
            i--, j--;
        else
            return i == -1 && j == -1;
    }
}
```
The algorithm implements a two-pointer approach to compare the characters in the given strings `s` and `t`. We initialize two pointers `i` and `j` at the end of the respective strings. We use two nested loops to iterate through the characters from right to left, considering the backspace characters.

In both loops, we maintain a backspace counter. If we encounter a backspace character, we increment the counter. If we encounter a non-backspace character while the counter is greater than 0, we decrement the counter and continue. This effectively simulates the deletion of characters due to backspace.

We then compare the characters at positions `i` and `j`. If they are equal, we decrement both pointers. If they are not equal, we break the loop and check if both pointers are equal to -1, indicating that both strings are equal after considering backspaces. If both pointers are equal to -1, we return true; otherwise, we return false.

This algorithm has a time complexity of O(n), where n is the length of the input strings, and a space complexity of O(1) as we do not use any additional data structures.

## A solution in C++

```cpp
bool backspaceCompare(string s, string t) {
    int i = s.length() - 1, j = t.length() - 1;
    while (true) {
        int back;
        for (back = 0; i >= 0 && (back > 0 || s[i] == '#'); --i)
            back += s[i] == '#' ? 1 : -1;
        for (back = 0; j >= 0 && (back > 0 || t[j] == '#'); --j)
            back += t[j] == '#' ? 1 : -1;
        if (i >= 0 && j >= 0 && s[i] == t[j])
            i--, j--;
        else
            return i == -1 && j == -1;
    }
}
```
The algorithm implements a two-pointer approach to compare the characters in the given strings `s` and `t`. We initialize two pointers `i` and `j` at the end of the respective strings. We use two nested loops to iterate through the characters from right to left, considering the backspace characters.

In both loops, we maintain a backspace counter. If we encounter a backspace character, we increment the counter. If we encounter a non-backspace character while the counter is greater than 0, we decrement the counter and continue. This effectively simulates the deletion of characters due to backspace.

We then compare the characters at positions `i` and `j`. If they are equal, we decrement both pointers. If they are not equal, we break the loop and check if both pointers are equal to -1, indicating that both strings are equal after considering backspaces. If both pointers are equal to -1, we return true; otherwise, we return false.

This algorithm has a time complexity of O(n), where n is the length of the input strings, and a space complexity of O(1) as we do not use any additional data structures.

## A solution in Python

```python
def backspaceCompare(s: str, t: str) -> bool:
    i, j = len(s) - 1, len(t) - 1
    while True:
        back = 0
        while i >= 0 and (back > 0 or s[i] == '#'):
            back = back + 1 if s[i] == '#' else back - 1
            i -= 1
        back = 0
        while j >= 0 and (back > 0 or t[j] == '#'):
            back = back + 1 if t[j] == '#' else back - 1
            j -= 1
        if i >= 0 and j >= 0 and s[i] == t[j]:
            i, j = i -1, j - 1
        else:
            return i == -1 and j == -1
```
The algorithm implements a two-pointer approach to compare the characters in the given strings `s` and `t`. We initialize two pointers `i` and `j` at the end of the respective strings. We use two nested loops to iterate through the characters from right to left, considering the backspace characters.

In both loops, we maintain a backspace counter. If we encounter a backspace character, we increment the counter. If we encounter a non-backspace character while the counter is greater than 0, we decrement the counter and continue. This effectively simulates the deletion of characters due to backspace.

We then compare the characters at positions `i` and `j`. If they are equal, we decrement both pointers. If they are not equal, we break the loop and check if both pointers are equal to -1, indicating that both strings are equal after considering backspaces. If both pointers are equal to -1, we return true; otherwise, we return false.

This algorithm has a time complexity of O(n), where n is the length of the input strings, and a space complexity of O(1) as we do not use any additional data structures.

## A solution in Javascript

```javascript
var backspaceCompare = function(s, t) {
    let i = s.length - 1, j = t.length - 1;
    while (true) {
        let back;
        for (back = 0; i >= 0 && (back > 0 || s[i] === '#'); --i)
            back += s[i] === '#' ? 1 : -1;
        for (back = 0; j >= 0 && (back > 0 || t[j] === '#'); --j)
            back += t[j] === '#' ? 1 : -1;
        if (i >= 0 && j >= 0 && s[i] === t[j])
            i--, j--;
        else
            return i === -1 && j === -1;
    }
};
```
The algorithm implements a two-pointer approach to compare the characters in the given strings `s` and `t`. We initialize two pointers `i` and `j` at the end of the respective strings. We use two nested loops to iterate through the characters from right to left, considering the backspace characters.

In both loops, we maintain a backspace counter. If we encounter a backspace character, we increment the counter. If we encounter a non-backspace character while the counter is greater than 0, we decrement the counter and continue. This effectively simulates the deletion of characters due to backspace.

We then compare the characters at positions `i` and `j`. If they are equal, we decrement both pointers. If they are not equal, we break the loop and check if both pointers are equal to -1, indicating that both strings are equal after considering backspaces. If both pointers are equal to -1, we return true; otherwise, we return false.

This algorithm has a time complexity of O(n), where n is the length of the input strings, and a space complexity of O(1) as we do not use any additional data structures.


# Longest Mountain in Array

- slug: longest-mountain-in-array
- difficulty: Medium

You may recall that an array `arr` is a **mountain array** if and only if:

*   `arr.length >= 3`
*   There exists some index `i` (**0-indexed**) with `0 < i < arr.length - 1` such that:
    *   `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
    *   `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`

Given an integer array `arr`, return _the length of the longest subarray, which is a mountain_. Return `0` if there is no mountain subarray.

**Example 1:**

**Input:** arr = \[2,1,4,7,3,2,5\]
**Output:** 5
**Explanation:** The largest mountain is \[1,4,7,3,2\] which has length 5.

**Example 2:**

**Input:** arr = \[2,2,2\]
**Output:** 0
**Explanation:** There is no mountain.

**Constraints:**

*   `1 <= arr.length <= 104`
*   `0 <= arr[i] <= 104`

**Follow up:**

*   Can you solve it using only one pass?
*   Can you solve it in `O(1)` space?

## A solution in Java

```java
public int longestMountain(int[] arr) {
    int n = arr.length;
    int res = 0, up = 0, down = 0;

    for (int i = 1; i < n; ++i) {
        if ((down != 0 && arr[i - 1] < arr[i]) || arr[i - 1] == arr[i]) {
            up = down = 0;
        }

        if (arr[i - 1] < arr[i]) up++;
        if (arr[i - 1] > arr[i]) down++;

        if (up != 0 && down != 0) {
            res = Math.max(res, up + down + 1);
        }
    }
    return res;
}
```
The algorithm uses one pass with two pointers and maintains two counters, "up" and "down". It begins at the 1st index, iterating through the array. If the current element is greater than the previous, it increases the "up" counter; otherwise, if it's less than the previous, it increases the "down" counter. Every time a mountain is identified (when both "up" and "down" are non-zero), the maximum length is updated. If some conditions are met, such as a new ascending sequence interruption or equal adjacent elements, reset the "up" and "down" counters to zero. Finally, return the maximum length of a mountain subarray found.

This solution executes in O(n) time with O(1) space complexity.

## A solution in C++

```cpp
int longestMountain(vector<int>& arr) {
    int n = arr.size(), res = 0, up = 0, down = 0;

    for (int i = 1; i < n; ++i) {
        if (down && arr[i - 1] < arr[i] || arr[i - 1] == arr[i]) {
            up = down = 0;
        }

        up += arr[i - 1] < arr[i];
        down += arr[i - 1] > arr[i];

        if (up && down) {
            res = max(res, up + down + 1);
        }
    }
    return res;
}
```
The algorithm uses one pass with two pointers and maintains two counters, "up" and "down". It begins at the 1st index, iterating through the array. If the current element is greater than the previous, it increases the "up" counter; otherwise, if it's less than the previous, it increases the "down" counter. Every time a mountain is identified (when both "up" and "down" are non-zero), the maximum length is updated. If some conditions are met, such as a new ascending sequence interruption or equal adjacent elements, reset the "up" and "down" counters to zero. Finally, return the maximum length of a mountain subarray found.

This solution executes in O(n) time with O(1) space complexity.

## A solution in Python

```python
def longestMountain(arr):
    n = len(arr)
    res = up = down = 0

    for i in range(1, n):
        if (down and arr[i - 1] < arr[i]) or arr[i - 1] == arr[i]:
            up = down = 0

        up += arr[i - 1] < arr[i]
        down += arr[i - 1] > arr[i]

        if up and down:
            res = max(res, up + down + 1)

    return res
```
The algorithm uses one pass with two pointers and maintains two counters, "up" and "down". It begins at the 1st index, iterating through the array. If the current element is greater than the previous, it increases the "up" counter; otherwise, if it's less than the previous, it increases the "down" counter. Every time a mountain is identified (when both "up" and "down" are non-zero), the maximum length is updated. If some conditions are met, such as a new ascending sequence interruption or equal adjacent elements, reset the "up" and "down" counters to zero. Finally, return the maximum length of a mountain subarray found.

This solution executes in O(n) time with O(1) space complexity.

## A solution in Javascript

```javascript
function longestMountain(arr) {
    let n = arr.length, res = 0, up = 0, down = 0;

    for (let i = 1; i < n; ++i) {
        if (down && arr[i - 1] < arr[i] || arr[i - 1] == arr[i]) {
            up = down = 0;
        }

        if (arr[i - 1] < arr[i]) up++;
        if (arr[i - 1] > arr[i]) down++;

        if (up && down) {
            res = Math.max(res, up + down + 1);
        }
    }
    return res;
}
```
The algorithm uses one pass with two pointers and maintains two counters, "up" and "down". It begins at the 1st index, iterating through the array. If the current element is greater than the previous, it increases the "up" counter; otherwise, if it's less than the previous, it increases the "down" counter. Every time a mountain is identified (when both "up" and "down" are non-zero), the maximum length is updated. If some conditions are met, such as a new ascending sequence interruption or equal adjacent elements, reset the "up" and "down" counters to zero. Finally, return the maximum length of a mountain subarray found.

This solution executes in O(n) time with O(1) space complexity.


# Hand of Straights

- slug: hand-of-straights
- difficulty: Medium

Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size `groupSize`, and consists of `groupSize` consecutive cards.

Given an integer array `hand` where `hand[i]` is the value written on the `ith` card and an integer `groupSize`, return `true` if she can rearrange the cards, or `false` otherwise.

**Example 1:**

**Input:** hand = \[1,2,3,6,2,3,4,7,8\], groupSize = 3
**Output:** true
**Explanation:** Alice's hand can be rearranged as \[1,2,3\],\[2,3,4\],\[6,7,8\]

**Example 2:**

**Input:** hand = \[1,2,3,4,5\], groupSize = 4
**Output:** false
**Explanation:** Alice's hand can not be rearranged into groups of 4.

**Constraints:**

*   `1 <= hand.length <= 104`
*   `0 <= hand[i] <= 109`
*   `1 <= groupSize <= hand.length`

**Note:** This question is the same as 1296: [https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/](https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/)

## A solution in Java

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

public boolean isPossibleDivide(int[] hand, int groupSize) {
    Map<Integer, Integer> cardCount = new TreeMap<>();
    for (int card : hand) {
        cardCount.put(card, cardCount.getOrDefault(card, 0) + 1);
    }

    for (int card : cardCount.keySet()) {
        int count = cardCount.get(card);
        if (count > 0) {
            for (int i = 1; i < groupSize; ++i) {
                int tmp = cardCount.getOrDefault(card + i, 0) - count;
                if (tmp < 0) {
                    return false;
                }
                cardCount.put(card + i, tmp);
            }
        }
    }

    return true;
}
```
The algorithm counts the occurrence of each card value and stores it in a map. Then, it iterates through the sorted card values in the map. For each card with a count greater than 0, it checks if it can decrement the count for the next `groupSize - 1` card values by the current count without going below 0. If it's possible to do so for all card values, then the cards can be divided into groups of size `groupSize` with consecutive values.

The algorithm has a time complexity of O(n * log(n)) due to the sorting process, where n is the length of the hand array.

## A solution in C++

```cpp
#include <vector>
#include <map>

bool isPossibleDivide(std::vector<int>& hand, int groupSize) {
    std::map<int, int> cardCount;
    for (int card : hand) {
        cardCount[card]++;
    }

    for (auto it = cardCount.begin(); it != cardCount.end(); ++it) {
        if (it->second > 0) {
            int count = it->second;
            for (int i = 1; i < groupSize; ++i) {
                cardCount[it->first + i] -= count;
                if (cardCount[it->first + i] < 0) {
                    return false;
                }
            }
        }
    }

    return true;
}
```
The algorithm counts the occurrence of each card value and stores it in a map. Then, it iterates through the sorted card values in the map. For each card with a count greater than 0, it checks if it can decrement the count for the next `groupSize - 1` card values by the current count without going below 0. If it's possible to do so for all card values, then the cards can be divided into groups of size `groupSize` with consecutive values.

The algorithm has a time complexity of O(n * log(n)) due to the sorting process, where n is the length of the hand array.

## A solution in Python

```python
from collections import Counter

def is_possible_divide(hand, group_size):
    card_count = Counter(hand)

    for card in sorted(card_count):
        if card_count[card] > 0:
            count = card_count[card]
            for i in range(1, group_size):
                if card_count[card + i] < count:
                    return False
                card_count[card + i] -= count

    return True
```
The algorithm counts the occurrence of each card value and stores it in a map. Then, it iterates through the sorted card values in the map. For each card with a count greater than 0, it checks if it can decrement the count for the next `groupSize - 1` card values by the current count without going below 0. If it's possible to do so for all card values, then the cards can be divided into groups of size `groupSize` with consecutive values.

The algorithm has a time complexity of O(n * log(n)) due to the sorting process, where n is the length of the hand array.

## A solution in Javascript

```javascript
function isPossibleDivide(hand, groupSize) {
    const cardCount = new Map();
    for (const card of hand) {
        cardCount.set(card, (cardCount.get(card) || 0) + 1);
    }

    for (const [card, count] of Array.from(cardCount.entries()).sort((a, b) => a[0] - b[0])) {
        if (count > 0) {
            for (let i = 1; i < groupSize; ++i) {
                const tmp = (cardCount.get(card + i) || 0) - count;
                if (tmp < 0) {
                    return false;
                }
                cardCount.set(card + i, tmp);
            }
        }
    }

    return true;
}
```
The algorithm counts the occurrence of each card value and stores it in a map. Then, it iterates through the sorted card values in the map. For each card with a count greater than 0, it checks if it can decrement the count for the next `groupSize - 1` card values by the current count without going below 0. If it's possible to do so for all card values, then the cards can be divided into groups of size `groupSize` with consecutive values.

The algorithm has a time complexity of O(n * log(n)) due to the sorting process, where n is the length of the hand array.


# Shortest Path Visiting All Nodes

- slug: shortest-path-visiting-all-nodes
- difficulty: Hard

You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge.

Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

**Example 1:**

**Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\]
**Output:** 4
**Explanation:** One possible path is \[1,0,2,0,3\]

**Example 2:**

**Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\]
**Output:** 4
**Explanation:** One possible path is \[0,1,4,2,3\]

**Constraints:**

*   `n == graph.length`
*   `1 <= n <= 12`
*   `0 <= graph[i].length < n`
*   `graph[i]` does not contain `i`.
*   If `graph[a]` contains `b`, then `graph[b]` contains `a`.
*   The input graph is always connected.

## A solution in Java

```java
import java.util.LinkedList;
import java.util.Queue;

public int shortestPathLength(int[][] graph) {
    int n = graph.length;
    Queue<int[]> queue = new LinkedList<>();
    boolean[][] visited = new boolean[n][1 << n];

    for (int i = 0; i < n; i++) {
        queue.offer(new int[]{i, 1 << i, 0});
        visited[i][1 << i] = true;
    }

    while (!queue.isEmpty()) {
        int[] cur = queue.poll();
        int node = cur[0], bitmask = cur[1], length = cur[2];

        if (bitmask == (1 << n) - 1) return length;

        for (int nei : graph[node]) {
            int next_bitmask = bitmask | (1 << nei);
            if (!visited[nei][next_bitmask]) {
                visited[nei][next_bitmask] = true;
                queue.offer(new int[]{nei, next_bitmask, length + 1});
            }
        }
    }

    return 0;
}
```
The problem can be solved using BFS (breadth-first search) and bitmasks to represent the state of visited nodes.

1. Initially, create a queue with each node as a starting point, and a 2D visited array to keep track of visited states.
2. For each node, mark its corresponding bitmask as visited.
3. Iterate through the queue until it's empty.
   1. Dequeue the first item, which is a tuple of the current node, its bitmask, and its length.
   2. If the bitmask represents all nodes visited (bitmask is equal to `(1 << n) - 1`), return the current length.
   3. For each neighboring node (`nei`), create the next bitmask by bitwise OR operation with the current bitmask and neighbor node.
   4. If the next bitmask hasn't been visited, mark it as visited and enqueue the tuple of the neighboring node, next bitmask, and incremented length.

The algorithm eventually returns the length of the shortest path that visits every node. Since we start and finish at any possible node, the running time complexity is O(n * 2^n).

## A solution in C++

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

int shortestPathLength(const std::vector<std::vector<int>>& graph) {
    int n = graph.size();
    std::queue<std::tuple<int, int, int>> q;
    std::vector<std::vector<bool>> visited(n, std::vector<bool>(1 << n, false));

    for (int i = 0; i < n; ++i) {
        q.push({i, 1 << i, 0});
        visited[i][1 << i] = true;
    }

    while (!q.empty()) {
        auto [node, bitmask, length] = q.front();
        q.pop();

        if (bitmask == (1 << n) - 1) return length;

        for (int nei : graph[node]) {
            int next_bitmask = bitmask | (1 << nei);
            if (!visited[nei][next_bitmask]) {
                visited[nei][next_bitmask] = true;
                q.push({nei, next_bitmask, length + 1});
            }
        }
    }

    return 0;
}
```
The problem can be solved using BFS (breadth-first search) and bitmasks to represent the state of visited nodes.

1. Initially, create a queue with each node as a starting point, and a 2D visited array to keep track of visited states.
2. For each node, mark its corresponding bitmask as visited.
3. Iterate through the queue until it's empty.
   1. Dequeue the first item, which is a tuple of the current node, its bitmask, and its length.
   2. If the bitmask represents all nodes visited (bitmask is equal to `(1 << n) - 1`), return the current length.
   3. For each neighboring node (`nei`), create the next bitmask by bitwise OR operation with the current bitmask and neighbor node.
   4. If the next bitmask hasn't been visited, mark it as visited and enqueue the tuple of the neighboring node, next bitmask, and incremented length.

The algorithm eventually returns the length of the shortest path that visits every node. Since we start and finish at any possible node, the running time complexity is O(n * 2^n).

## A solution in Python

```python
from collections import deque

def shortestPathLength(graph):
    n = len(graph)
    queue = deque([(i, 1 << i, 0) for i in range(n)])
    visited = [[False] * (1 << n) for _ in range(n)]

    for i in range(n):
        visited[i][1 << i] = True

    while queue:
        node, bitmask, length = queue.popleft()

        if bitmask == (1 << n) - 1:
            return length

        for nei in graph[node]:
            next_bitmask = bitmask | (1 << nei)
            if not visited[nei][next_bitmask]:
                visited[nei][next_bitmask] = True
                queue.append((nei, next_bitmask, length + 1))

    return 0
```
The problem can be solved using BFS (breadth-first search) and bitmasks to represent the state of visited nodes.

1. Initially, create a queue with each node as a starting point, and a 2D visited array to keep track of visited states.
2. For each node, mark its corresponding bitmask as visited.
3. Iterate through the queue until it's empty.
   1. Dequeue the first item, which is a tuple of the current node, its bitmask, and its length.
   2. If the bitmask represents all nodes visited (bitmask is equal to `(1 << n) - 1`), return the current length.
   3. For each neighboring node (`nei`), create the next bitmask by bitwise OR operation with the current bitmask and neighbor node.
   4. If the next bitmask hasn't been visited, mark it as visited and enqueue the tuple of the neighboring node, next bitmask, and incremented length.

The algorithm eventually returns the length of the shortest path that visits every node. Since we start and finish at any possible node, the running time complexity is O(n * 2^n).

## A solution in Javascript

```javascript
function shortestPathLength(graph) {
    const n = graph.length;
    const queue = [];
    const visited = Array.from({length: n}, () => Array(1 << n).fill(false));

    for (let i = 0; i < n; i++) {
        queue.push([i, 1 << i, 0]);
        visited[i][1 << i] = true;
    }

    while (queue.length) {
        const [node, bitmask, length] = queue.shift();

        if (bitmask === (1 << n) - 1) return length;

        for (const nei of graph[node]) {
            const next_bitmask = bitmask | (1 << nei);
            if (!visited[nei][next_bitmask]) {
                visited[nei][next_bitmask] = true;
                queue.push([nei, next_bitmask, length + 1]);
            }
        }
    }

    return 0;
}
```
The problem can be solved using BFS (breadth-first search) and bitmasks to represent the state of visited nodes.

1. Initially, create a queue with each node as a starting point, and a 2D visited array to keep track of visited states.
2. For each node, mark its corresponding bitmask as visited.
3. Iterate through the queue until it's empty.
   1. Dequeue the first item, which is a tuple of the current node, its bitmask, and its length.
   2. If the bitmask represents all nodes visited (bitmask is equal to `(1 << n) - 1`), return the current length.
   3. For each neighboring node (`nei`), create the next bitmask by bitwise OR operation with the current bitmask and neighbor node.
   4. If the next bitmask hasn't been visited, mark it as visited and enqueue the tuple of the neighboring node, next bitmask, and incremented length.

The algorithm eventually returns the length of the shortest path that visits every node. Since we start and finish at any possible node, the running time complexity is O(n * 2^n).


# Shifting Letters

- slug: shifting-letters
- difficulty: Medium

You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length.

Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`).

*   For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`.

Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times.

Return _the final string after all such shifts to s are applied_.

**Example 1:**

**Input:** s =  "abc ", shifts = \[3,5,9\]
**Output:**  "rpl "
**Explanation:** We start with  "abc ".
After shifting the first 1 letters of s by 3, we have  "dbc ".
After shifting the first 2 letters of s by 5, we have  "igc ".
After shifting the first 3 letters of s by 9, we have  "rpl ", the answer.

**Example 2:**

**Input:** s =  "aaa ", shifts = \[1,2,3\]
**Output:**  "gfd "

**Constraints:**

*   `1 <= s.length <= 105`
*   `s` consists of lowercase English letters.
*   `shifts.length == s.length`
*   `0 <= shifts[i] <= 109`

## A solution in Java

```java
public String shiftingLetters(String s, int[] shifts) {
    for (int i = shifts.length - 2; i >= 0; i--) {
        shifts[i] = (shifts[i] + shifts[i + 1] % 26) % 26;
    }

    char[] result = s.toCharArray();
    for (int i = 0; i < s.length(); i++) {
        result[i] = (char) ((result[i] - 'a' + shifts[i] % 26) % 26 + 'a');
    }

    return new String(result);
}
```
For this problem, we first need to retrieve the total shifts needed for each character. To achieve this, we start from the last character's shift value and go backwards through the `shifts` array, summing the shifts and taking the modulo 26 to avoid loops in the alphabet.

Once we have the total shifts needed for each character, we iterate through the given string `s`, and for each character, we calculate its new position in the alphabet by adding the character's total shift modulo 26, and updating its value in the result string or array.

Finally, we return the result string/array, which holds the final string after all of the shifts have been applied.

## A solution in C++

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

string shiftingLetters(string s, vector<int>& shifts) {
    for (int i = shifts.size() - 2; i >= 0; i--) {
        shifts[i] += shifts[i + 1] % 26;
    }

    for (int i = 0; i < s.size(); i++) {
        s[i] = (s[i] - 'a' + shifts[i] % 26) % 26 + 'a';
    }

    return s;
}
```
For this problem, we first need to retrieve the total shifts needed for each character. To achieve this, we start from the last character's shift value and go backwards through the `shifts` array, summing the shifts and taking the modulo 26 to avoid loops in the alphabet.

Once we have the total shifts needed for each character, we iterate through the given string `s`, and for each character, we calculate its new position in the alphabet by adding the character's total shift modulo 26, and updating its value in the result string or array.

Finally, we return the result string/array, which holds the final string after all of the shifts have been applied.

## A solution in Python

```python
def shiftingLetters(s: str, shifts) -> str:
    for i in range(len(shifts) - 2, -1, -1):
        shifts[i] += shifts[i + 1] % 26

    result = list(s)
    for i in range(len(s)):
        result[i] = chr((ord(result[i]) - ord('a') + shifts[i] % 26) % 26 + ord('a'))

    return "".join(result)
```
For this problem, we first need to retrieve the total shifts needed for each character. To achieve this, we start from the last character's shift value and go backwards through the `shifts` array, summing the shifts and taking the modulo 26 to avoid loops in the alphabet.

Once we have the total shifts needed for each character, we iterate through the given string `s`, and for each character, we calculate its new position in the alphabet by adding the character's total shift modulo 26, and updating its value in the result string or array.

Finally, we return the result string/array, which holds the final string after all of the shifts have been applied.

## A solution in Javascript

```javascript
function shiftingLetters(s, shifts) {
    for (let i = shifts.length - 2; i >= 0; i--) {
        shifts[i] = (shifts[i] + shifts[i + 1] % 26) % 26;
    }

    let result = s.split('');
    for (let i = 0; i < s.length; i++) {
        result[i] = String.fromCharCode((result[i].charCodeAt(0) - 'a'.charCodeAt(0) + shifts[i] % 26) % 26 + 'a'.charCodeAt(0));
    }

    return result.join('');
}
```
For this problem, we first need to retrieve the total shifts needed for each character. To achieve this, we start from the last character's shift value and go backwards through the `shifts` array, summing the shifts and taking the modulo 26 to avoid loops in the alphabet.

Once we have the total shifts needed for each character, we iterate through the given string `s`, and for each character, we calculate its new position in the alphabet by adding the character's total shift modulo 26, and updating its value in the result string or array.

Finally, we return the result string/array, which holds the final string after all of the shifts have been applied.


# Maximize Distance to Closest Person

- slug: maximize-distance-to-closest-person
- difficulty: Medium

You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**.

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.

Return _that maximum distance to the closest person_.

**Example 1:**

**Input:** seats = \[1,0,0,0,1,0,1\]
**Output:** 2
**Explanation:**
If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.

**Example 2:**

**Input:** seats = \[1,0,0,0\]
**Output:** 3
**Explanation:**
If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.

**Example 3:**

**Input:** seats = \[0,1\]
**Output:** 1

**Constraints:**

*   `2 <= seats.length <= 2 * 104`
*   `seats[i]` is `0` or `1`.
*   At least one seat is **empty**.
*   At least one seat is **occupied**.

## A solution in Java

```java
public int maxDistToClosest(int[] seats) {
    int n = seats.length;
    int maxDist = 0, lastPerson = -1;

    for (int i = 0; i < n; ++i) {
        if (seats[i] == 1) {
            if (lastPerson == -1)
                maxDist = i;
            else
                maxDist = Math.max(maxDist, (i - lastPerson) / 2);
            lastPerson = i;
        }
    }
    maxDist = Math.max(maxDist, n - 1 - lastPerson);
    return maxDist;
}
```
1. Initialize `maxDist` to 0 and `lastPerson` to -1.
2. Loop through the array with the index `i`.
3. If a person is found sitting in the current seat, calculate the distance.
   - If this is the first person found (`lastPerson == -1`), set the maximum distance as their index `i`.
   - If not, calculate and update the maximum distance as `(i - lastPerson) / 2`.
4. Update `lastPerson` to the index of the current person (`lastPerson = i`).
5. After the loop, compare the maximum distance to the distance between the last person and the end of the array (`n - 1 - lastPerson`). Update `maxDist` to the larger value.
6. Return `maxDist` as the maximum distance to the closest person.

## A solution in C++

```cpp
int maxDistToClosest(vector<int>& seats) {
    int n = seats.size();
    int maxDist = 0, lastPerson = -1;

    for (int i = 0; i < n; ++i) {
        if (seats[i] == 1) {
            if (lastPerson == -1)
                maxDist = i;
            else
                maxDist = max(maxDist, (i - lastPerson) / 2);
            lastPerson = i;
        }
    }
    maxDist = max(maxDist, n - 1 - lastPerson);
    return maxDist;
}
```
1. Initialize `maxDist` to 0 and `lastPerson` to -1.
2. Loop through the array with the index `i`.
3. If a person is found sitting in the current seat, calculate the distance.
   - If this is the first person found (`lastPerson == -1`), set the maximum distance as their index `i`.
   - If not, calculate and update the maximum distance as `(i - lastPerson) / 2`.
4. Update `lastPerson` to the index of the current person (`lastPerson = i`).
5. After the loop, compare the maximum distance to the distance between the last person and the end of the array (`n - 1 - lastPerson`). Update `maxDist` to the larger value.
6. Return `maxDist` as the maximum distance to the closest person.

## A solution in Python

```python
def maxDistToClosest(seats):
    n = len(seats)
    maxDist = 0
    lastPerson = -1

    for i in range(n):
        if seats[i] == 1:
            if lastPerson == -1:
                maxDist = i
            else:
                maxDist = max(maxDist, (i - lastPerson) // 2)
            lastPerson = i

    maxDist = max(maxDist, n - 1 - lastPerson)
    return maxDist
```
1. Initialize `maxDist` to 0 and `lastPerson` to -1.
2. Loop through the array with the index `i`.
3. If a person is found sitting in the current seat, calculate the distance.
   - If this is the first person found (`lastPerson == -1`), set the maximum distance as their index `i`.
   - If not, calculate and update the maximum distance as `(i - lastPerson) / 2`.
4. Update `lastPerson` to the index of the current person (`lastPerson = i`).
5. After the loop, compare the maximum distance to the distance between the last person and the end of the array (`n - 1 - lastPerson`). Update `maxDist` to the larger value.
6. Return `maxDist` as the maximum distance to the closest person.

## A solution in Javascript

```javascript
function maxDistToClosest(seats) {
    let n = seats.length;
    let maxDist = 0, lastPerson = -1;

    for (let i = 0; i < n; ++i) {
        if (seats[i] === 1) {
            if (lastPerson === -1)
                maxDist = i;
            else
                maxDist = Math.max(maxDist, Math.floor((i - lastPerson) / 2));
            lastPerson = i;
        }
    }
    maxDist = Math.max(maxDist, n - 1 - lastPerson);
    return maxDist;
}
```
1. Initialize `maxDist` to 0 and `lastPerson` to -1.
2. Loop through the array with the index `i`.
3. If a person is found sitting in the current seat, calculate the distance.
   - If this is the first person found (`lastPerson == -1`), set the maximum distance as their index `i`.
   - If not, calculate and update the maximum distance as `(i - lastPerson) / 2`.
4. Update `lastPerson` to the index of the current person (`lastPerson = i`).
5. After the loop, compare the maximum distance to the distance between the last person and the end of the array (`n - 1 - lastPerson`). Update `maxDist` to the larger value.
6. Return `maxDist` as the maximum distance to the closest person.


# Rectangle Area II

- slug: rectangle-area-ii
- difficulty: Hard

You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**.

Calculate the **total area** covered by all `rectangles` in the plane. Any area covered by two or more rectangles should only be counted **once**.

Return _the **total area**_. Since the answer may be too large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** rectangles = \[\[0,0,2,2\],\[1,0,2,3\],\[1,0,3,1\]\]
**Output:** 6
**Explanation:** A total area of 6 is covered by all three rectangles, as illustrated in the picture.
From (1,1) to (2,2), the green and red rectangles overlap.
From (1,0) to (2,3), all three rectangles overlap.

**Example 2:**

**Input:** rectangles = \[\[0,0,1000000000,1000000000\]\]
**Output:** 49
**Explanation:** The answer is 1018 modulo (109 + 7), which is 49.

**Constraints:**

*   `1 <= rectangles.length <= 200`
*   `rectanges[i].length == 4`
*   `0 <= xi1, yi1, xi2, yi2 <= 109`
*   `xi1 <= xi2`
*   `yi1 <= yi2`

## A solution in Java

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

public int rectangleArea(int[][] rectangles) {
    final int mod = 1000000007;
    int n = rectangles.length;
    Set<Integer> X = new HashSet<>();
    Set<Integer> Y = new HashSet<>();
    for (int[] rect : rectangles) {
        X.add(rect[0]);
        X.add(rect[2]);
        Y.add(rect[1]);
        Y.add(rect[3]);
    }
    Integer[] sortedX = X.toArray(new Integer[0]);
    Integer[] sortedY = Y.toArray(new Integer[0]);
    Arrays.sort(sortedX);
    Arrays.sort(sortedY);

...
```
(Java code is similar to C++, with minor adjustments to use Java Collections)

    - For each rectangle, add its x-coordinates and y-coordinates (both left and right) into two separate sets X and Y.
- Convert the sets X and Y to sorted lists (sortedX, sortedY).
- Create an 2D array (matrix) cnt, which will represent the overlap of rectangles, i.e., cnt[i][j] == 1 if any rectangle covers that area.
- Iterate through the rectangles and for each rectangle, find its left and right, top and bottom boundaries in the sortedX and sortedY lists.
- Mark cnt[i][j] = 1 for each rectangle covering the area between indices i and j.
- Initialize a variable total_area to 0. Iterate over the cnt matrix, and for each cell with value 1, increment total_area by the area of the cell (product of the difference in x and y-coordinates).
- Return total_area modulo 10^9 + 7.

## A solution in C++

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

int rectangleArea(vector<vector<int>>& rectangles) {
    const int64_t mod = 1e9 + 7;
    int n = rectangles.size();
    vector<int> X, Y;
    for (const auto &rect : rectangles) {
        X.push_back(rect[0]);
        X.push_back(rect[2]);
        Y.push_back(rect[1]);
        Y.push_back(rect[3]);
    }
    sort(X.begin(), X.end());
    sort(Y.begin(), Y.end());

    X.erase(unique(X.begin(), X.end()), X.end());
    Y.erase(unique(Y.begin(), Y.end()), Y.end());

    vector<vector<int>> cnt(X.size() - 1, vector<int>(Y.size() - 1));

    for (const auto &rect : rectangles) {
        int x1_idx = lower_bound(X.begin(), X.end(), rect[0]) - X.begin();
        int x2_idx = lower_bound(X.begin(), X.end(), rect[2]) - X.begin() - 1;
        int y1_idx = lower_bound(Y.begin(), Y.end(), rect[1]) - Y.begin();
        int y2_idx = lower_bound(Y.begin(), Y.end(), rect[3]) - Y.begin() - 1;
        for (int i = x1_idx; i <= x2_idx; ++i) {
            for (int j = y1_idx; j <= y2_idx; ++j) {
                cnt[i][j] = 1;
            }
        }
    }
    int64_t total_area = 0;
    for (int i = 0; i < X.size() - 1; ++i) {
        for (int j = 0; j < Y.size() - 1; ++j) {
            if (cnt[i][j]) {
                total_area += (int64_t)(X[i + 1] - X[i]) * (Y[j + 1] - Y[j]);
                total_area %= mod;
            }
        }
    }
    return total_area;
}
```
- For each rectangle, add its x-coordinates and y-coordinates (both left and right) into two separate sets X and Y.
- Convert the sets X and Y to sorted lists (sortedX, sortedY).
- Create an 2D array (matrix) cnt, which will represent the overlap of rectangles, i.e., cnt[i][j] == 1 if any rectangle covers that area.
- Iterate through the rectangles and for each rectangle, find its left and right, top and bottom boundaries in the sortedX and sortedY lists.
- Mark cnt[i][j] = 1 for each rectangle covering the area between indices i and j.
- Initialize a variable total_area to 0. Iterate over the cnt matrix, and for each cell with value 1, increment total_area by the area of the cell (product of the difference in x and y-coordinates).
- Return total_area modulo 10^9 + 7.

## A solution in Python

```python
def rectangleArea(rectangles):
    mod = 10**9 + 7
    n = len(rectangles)
    X, Y = set(), set()
    for rect in rectangles:
        X.add(rect[0])
        X.add(rect[2])
        Y.add(rect[1])
        Y.add(rect[3])
    sorted_x = sorted(X)
    sorted_y = sorted(Y)
    cnt = [[0 for _ in range(len(Y) - 1)] for _ in range(len(X) - 1)]

    for rect in rectangles:
        x1_idx = sorted_x.index(rect[0])
        x2_idx = sorted_x.index(rect[2]) - 1
        y1_idx = sorted_y.index(rect[1])
        y2_idx = sorted_y.index(rect[3]) - 1
        for i in range(x1_idx, x2_idx + 1):
            for j in range(y1_idx, y2_idx + 1):
                cnt[i][j] = 1

    total_area = 0
    for i in range(len(X) - 1):
        for j in range(len(Y) - 1):
            if cnt[i][j]:
                total_area += (sorted_x[i + 1] - sorted_x[i]) * (sorted_y[j + 1] - sorted_y[j])
                total_area %= mod

    return total_area
```
- For each rectangle, add its x-coordinates and y-coordinates (both left and right) into two separate sets X and Y.
- Convert the sets X and Y to sorted lists (sortedX, sortedY).
- Create an 2D array (matrix) cnt, which will represent the overlap of rectangles, i.e., cnt[i][j] == 1 if any rectangle covers that area.
- Iterate through the rectangles and for each rectangle, find its left and right, top and bottom boundaries in the sortedX and sortedY lists.
- Mark cnt[i][j] = 1 for each rectangle covering the area between indices i and j.
- Initialize a variable total_area to 0. Iterate over the cnt matrix, and for each cell with value 1, increment total_area by the area of the cell (product of the difference in x and y-coordinates).
- Return total_area modulo 10^9 + 7.

## A solution in Javascript

```javascript
function rectangleArea(rectangles) {
    const mod = 1e9 + 7;
    let n = rectangles.length;
    let X = new Set(), Y = new Set();
    for (const rect of rectangles) {
        X.add(rect[0]);
        X.add(rect[2]);
        Y.add(rect[1]);
        Y.add(rect[3]);
    }
    let sortedX = Array.from(X).sort((a, b) => a - b);
    let sortedY = Array.from(Y).sort((a, b) => a - b);

    let cnt = Array.from({ length: X.size - 1 }, () => Array.from({ length: Y.size - 1 }, () => 0));

    for (const rect of rectangles) {
        let x1_idx = sortedX.indexOf(rect[0]);
        let x2_idx = sortedX.indexOf(rect[2]) - 1;
        let y1_idx = sortedY.indexOf(rect[1]);
        let y2_idx = sortedY.indexOf(rect[3]) - 1;
        for (let i = x1_idx; i <= x2_idx; i++) {
            for (let j = y1_idx; j <= y2_idx; j++) {
                cnt[i][j] = 1;
            }
        }
    }

    let total_area = 0;
    for (let i = 0; i < X.size - 1; i++) {
        for (let j = 0; j < Y.size - 1; j++) {
            if (cnt[i][j]) {
                total_area += (sortedX[i + 1] - sortedX[i]) * (sortedY[j + 1] - sortedY[j]);
                total_area %= mod;
            }
        }
    }

    return total_area;
}
```
- For each rectangle, add its x-coordinates and y-coordinates (both left and right) into two separate sets X and Y.
- Convert the sets X and Y to sorted lists (sortedX, sortedY).
- Create an 2D array (matrix) cnt, which will represent the overlap of rectangles, i.e., cnt[i][j] == 1 if any rectangle covers that area.
- Iterate through the rectangles and for each rectangle, find its left and right, top and bottom boundaries in the sortedX and sortedY lists.
- Mark cnt[i][j] = 1 for each rectangle covering the area between indices i and j.
- Initialize a variable total_area to 0. Iterate over the cnt matrix, and for each cell with value 1, increment total_area by the area of the cell (product of the difference in x and y-coordinates).
- Return total_area modulo 10^9 + 7.


# Loud and Rich

- slug: loud-and-rich
- difficulty: Medium

There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness.

You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time).

Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`.

**Example 1:**

**Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\]
**Output:** \[5,5,2,5,4,5,6,7\]
**Explanation:**
answer\[0\] = 5.
Person 5 has more money than 3, which has more money than 1, which has more money than 0.
The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0.
answer\[7\] = 7.
Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7.
The other answers can be filled out with similar reasoning.

**Example 2:**

**Input:** richer = \[\], quiet = \[0\]
**Output:** \[0\]

**Constraints:**

*   `n == quiet.length`
*   `1 <= n <= 500`
*   `0 <= quiet[i] < n`
*   All the values of `quiet` are **unique**.
*   `0 <= richer.length <= n * (n - 1) / 2`
*   `0 <= ai, bi < n`
*   `ai != bi`
*   All the pairs of `richer` are **unique**.
*   The observations in `richer` are all logically consistent.

## A solution in Java

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

public String toGoatLatin(String sentence) {
    String[] words = sentence.split(" ");
    String vowels = "AEIOUaeiou";
    Set<Character> vowelSet = new HashSet<>();

    for (char c : vowels.toCharArray()) {
        vowelSet.add(c);
    }

    StringJoiner result = new StringJoiner(" ");
    StringBuilder suffix = new StringBuilder("a");

    for (String word : words) {
        if (!vowelSet.contains(word.charAt(0))) {
            word = word.substring(1) + word.charAt(0);
        }
        result.add(word + "ma" + suffix);
        suffix.append("a");
    }

    return result.toString();
}
```
The algorithm iterates through each word in the sentence. If the first character of the word is not a vowel, it moves the first character to the end of the word. Then, it appends "ma" and a number of "a"s equal to the index of the word in the sentence (1-based index). Finally, it joins the converted words back into a single string.

In all languages, we use some kind of set, string or list to define the vowels, which can be quickly checked against the first character of the word. When forming the final result, we split the sentence into words, and iterate through them, adding the corresponding suffix to each word, based on its index. Then we join the words back into a single string. In Java and JavaScript, we use a StringBuilder or an array to store the result words, in Python we use a list comprehension, and in C++ we concatenate the result string along with the changing suffix.

## A solution in C++

```cpp
#include <sstream>

std::string toGoatLatin(std::string sentence) {
    std::istringstream ss(sentence);
    std::string word, result, suffix = "a";
    const std::string vowels = "AEIOUaeiou";

    while (ss >> word) {
        if (vowels.find(word[0]) == std::string::npos) {
            word = word.substr(1) + word[0];
        }
        result += word + "ma" + suffix + " ";
        suffix += "a";
    }

    result.pop_back();
    return result;
}
```
The algorithm iterates through each word in the sentence. If the first character of the word is not a vowel, it moves the first character to the end of the word. Then, it appends "ma" and a number of "a"s equal to the index of the word in the sentence (1-based index). Finally, it joins the converted words back into a single string.

In all languages, we use some kind of set, string or list to define the vowels, which can be quickly checked against the first character of the word. When forming the final result, we split the sentence into words, and iterate through them, adding the corresponding suffix to each word, based on its index. Then we join the words back into a single string. In Java and JavaScript, we use a StringBuilder or an array to store the result words, in Python we use a list comprehension, and in C++ we concatenate the result string along with the changing suffix.

## A solution in Python

```python
def to_goat_latin(sentence: str) -> str:
    words = sentence.split()
    vowels = set("AEIOUaeiou")
    result = []

    for i, word in enumerate(words):
        if word[0] not in vowels:
            word = word[1:] + word[0]
        result.append(word + "ma" + "a" * (i + 1))

    return ' '.join(result)
```
The algorithm iterates through each word in the sentence. If the first character of the word is not a vowel, it moves the first character to the end of the word. Then, it appends "ma" and a number of "a"s equal to the index of the word in the sentence (1-based index). Finally, it joins the converted words back into a single string.

In all languages, we use some kind of set, string or list to define the vowels, which can be quickly checked against the first character of the word. When forming the final result, we split the sentence into words, and iterate through them, adding the corresponding suffix to each word, based on its index. Then we join the words back into a single string. In Java and JavaScript, we use a StringBuilder or an array to store the result words, in Python we use a list comprehension, and in C++ we concatenate the result string along with the changing suffix.

## A solution in Javascript

```javascript
function toGoatLatin(sentence) {
    const words = sentence.split(" ");
    const vowels = new Set("AEIOUaeiou");
    let result = [];
    let suffix = "a";

    words.forEach(word => {
        if (!vowels.has(word[0])) {
            word = word.slice(1) + word[0];
        }
        result.push(word + "ma" + suffix);
        suffix += "a";
    });

    return result.join(" ");
}
```
The algorithm iterates through each word in the sentence. If the first character of the word is not a vowel, it moves the first character to the end of the word. Then, it appends "ma" and a number of "a"s equal to the index of the word in the sentence (1-based index). Finally, it joins the converted words back into a single string.

In all languages, we use some kind of set, string or list to define the vowels, which can be quickly checked against the first character of the word. When forming the final result, we split the sentence into words, and iterate through them, adding the corresponding suffix to each word, based on its index. Then we join the words back into a single string. In Java and JavaScript, we use a StringBuilder or an array to store the result words, in Python we use a list comprehension, and in C++ we concatenate the result string along with the changing suffix.