# Prime Palindrome

- slug: prime-palindrome
- difficulty: Medium

Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`.

An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number.

*   For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes.

An integer is a **palindrome** if it reads the same from left to right as it does from right to left.

*   For example, `101` and `12321` are palindromes.

The test cases are generated so that the answer always exists and is in the range `[2, 2 * 108]`.

**Example 1:**

**Input:** n = 6
**Output:** 7

**Example 2:**

**Input:** n = 8
**Output:** 11

**Example 3:**

**Input:** n = 13
**Output:** 101

**Constraints:**

*   `1 <= n <= 108`

## A solution in Java

```java
public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
    return rec1[2] > rec2[0] && rec1[3] > rec2[1] && rec1[0] < rec2[2] && rec1[1] < rec2[3];
}
```
The algorithm checks if the rectangles overlap by verifying that the `x` coordinate of the top-right corner of `rec1` is greater than the `x` coordinate of the bottom-left corner of `rec2`, the `y` coordinate of the top-right corner of `rec1` is greater than the `y` coordinate of the bottom-left corner of `rec2`, the `x` coordinate of the bottom-left corner of `rec1` is less than the `x` coordinate of the top-right corner of `rec2`, and the `y` coordinate of the bottom-left corner of `rec1` is less than the `y` coordinate of the top-right corner of `rec2`. If all these conditions hold, it means that the rectangles overlap, otherwise they do not.

## A solution in C++

```cpp
bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
    return rec1[2] > rec2[0] && rec1[3] > rec2[1] && rec1[0] < rec2[2] && rec1[1] < rec2[3];
}
```
The algorithm checks if the rectangles overlap by verifying that the `x` coordinate of the top-right corner of `rec1` is greater than the `x` coordinate of the bottom-left corner of `rec2`, the `y` coordinate of the top-right corner of `rec1` is greater than the `y` coordinate of the bottom-left corner of `rec2`, the `x` coordinate of the bottom-left corner of `rec1` is less than the `x` coordinate of the top-right corner of `rec2`, and the `y` coordinate of the bottom-left corner of `rec1` is less than the `y` coordinate of the top-right corner of `rec2`. If all these conditions hold, it means that the rectangles overlap, otherwise they do not.

## A solution in Python

```python
def isRectangleOverlap(rec1, rec2):
    return rec1[2] > rec2[0] and rec1[3] > rec2[1] and rec1[0] < rec2[2] and rec1[1] < rec2[3]
```
The algorithm checks if the rectangles overlap by verifying that the `x` coordinate of the top-right corner of `rec1` is greater than the `x` coordinate of the bottom-left corner of `rec2`, the `y` coordinate of the top-right corner of `rec1` is greater than the `y` coordinate of the bottom-left corner of `rec2`, the `x` coordinate of the bottom-left corner of `rec1` is less than the `x` coordinate of the top-right corner of `rec2`, and the `y` coordinate of the bottom-left corner of `rec1` is less than the `y` coordinate of the top-right corner of `rec2`. If all these conditions hold, it means that the rectangles overlap, otherwise they do not.

## A solution in Javascript

```javascript
function isRectangleOverlap(rec1, rec2) {
    return rec1[2] > rec2[0] && rec1[3] > rec2[1] && rec1[0] < rec2[2] && rec1[1] < rec2[3];
}
```
The algorithm checks if the rectangles overlap by verifying that the `x` coordinate of the top-right corner of `rec1` is greater than the `x` coordinate of the bottom-left corner of `rec2`, the `y` coordinate of the top-right corner of `rec1` is greater than the `y` coordinate of the bottom-left corner of `rec2`, the `x` coordinate of the bottom-left corner of `rec1` is less than the `x` coordinate of the top-right corner of `rec2`, and the `y` coordinate of the bottom-left corner of `rec1` is less than the `y` coordinate of the top-right corner of `rec2`. If all these conditions hold, it means that the rectangles overlap, otherwise they do not.


# Transpose Matrix

- slug: transpose-matrix
- difficulty: Easy

Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`.

The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

**Example 1:**

**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\]

**Example 2:**

**Input:** matrix = \[\[1,2,3\],\[4,5,6\]\]
**Output:** \[\[1,4\],\[2,5\],\[3,6\]\]

**Constraints:**

*   `m == matrix.length`
*   `n == matrix[i].length`
*   `1 <= m, n <= 1000`
*   `1 <= m * n <= 105`
*   `-109 <= matrix[i][j] <= 109`

## A solution in Java

```java
public double new21Game(int n, int k, int maxPts) {
    if (k == 0 || n >= k + maxPts) {
        return 1;
    }

    double[] dp = new double[n + 1];
    dp[0] = 1;
    double sum = 1, ans = 0;

    for (int i = 1; i <= n; i++) {
        dp[i] = sum / maxPts;
        if (i < k) {
            sum += dp[i];
        } else {
            ans += dp[i];
        }
        if (i >= maxPts) {
            sum -= dp[i - maxPts];
        }
    }

    return ans;
}
```
1. If Alice has already reached k points or n >= k + maxPts, there is no chance of drawing more cards, so return 1.
2. Create a dynamic programming array (dp) to store the probability of reaching each point from 0 to n. Initialize dp[0] as 1.
3. Keep a rolling sum of probabilities and iterate through the range [1, n]. Calculate the probability of reaching points i as the rolling sum divided by maxPts.
4. If i < k, Alice needs to draw more cards, so update the rolling sum by adding the i-th probability.
5. If i >= k, Alice already reached the target, so update the answer by adding the i-th probability.
6. If i >= maxPts, remove the (i-maxPts)-th probability from the rolling sum since it's not in the range of possibilities.
7. Return the accumulated probability after the iteration.

## A solution in C++

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

double new21Game(int n, int k, int maxPts) {
    if (k == 0 || n >= k + maxPts) {
        return 1;
    }

    vector<double> dp(n + 1, 0);
    dp[0] = 1;
    double sum = 1, ans = 0;

    for (int i = 1; i <= n; ++i) {
        dp[i] = sum / maxPts;
        if (i < k) {
            sum += dp[i];
        } else {
            ans += dp[i];
        }
        if (i >= maxPts) {
            sum -= dp[i - maxPts];
        }
    }

    return ans;
}
```
1. If Alice has already reached k points or n >= k + maxPts, there is no chance of drawing more cards, so return 1.
2. Create a dynamic programming array (dp) to store the probability of reaching each point from 0 to n. Initialize dp[0] as 1.
3. Keep a rolling sum of probabilities and iterate through the range [1, n]. Calculate the probability of reaching points i as the rolling sum divided by maxPts.
4. If i < k, Alice needs to draw more cards, so update the rolling sum by adding the i-th probability.
5. If i >= k, Alice already reached the target, so update the answer by adding the i-th probability.
6. If i >= maxPts, remove the (i-maxPts)-th probability from the rolling sum since it's not in the range of possibilities.
7. Return the accumulated probability after the iteration.

## A solution in Python

```python
def new21Game(n: int, k: int, maxPts: int) -> float:
    if k == 0 or n >= k + maxPts:
        return 1

    dp = [0] * (n + 1)
    dp[0] = 1
    s, ans = 1, 0

    for i in range(1, n + 1):
        dp[i] = s / maxPts
        if i < k:
            s += dp[i]
        else:
            ans += dp[i]
        if i >= maxPts:
            s -= dp[i - maxPts]

    return ans
```
1. If Alice has already reached k points or n >= k + maxPts, there is no chance of drawing more cards, so return 1.
2. Create a dynamic programming array (dp) to store the probability of reaching each point from 0 to n. Initialize dp[0] as 1.
3. Keep a rolling sum of probabilities and iterate through the range [1, n]. Calculate the probability of reaching points i as the rolling sum divided by maxPts.
4. If i < k, Alice needs to draw more cards, so update the rolling sum by adding the i-th probability.
5. If i >= k, Alice already reached the target, so update the answer by adding the i-th probability.
6. If i >= maxPts, remove the (i-maxPts)-th probability from the rolling sum since it's not in the range of possibilities.
7. Return the accumulated probability after the iteration.

## A solution in Javascript

```javascript
function new21Game(n, k, maxPts) {
    if (k === 0 || n >= k + maxPts) {
        return 1;
    }

    let dp = new Array(n + 1).fill(0);
    dp[0] = 1;
    let sum = 1, ans = 0;

    for (let i = 1; i <= n; i++) {
        dp[i] = sum / maxPts;
        if (i < k) {
            sum += dp[i];
        } else {
            ans += dp[i];
        }
        if (i >= maxPts) {
            sum -= dp[i - maxPts];
        }
    }

    return ans;
}
```
1. If Alice has already reached k points or n >= k + maxPts, there is no chance of drawing more cards, so return 1.
2. Create a dynamic programming array (dp) to store the probability of reaching each point from 0 to n. Initialize dp[0] as 1.
3. Keep a rolling sum of probabilities and iterate through the range [1, n]. Calculate the probability of reaching points i as the rolling sum divided by maxPts.
4. If i < k, Alice needs to draw more cards, so update the rolling sum by adding the i-th probability.
5. If i >= k, Alice already reached the target, so update the answer by adding the i-th probability.
6. If i >= maxPts, remove the (i-maxPts)-th probability from the rolling sum since it's not in the range of possibilities.
7. Return the accumulated probability after the iteration.


# Binary Gap

- slug: binary-gap
- difficulty: Easy

Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._

Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `1`'s is the absolute difference between their bit positions. For example, the two `1`'s in `"1001 "` have a distance of 3.

**Example 1:**

**Input:** n = 22
**Output:** 2
**Explanation:** 22 in binary is  "10110 ".
The first adjacent pair of 1's is  "10110 " with a distance of 2.
The second adjacent pair of 1's is  "10110 " with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that  "10110 " is not a valid pair since there is a 1 separating the two 1's underlined.

**Example 2:**

**Input:** n = 8
**Output:** 0
**Explanation:** 8 in binary is  "1000 ".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.

**Example 3:**

**Input:** n = 5
**Output:** 2
**Explanation:** 5 in binary is  "101 ".

**Constraints:**

*   `1 <= n <= 109`

## A solution in Java

```java
public String pushDominoes(String dominoes) {
    int n = dominoes.length();
    String prev;
    String cur = dominoes;
    do {
        prev = cur;
        StringBuilder sb = new StringBuilder(prev);
        for (int i = 0; i < n; ++i) {
            if (prev.charAt(i) == 'L' && i > 0 && prev.charAt(i - 1) == '.')
                sb.setCharAt(i - 1, 'L');
            else if (prev.charAt(i) == 'R' && i < n - 1 && prev.charAt(i + 1) == '.')
                sb.setCharAt(i + 1, 'R');
        }
        cur = sb.toString();
    } while (!prev.equals(cur));
    return cur;
}
```
1. Initialize `prev` and `cur` variables to store the state of dominoes. Set `cur` initially to the input string.
2. Run a loop until the states of dominoes do not change, i.e., `prev != cur`.
3. Iterate through each character in the `prev` string:
   - If the character is 'L' and there is a domino to its left, and the left domino is '.', set that domino to 'L'.
   - If the character is 'R' and there is a domino to its right, and the right domino is '.', set that domino to 'R'.
4. Concatenate the new state of the dominoes to form the string `cur`.
5. Continue the loop until there is no change in the states of the dominoes.
6. Return the final state of the dominoes as a string.

## A solution in C++

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

string pushDominoes(string dominoes) {
    int n = dominoes.size();
    string prev, cur = dominoes;
    do {
        prev = cur;
        for (int i = 0; i < n; ++i) {
            if (prev[i] == 'L' && i > 0 && prev[i - 1] == '.')
                cur[i - 1] = 'L';
            else if (prev[i] == 'R' && i < n - 1 && prev[i + 1] == '.')
                cur[i + 1] = 'R';
        }
    } while (prev != cur);
    return cur;
}
```
1. Initialize `prev` and `cur` variables to store the state of dominoes. Set `cur` initially to the input string.
2. Run a loop until the states of dominoes do not change, i.e., `prev != cur`.
3. Iterate through each character in the `prev` string:
   - If the character is 'L' and there is a domino to its left, and the left domino is '.', set that domino to 'L'.
   - If the character is 'R' and there is a domino to its right, and the right domino is '.', set that domino to 'R'.
4. Concatenate the new state of the dominoes to form the string `cur`.
5. Continue the loop until there is no change in the states of the dominoes.
6. Return the final state of the dominoes as a string.

## A solution in Python

```python
def push_dominoes(dominoes: str) -> str:
    prev, cur = None, dominoes
    while prev != cur:
        prev = cur
        cur_lst = list(prev)
        for i in range(len(cur)):
            if prev[i] == 'L' and i > 0 and prev[i - 1] == '.':
                cur_lst[i - 1] = 'L'
            elif prev[i] == 'R' and i < len(cur) - 1 and prev[i + 1] == '.':
                cur_lst[i + 1] = 'R'
        cur = ''.join(cur_lst)
    return cur
```
1. Initialize `prev` and `cur` variables to store the state of dominoes. Set `cur` initially to the input string.
2. Run a loop until the states of dominoes do not change, i.e., `prev != cur`.
3. Iterate through each character in the `prev` string:
   - If the character is 'L' and there is a domino to its left, and the left domino is '.', set that domino to 'L'.
   - If the character is 'R' and there is a domino to its right, and the right domino is '.', set that domino to 'R'.
4. Concatenate the new state of the dominoes to form the string `cur`.
5. Continue the loop until there is no change in the states of the dominoes.
6. Return the final state of the dominoes as a string.

## A solution in Javascript

```javascript
function pushDominoes(dominoes) {
    let prev, cur = dominoes;
    do {
        prev = cur;
        let curList = prev.split('');
        for (let i = 0; i < prev.length; ++i) {
            if (prev[i] === 'L' && i > 0 && prev[i - 1] === '.')
                curList[i - 1] = 'L';
            else if (prev[i] === 'R' && i < prev.length - 1 && prev[i + 1] === '.')
                curList[i + 1] = 'R';
        }
        cur = curList.join('');
    } while (prev !== cur);
    return cur;
}
```
1. Initialize `prev` and `cur` variables to store the state of dominoes. Set `cur` initially to the input string.
2. Run a loop until the states of dominoes do not change, i.e., `prev != cur`.
3. Iterate through each character in the `prev` string:
   - If the character is 'L' and there is a domino to its left, and the left domino is '.', set that domino to 'L'.
   - If the character is 'R' and there is a domino to its right, and the right domino is '.', set that domino to 'R'.
4. Concatenate the new state of the dominoes to form the string `cur`.
5. Continue the loop until there is no change in the states of the dominoes.
6. Return the final state of the dominoes as a string.


# Reordered Power of 2

- slug: reordered-power-of-2
- difficulty: Medium

You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero.

Return `true` _if and only if we can do this so that the resulting number is a power of two_.

**Example 1:**

**Input:** n = 1
**Output:** true

**Example 2:**

**Input:** n = 10
**Output:** false

**Constraints:**

*   `1 <= n <= 109`

## A solution in Java

```java
import java.util.Arrays;

public class SimilarGroups {
    public static boolean isSimilar(String a, String b) {
        int diffCount = 0;
        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) != b.charAt(i)) {
                diffCount++;
                if (diffCount > 2) {
                    return false;
                }
            }
        }
        return true;
    }

    public static int countGroups(String[] strs) {
        int count = 0;
        boolean[] visited = new boolean[strs.length];
        Arrays.fill(visited, false);
        for (int i = 0; i < strs.length; i++) {
            if (!visited[i]) {
                count++;
                visited[i] = true;
                for (int j = i + 1; j < strs.length; j++) {
                    if (isSimilar(strs[i], strs[j])) {
                        visited[j] = true;
                    }
                }
            }
        }
        return count;
    }
}
```
The algorithm uses a helper function called `is_similar(str1, str2)` which checks if two strings are similar or not by checking the count of different characters between them. If the count is less than or equal to 2, the two strings are similar. The main function `count_groups(strs)` iterates through the list of strings and uses a visited array to keep track of strings that have already been marked as part of a group. If a string is not visited, a new group is formed, and all other non-visited strings in the list are checked against this string. If they are similar, they are marked visited and considered part of the same group. The process continues until all strings have been visited, and the algorithm returns the total count of the groups formed.

## A solution in C++

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

bool is_similar(const string& a, const string& b) {
    int diff_count = 0;
    for (int i = 0; i < a.size(); ++i) {
        if (a[i] != b[i]) {
            ++diff_count;
            if (diff_count > 2) {
                return false;
            }
        }
    }
    return true;
}

int count_groups(vector<string>& strs) {
    int count = 0;
    vector<bool> visited(strs.size(), false);
    for (int i = 0; i < strs.size(); ++i) {
        if (!visited[i]) {
            ++count;
            visited[i] = true;
            for (int j = i + 1; j < strs.size(); ++j) {
                if (is_similar(strs[i], strs[j])) {
                    visited[j] = true;
                }
            }
        }
    }
    return count;
}
```
The algorithm uses a helper function called `is_similar(str1, str2)` which checks if two strings are similar or not by checking the count of different characters between them. If the count is less than or equal to 2, the two strings are similar. The main function `count_groups(strs)` iterates through the list of strings and uses a visited array to keep track of strings that have already been marked as part of a group. If a string is not visited, a new group is formed, and all other non-visited strings in the list are checked against this string. If they are similar, they are marked visited and considered part of the same group. The process continues until all strings have been visited, and the algorithm returns the total count of the groups formed.

## A solution in Python

```python
def is_similar(a: str, b: str) -> bool:
    diff_count = 0
    for char_a, char_b in zip(a, b):
        if char_a != char_b:
            diff_count += 1
            if diff_count > 2:
                return False
    return True

def count_groups(strs: list[str]) -> int:
    count = 0
    visited = [False] * len(strs)
    for i in range(len(strs)):
        if not visited[i]:
            count += 1
            visited[i] = True
            for j in range(i + 1, len(strs)):
                if is_similar(strs[i], strs[j]):
                    visited[j] = True
    return count
```
The algorithm uses a helper function called `is_similar(str1, str2)` which checks if two strings are similar or not by checking the count of different characters between them. If the count is less than or equal to 2, the two strings are similar. The main function `count_groups(strs)` iterates through the list of strings and uses a visited array to keep track of strings that have already been marked as part of a group. If a string is not visited, a new group is formed, and all other non-visited strings in the list are checked against this string. If they are similar, they are marked visited and considered part of the same group. The process continues until all strings have been visited, and the algorithm returns the total count of the groups formed.

## A solution in Javascript

```javascript
function isSimilar(a, b) {
    let diffCount = 0;
    for (let i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) {
            diffCount++;
            if (diffCount > 2) {
                return false;
            }
        }
    }
    return true;
}

function countGroups(strs) {
    let count = 0;
    let visited = new Array(strs.length).fill(false);
    for (let i = 0; i < strs.length; i++) {
        if (!visited[i]) {
            count++;
            visited[i] = true;
            for (let j = i + 1; j < strs.length; j++) {
                if (isSimilar(strs[i], strs[j])) {
                    visited[j] = true;
                }
            }
        }
    }
    return count;
}
```
The algorithm uses a helper function called `is_similar(str1, str2)` which checks if two strings are similar or not by checking the count of different characters between them. If the count is less than or equal to 2, the two strings are similar. The main function `count_groups(strs)` iterates through the list of strings and uses a visited array to keep track of strings that have already been marked as part of a group. If a string is not visited, a new group is formed, and all other non-visited strings in the list are checked against this string. If they are similar, they are marked visited and considered part of the same group. The process continues until all strings have been visited, and the algorithm returns the total count of the groups formed.


# Advantage Shuffle

- slug: advantage-shuffle
- difficulty: Medium

You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`.

Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`.

**Example 1:**

**Input:** nums1 = \[2,7,11,15\], nums2 = \[1,10,4,11\]
**Output:** \[2,11,7,15\]

**Example 2:**

**Input:** nums1 = \[12,24,8,32\], nums2 = \[13,25,32,11\]
**Output:** \[24,32,8,12\]

**Constraints:**

*   `1 <= nums1.length <= 105`
*   `nums2.length == nums1.length`
*   `0 <= nums1[i], nums2[i] <= 109`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int[] advantageCount(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int[] result = new int[n];
        TreeSet<Integer> set = new TreeSet<>();
        for (int num : nums1) set.add(num);
        for (int i = 0; i < n; i++) {
            Integer greater = set.higher(nums2[i]);
            if (greater == null) {
                greater = set.first();
            }
            set.remove(greater);
            result[i] = greater;
        }
        return result;
    }
}
```
1. Create a sorted data structure (`multiset` in C++, `TreeSet` in Java, `SortedList` in Python, and a sorted array in JavaScript) from nums1.
2. For each number `num` in nums2, find the smallest element in the sorted data structure that is greater than `num`. If there is no such element, select the smallest element in the sorted data structure.
3. Remove the selected element from the sorted data structure and append it to the result list/array.
4. Return the result list/array after processing all elements in nums2.

## A solution in C++

```cpp
#include <vector>
#include <set>

std::vector<int> advantageCount(std::vector<int>& nums1, std::vector<int>& nums2) {
    std::multiset<int> s(nums1.begin(), nums1.end());
    std::vector<int> res;
    for (int i : nums2) {
        auto it = s.upper_bound(i);
        if (it == s.end()) it = s.begin();
        res.push_back(*it);
        s.erase(it);
    }
    return res;
}
```
1. Create a sorted data structure (`multiset` in C++, `TreeSet` in Java, `SortedList` in Python, and a sorted array in JavaScript) from nums1.
2. For each number `num` in nums2, find the smallest element in the sorted data structure that is greater than `num`. If there is no such element, select the smallest element in the sorted data structure.
3. Remove the selected element from the sorted data structure and append it to the result list/array.
4. Return the result list/array after processing all elements in nums2.

## A solution in Python

```python
from sortedcontainers import SortedList

def advantage_count(nums1, nums2):
    nums1_sorted = SortedList(nums1)
    result = []
    for num in nums2:
        index = nums1_sorted.bisect_right(num)
        if index == len(nums1_sorted):
            val = nums1_sorted.pop(0)
        else:
            val = nums1_sorted.pop(index)
        result.append(val)
    return result
```
1. Create a sorted data structure (`multiset` in C++, `TreeSet` in Java, `SortedList` in Python, and a sorted array in JavaScript) from nums1.
2. For each number `num` in nums2, find the smallest element in the sorted data structure that is greater than `num`. If there is no such element, select the smallest element in the sorted data structure.
3. Remove the selected element from the sorted data structure and append it to the result list/array.
4. Return the result list/array after processing all elements in nums2.

## A solution in Javascript

```javascript
function advantageCount(nums1, nums2) {
    const sortedNums1 = [...nums1].sort((a, b) => a - b);
    const result = [];
    for (const num of nums2) {
        let index = sortedNums1.findIndex(el => el > num);
        if (index === -1) index = 0;
        result.push(sortedNums1[index]);
        sortedNums1.splice(index, 1);
    }
    return result;
}
```
1. Create a sorted data structure (`multiset` in C++, `TreeSet` in Java, `SortedList` in Python, and a sorted array in JavaScript) from nums1.
2. For each number `num` in nums2, find the smallest element in the sorted data structure that is greater than `num`. If there is no such element, select the smallest element in the sorted data structure.
3. Remove the selected element from the sorted data structure and append it to the result list/array.
4. Return the result list/array after processing all elements in nums2.


# Minimum Number of Refueling Stops

- slug: minimum-number-of-refueling-stops
- difficulty: Hard

A car travels from a starting position to a destination which is `target` miles east of the starting position.

There are gas stations along the way. The gas stations are represented as an array `stations` where `stations[i] = [positioni, fueli]` indicates that the `ith` gas station is `positioni` miles east of the starting position and has `fueli` liters of gas.

The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.

Return _the minimum number of refueling stops the car must make in order to reach its destination_. If it cannot reach the destination, return `-1`.

Note that if the car reaches a gas station with `0` fuel left, the car can still refuel there. If the car reaches the destination with `0` fuel left, it is still considered to have arrived.

**Example 1:**

**Input:** target = 1, startFuel = 1, stations = \[\]
**Output:** 0
**Explanation:** We can reach the target without refueling.

**Example 2:**

**Input:** target = 100, startFuel = 1, stations = \[\[10,100\]\]
**Output:** -1
**Explanation:** We can not reach the target (or even the first gas station).

**Example 3:**

**Input:** target = 100, startFuel = 10, stations = \[\[10,60\],\[20,30\],\[30,30\],\[60,40\]\]
**Output:** 2
**Explanation:** We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel.  We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas.  We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.

**Constraints:**

*   `1 <= target, startFuel <= 109`
*   `0 <= stations.length <= 500`
*   `1 <= positioni < positioni+1 < target`
*   `1 <= fueli < 109`

## A solution in Java

```java
import java.util.HashSet;
import java.util.List;
import java.util.Stack;

public boolean canVisitAllRooms(List<List<Integer>> rooms) {
    HashSet<Integer> visited = new HashSet<>();
    Stack<Integer> stack = new Stack<>();
    stack.push(0);

    while (!stack.isEmpty()) {
        int currentRoom = stack.pop();

        visited.add(currentRoom);

        for (int key : rooms.get(currentRoom)) {
            if (!visited.contains(key)) {
                stack.push(key);
            }
        }
    }

    return visited.size() == rooms.size();
}
```
The algorithm uses a depth-first search approach to visit all the rooms. It starts with room 0 and adds it to the visited set and also adds it to the stack. Then it enters a loop and keeps visiting the rooms till the stack is empty.

Inside the loop, it pops a room from the stack, adds it to the visited set, and iterates through the keys in the room. If a key (i.e., a room) is not in the visited set, it adds that key to the stack to visit the respective room.

At the end, if the size of the visited set is equal to the number of rooms, it returns true, indicating that all the rooms can be visited. Otherwise, it returns false.

## A solution in C++

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

bool canVisitAllRooms(const std::vector<std::vector<int>>& rooms) {
    std::unordered_set<int> visited;
    std::vector<int> stack = {0};

    while (!stack.empty()) {
        int currentRoom = stack.back();
        stack.pop_back();

        visited.insert(currentRoom);

        for (int key : rooms[currentRoom]) {
            if (!visited.count(key)) {
                stack.push_back(key);
            }
        }
    }

    return visited.size() == rooms.size();
}
```
The algorithm uses a depth-first search approach to visit all the rooms. It starts with room 0 and adds it to the visited set and also adds it to the stack. Then it enters a loop and keeps visiting the rooms till the stack is empty.

Inside the loop, it pops a room from the stack, adds it to the visited set, and iterates through the keys in the room. If a key (i.e., a room) is not in the visited set, it adds that key to the stack to visit the respective room.

At the end, if the size of the visited set is equal to the number of rooms, it returns true, indicating that all the rooms can be visited. Otherwise, it returns false.

## A solution in Python

```python
def can_visit_all_rooms(rooms):
    visited = set()
    stack = [0]

    while stack:
        current_room = stack.pop()

        visited.add(current_room)

        for key in rooms[current_room]:
            if key not in visited:
                stack.append(key)

    return len(visited) == len(rooms)
```
The algorithm uses a depth-first search approach to visit all the rooms. It starts with room 0 and adds it to the visited set and also adds it to the stack. Then it enters a loop and keeps visiting the rooms till the stack is empty.

Inside the loop, it pops a room from the stack, adds it to the visited set, and iterates through the keys in the room. If a key (i.e., a room) is not in the visited set, it adds that key to the stack to visit the respective room.

At the end, if the size of the visited set is equal to the number of rooms, it returns true, indicating that all the rooms can be visited. Otherwise, it returns false.

## A solution in Javascript

```javascript
function canVisitAllRooms(rooms) {
    const visited = new Set();
    const stack = [0];

    while (stack.length > 0) {
        const currentRoom = stack.pop();

        visited.add(currentRoom);

        for (const key of rooms[currentRoom]) {
            if (!visited.has(key)) {
                stack.push(key);
            }
        }
    }

    return visited.size === rooms.length;
}
```
The algorithm uses a depth-first search approach to visit all the rooms. It starts with room 0 and adds it to the visited set and also adds it to the stack. Then it enters a loop and keeps visiting the rooms till the stack is empty.

Inside the loop, it pops a room from the stack, adds it to the visited set, and iterates through the keys in the room. If a key (i.e., a room) is not in the visited set, it adds that key to the stack to visit the respective room.

At the end, if the size of the visited set is equal to the number of rooms, it returns true, indicating that all the rooms can be visited. Otherwise, it returns false.


# Leaf-Similar Trees

- slug: leaf-similar-trees
- difficulty: Easy

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._

For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`.

Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same.

Return `true` if and only if the two given trees with head nodes `root1` and `root2` are leaf-similar.

**Example 1:**

**Input:** root1 = \[3,5,1,6,2,9,8,null,null,7,4\], root2 = \[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8\]
**Output:** true

**Example 2:**

**Input:** root1 = \[1,2,3\], root2 = \[1,3,2\]
**Output:** false

**Constraints:**

*   The number of nodes in each tree will be in the range `[1, 200]`.
*   Both of the given trees will have values in the range `[0, 200]`.

## A solution in Java

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

public List<Integer> splitIntoFibonacci(String num) {
    List<Integer> ans = new ArrayList<>();
    backtrack(num, ans, 0, 0, 0);
    return ans;
}

private boolean backtrack(String num, List<Integer> ans, int index, int prev1, int prev2) {
    if (index == num.length()) {
        return ans.size() >= 3;
    }
    long curr = 0;
    for (int i = index; i < num.length(); ++i) {
        if (i > index && num.charAt(index) == '0') {
            break;
        }
        curr = curr * 10 + num.charAt(i) - '0';
        if (curr > Integer.MAX_VALUE) {
            break;
        }

        if (ans.size() >= 2) {
            long sum = (long) prev1 + prev2;
            if (curr < sum) {
                continue;
            } else if (curr > sum) {
                break;
            }
        }

        ans.add((int) curr);
        if (backtrack(num, ans, i + 1, prev2, (int) curr)) {
            return true;
        }
        ans.remove(ans.size() - 1);
    }
    return false;
}
```
The algorithm uses backtracking to solve the problem. It starts by iterating through the input string, parsing every possible length substring as numbers. The algorithm maintains a list, 'ans', to keep track of the Fibonacci-like sequence formed so far and also stores the previous 2 numbers in the sequence.

The base case is when the entire string has been processed (i.e., index == string length) and the 'ans' list has at least 3 elements. In that case, we return true and stop further processing.

While iterating through the string and parsing substrings, we perform the following steps:
1. Skip the current substring if it has a leading zero but isn't just "0".
2. If the current number is greater than the 32-bit integer limit, break because it can't be a valid Fibonacci number.
3. If the list 'ans' has at least 2 elements, we check whether the sum of the previous 2 numbers is equal to the current number. If the sum is smaller, we continue to the next substring, whereas if the sum is larger, we break because any larger substring will lead to an invalid sequence.
4. If the current number is a valid candidate, we add it to the 'ans' list.
5. Perform backtracking on the next index with the updated values of previous numbers. If the backtracking returns true, exit early; otherwise, we remove the current number from the 'ans' list and continue with the next substring.

## A solution in C++

```c++
#include <vector>
#include <string>

std::vector<int> splitIntoFibonacci(std::string num) {
    std::vector<int> ans;
    backtrack(num, ans, 0, 0, 0);
    return ans;
}

bool backtrack(std::string& num, std::vector<int>& ans, int index, int prev1, int prev2) {
    if (index == num.size()) {
        return ans.size() >= 3;
    }
    long curr = 0;
    for (int i = index; i < num.size(); ++i) {
        if (i > index && num[index] == '0') {
            break;
        }
        curr = curr * 10 + num[i] - '0';
        if (curr > INT32_MAX) {
            break;
        }

        if (ans.size() >= 2) {
            long sum = (long)prev1 + prev2;
            if (curr < sum) {
                continue;
            } else if (curr > sum) {
                break;
            }
        }

        ans.push_back(curr);
        if (backtrack(num, ans, i + 1, prev2, curr)) {
            return true;
        }
        ans.pop_back();
    }
    return false;
}
```
The algorithm uses backtracking to solve the problem. It starts by iterating through the input string, parsing every possible length substring as numbers. The algorithm maintains a list, 'ans', to keep track of the Fibonacci-like sequence formed so far and also stores the previous 2 numbers in the sequence.

The base case is when the entire string has been processed (i.e., index == string length) and the 'ans' list has at least 3 elements. In that case, we return true and stop further processing.

While iterating through the string and parsing substrings, we perform the following steps:
1. Skip the current substring if it has a leading zero but isn't just "0".
2. If the current number is greater than the 32-bit integer limit, break because it can't be a valid Fibonacci number.
3. If the list 'ans' has at least 2 elements, we check whether the sum of the previous 2 numbers is equal to the current number. If the sum is smaller, we continue to the next substring, whereas if the sum is larger, we break because any larger substring will lead to an invalid sequence.
4. If the current number is a valid candidate, we add it to the 'ans' list.
5. Perform backtracking on the next index with the updated values of previous numbers. If the backtracking returns true, exit early; otherwise, we remove the current number from the 'ans' list and continue with the next substring.

## A solution in Python

```python
def splitIntoFibonacci(num):
    ans = []
    def backtrack(index, prev1, prev2):
        if index == len(num):
            return len(ans) >= 3
        curr = 0
        for i in range(index, len(num)):
            if i > index and num[index] == '0':
                break
            curr = curr * 10 + ord(num[i]) - ord('0')
            if curr > 2**31 - 1:
                break
            if len(ans) >= 2:
                if curr < prev1 + prev2:
                    continue
                elif curr > prev1 + prev2:
                    break
            ans.append(curr)
            if backtrack(i + 1, prev2, curr):
                return True
            ans.pop()
        return False

    backtrack(0, 0, 0)
    return ans
```
The algorithm uses backtracking to solve the problem. It starts by iterating through the input string, parsing every possible length substring as numbers. The algorithm maintains a list, 'ans', to keep track of the Fibonacci-like sequence formed so far and also stores the previous 2 numbers in the sequence.

The base case is when the entire string has been processed (i.e., index == string length) and the 'ans' list has at least 3 elements. In that case, we return true and stop further processing.

While iterating through the string and parsing substrings, we perform the following steps:
1. Skip the current substring if it has a leading zero but isn't just "0".
2. If the current number is greater than the 32-bit integer limit, break because it can't be a valid Fibonacci number.
3. If the list 'ans' has at least 2 elements, we check whether the sum of the previous 2 numbers is equal to the current number. If the sum is smaller, we continue to the next substring, whereas if the sum is larger, we break because any larger substring will lead to an invalid sequence.
4. If the current number is a valid candidate, we add it to the 'ans' list.
5. Perform backtracking on the next index with the updated values of previous numbers. If the backtracking returns true, exit early; otherwise, we remove the current number from the 'ans' list and continue with the next substring.

## A solution in Javascript

```javascript
function splitIntoFibonacci(num) {
    const ans = [];
    const backtrack = (index, prev1, prev2) => {
        if (index === num.length) {
            return ans.length >= 3;
        }
        let curr = 0;
        for (let i = index; i < num.length; ++i) {
            if (i > index && num[index] === '0') {
                break;
            }
            curr = curr * 10 + num.charCodeAt(i) - 48;
            if (curr > 2**31 - 1) {
                break;
            }

            if (ans.length >= 2) {
                const sum = prev1 + prev2;
                if (curr < sum) {
                    continue;
                } else if (curr > sum) {
                    break;
                }
            }

            ans.push(curr);
            if (backtrack(i + 1, prev2, curr)) {
                return true;
            }
            ans.pop();
        }
        return false;
    }

    backtrack(0, 0, 0);
    return ans;
}
```
The algorithm uses backtracking to solve the problem. It starts by iterating through the input string, parsing every possible length substring as numbers. The algorithm maintains a list, 'ans', to keep track of the Fibonacci-like sequence formed so far and also stores the previous 2 numbers in the sequence.

The base case is when the entire string has been processed (i.e., index == string length) and the 'ans' list has at least 3 elements. In that case, we return true and stop further processing.

While iterating through the string and parsing substrings, we perform the following steps:
1. Skip the current substring if it has a leading zero but isn't just "0".
2. If the current number is greater than the 32-bit integer limit, break because it can't be a valid Fibonacci number.
3. If the list 'ans' has at least 2 elements, we check whether the sum of the previous 2 numbers is equal to the current number. If the sum is smaller, we continue to the next substring, whereas if the sum is larger, we break because any larger substring will lead to an invalid sequence.
4. If the current number is a valid candidate, we add it to the 'ans' list.
5. Perform backtracking on the next index with the updated values of previous numbers. If the backtracking returns true, exit early; otherwise, we remove the current number from the 'ans' list and continue with the next substring.


# Length of Longest Fibonacci Subsequence

- slug: length-of-longest-fibonacci-subsequence
- difficulty: Medium

A sequence `x1, x2, ..., xn` is _Fibonacci-like_ if:

*   `n >= 3`
*   `xi + xi+1 == xi+2` for all `i + 2 <= n`

Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`.

A **subsequence** is derived from another sequence `arr` by deleting any number of elements (including none) from `arr`, without changing the order of the remaining elements. For example, `[3, 5, 8]` is a subsequence of `[3, 4, 5, 6, 7, 8]`.

**Example 1:**

**Input:** arr = \[1,2,3,4,5,6,7,8\]
**Output:** 5
**Explanation:** The longest subsequence that is fibonacci-like: \[1,2,3,5,8\].

**Example 2:**

**Input:** arr = \[1,3,7,11,12,14,18\]
**Output:** 3
**Explanation**: The longest subsequence that is fibonacci-like: \[1,11,12\], \[3,11,14\] or \[7,11,18\].

**Constraints:**

*   `3 <= arr.length <= 1000`
*   `1 <= arr[i] < arr[i + 1] <= 109`

## A solution in Java

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

class Solution {
    private int match(String a, String b) {
        int matches = 0;
        for (int i = 0; i < 6; ++i)
            if (a.charAt(i) == b.charAt(i)) matches++;
        return matches;
    }

    public void findSecretWord(String[] wordlist, Master master) {
        List<String> words = new ArrayList<>();
        for (String word : wordlist) words.add(word);
        Random rand = new Random();

        for (int i = 0, matchCnt = 0; i < 10 && matchCnt < 6; ++i) {
            String guess = words.get(rand.nextInt(words.size()));
            matchCnt = master.guess(guess);
            List<String> candidates = new ArrayList<>();
            for (String word : words)
                if (match(word, guess) == matchCnt)
                    candidates.add(word);
            words = candidates;
        }
    }
}
```
1. Define a `match` function to calculate the number of exact matches between two strings.
2. For 10 iterations or until the secret word is guessed:
  a. Randomly select a word (`guess`) from the `wordlist`.
  b. Call `Master.guess` with the `guess`, and store the number of exact matches in `match_cnt`.
  c. If the `match_cnt` equals 6 (i.e., the word is guessed), terminate the loop.
  d. Filter the `wordlist` to keep only those words that have the same number of exact matches with the `guess` as `match_cnt`.
3. Complete the loop and return.

## A solution in C++

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

int match(const std::string& a, const std::string& b) {
    int matches = 0;
    for (int i = 0; i < 6; ++i)
        if (a[i] == b[i]) matches++;
    return matches;
}

void findSecretWord(std::vector<std::string>& wordlist, Master& master) {
    int n = word_list.size();
    for (int i = 0, match_cnt=0; i < 10 && match_cnt < 6; ++i) {
        std::string guess = wordlist[rand() %n];
        match_cnt = master.guess(guess);
        std::vector<std::string> candidates;
        for (const std::string& word : wordlist)
            if (match(word, guess) == match_cnt)
                candidates.push_back(word);
        wordlist = candidates;
        n = wordlist.size();
    }
}
```
1. Define a `match` function to calculate the number of exact matches between two strings.
2. For 10 iterations or until the secret word is guessed:
  a. Randomly select a word (`guess`) from the `wordlist`.
  b. Call `Master.guess` with the `guess`, and store the number of exact matches in `match_cnt`.
  c. If the `match_cnt` equals 6 (i.e., the word is guessed), terminate the loop.
  d. Filter the `wordlist` to keep only those words that have the same number of exact matches with the `guess` as `match_cnt`.
3. Complete the loop and return.

## A solution in Python

```python
import random

def match(a, b):
    return sum(a[i] == b[i] for i in range(6))

def find_secret_word(wordlist, master):
    for _ in range(10):
        guess = random.choice(wordlist)
        match_cnt = master.guess(guess)
        if match_cnt == 6:
            return
        wordlist = [word for word in wordlist if match(word, guess) == match_cnt]
```
1. Define a `match` function to calculate the number of exact matches between two strings.
2. For 10 iterations or until the secret word is guessed:
  a. Randomly select a word (`guess`) from the `wordlist`.
  b. Call `Master.guess` with the `guess`, and store the number of exact matches in `match_cnt`.
  c. If the `match_cnt` equals 6 (i.e., the word is guessed), terminate the loop.
  d. Filter the `wordlist` to keep only those words that have the same number of exact matches with the `guess` as `match_cnt`.
3. Complete the loop and return.

## A solution in Javascript

```javascript
function match(a, b) {
    let matches = 0;
    for (let i = 0; i < 6; ++i)
        if (a[i] == b[i]) matches++;
    return matches;
}

function findSecretWord(wordlist, master) {
    let n = wordlist.length;
    for (let i = 0, matchCnt = 0; i < 10 && matchCnt < 6; ++i) {
        let guess = wordlist[Math.floor(Math.random() * n)];
        matchCnt = master.guess(guess);
        let candidates = [];
        for (const word of wordlist)
            if (match(word, guess) == matchCnt)
                candidates.push(word);
        wordlist = candidates;
        n = wordlist.length;
    }
}
```
1. Define a `match` function to calculate the number of exact matches between two strings.
2. For 10 iterations or until the secret word is guessed:
  a. Randomly select a word (`guess`) from the `wordlist`.
  b. Call `Master.guess` with the `guess`, and store the number of exact matches in `match_cnt`.
  c. If the `match_cnt` equals 6 (i.e., the word is guessed), terminate the loop.
  d. Filter the `wordlist` to keep only those words that have the same number of exact matches with the `guess` as `match_cnt`.
3. Complete the loop and return.


# Walking Robot Simulation

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

A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:

*   `-2`: Turn left `90` degrees.
*   `-1`: Turn right `90` degrees.
*   `1 <= k <= 9`: Move forward `k` units, one unit at a time.

Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.

Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.

**Note:**

*   North means +Y direction.
*   East means +X direction.
*   South means -Y direction.
*   West means -X direction.

**Example 1:**

**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.

**Example 2:**

**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.

**Example 3:**

**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.

**Constraints:**

*   `1 <= commands.length <= 104`
*   `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
*   `0 <= obstacles.length <= 104`
*   `-3 * 104 <= xi, yi <= 3 * 104`
*   The answer is guaranteed to be less than `231`.

## A solution in Java

```java
import java.util.Stack;

public class Solution {
    public boolean backspaceCompare(String s, String t) {
        Stack<Character> sStack = processBackspaces(s);
        Stack<Character> tStack = processBackspaces(t);

        return sStack.equals(tStack);
    }

    private Stack<Character> processBackspaces(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c != '#') {
                stack.push(c);
            } else if (!stack.isEmpty()) {
                stack.pop();
            }
        }
        return stack;
    }
}
```
In this problem, we need to simulate the backspace (`#`) operation in a text editor. The algorithm follows these steps:

1. Initialize two stacks (`sStack` and `tStack`) to store the characters in the strings `s` and `t`. The reason for using stacks is to keep track of the characters after performing the backspace operations.
2. Iterate through both strings, and for each character:
   - If the character is not a `#`, push it onto the respective stack.
   - If the character is a `#` and the stack is not empty, pop the top element from the stack (simulate backspace).
3. Finally, compare the stacks for equality. If they are equal, it means the strings after processing backspaces are also equal.

In the C++, Java, Python, and JavaScript implementations, the code follows the same algorithm. It differs in the syntax of each language, such as using different types for the stacks or different methods to iterate through the strings.

## A solution in C++

```cpp
#include <iostream>
#include <string>
#include <stack>

bool backspaceCompare(std::string s, std::string t) {
    std::stack<char> sStack, tStack;

    for (char c : s) {
        if (c != '#') {
            sStack.push(c);
        } else if (!sStack.empty()) {
            sStack.pop();
        }
    }

    for (char c : t) {
        if (c != '#') {
            tStack.push(c);
        } else if (!tStack.empty()) {
            tStack.pop();
        }
    }

    return sStack == tStack;
}
```
In this problem, we need to simulate the backspace (`#`) operation in a text editor. The algorithm follows these steps:

1. Initialize two stacks (`sStack` and `tStack`) to store the characters in the strings `s` and `t`. The reason for using stacks is to keep track of the characters after performing the backspace operations.
2. Iterate through both strings, and for each character:
   - If the character is not a `#`, push it onto the respective stack.
   - If the character is a `#` and the stack is not empty, pop the top element from the stack (simulate backspace).
3. Finally, compare the stacks for equality. If they are equal, it means the strings after processing backspaces are also equal.

In the C++, Java, Python, and JavaScript implementations, the code follows the same algorithm. It differs in the syntax of each language, such as using different types for the stacks or different methods to iterate through the strings.

## A solution in Python

```python
def backspace_compare(s, t):
    def process_backspaces(string):
        stack = []
        for c in string:
            if c != '#':
                stack.append(c)
            elif stack:
                stack.pop()
        return stack

    return process_backspaces(s) == process_backspaces(t)
```
In this problem, we need to simulate the backspace (`#`) operation in a text editor. The algorithm follows these steps:

1. Initialize two stacks (`sStack` and `tStack`) to store the characters in the strings `s` and `t`. The reason for using stacks is to keep track of the characters after performing the backspace operations.
2. Iterate through both strings, and for each character:
   - If the character is not a `#`, push it onto the respective stack.
   - If the character is a `#` and the stack is not empty, pop the top element from the stack (simulate backspace).
3. Finally, compare the stacks for equality. If they are equal, it means the strings after processing backspaces are also equal.

In the C++, Java, Python, and JavaScript implementations, the code follows the same algorithm. It differs in the syntax of each language, such as using different types for the stacks or different methods to iterate through the strings.

## A solution in Javascript

```javascript
function backspaceCompare(s, t) {
    const processBackspaces = (string) => {
        let stack = [];
        for (let c of string) {
            if (c !== '#') {
                stack.push(c);
            } else if (stack.length > 0) {
                stack.pop();
            }
        }
        return stack;
    }

    return processBackspaces(s).join('') === processBackspaces(t).join('');
}
```
In this problem, we need to simulate the backspace (`#`) operation in a text editor. The algorithm follows these steps:

1. Initialize two stacks (`sStack` and `tStack`) to store the characters in the strings `s` and `t`. The reason for using stacks is to keep track of the characters after performing the backspace operations.
2. Iterate through both strings, and for each character:
   - If the character is not a `#`, push it onto the respective stack.
   - If the character is a `#` and the stack is not empty, pop the top element from the stack (simulate backspace).
3. Finally, compare the stacks for equality. If they are equal, it means the strings after processing backspaces are also equal.

In the C++, Java, Python, and JavaScript implementations, the code follows the same algorithm. It differs in the syntax of each language, such as using different types for the stacks or different methods to iterate through the strings.


# Koko Eating Bananas

- slug: koko-eating-bananas
- difficulty: Medium

Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours.

Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour.

Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_.

**Example 1:**

**Input:** piles = \[3,6,7,11\], h = 8
**Output:** 4

**Example 2:**

**Input:** piles = \[30,11,23,4,20\], h = 5
**Output:** 30

**Example 3:**

**Input:** piles = \[30,11,23,4,20\], h = 6
**Output:** 23

**Constraints:**

*   `1 <= piles.length <= 104`
*   `piles.length <= h <= 109`
*   `1 <= piles[i] <= 109`

## A solution in Java

```java
public int longestMountain(int[] arr) {
    int n = arr.length;
    int maxLength = 0;
    int i = 1;
    while (i < n - 1) {
        if (arr[i - 1] < arr[i] && arr[i] > arr[i + 1]) {
            int left = i - 1;
            int right = i + 1;
            while (left > 0 && arr[left - 1] < arr[left]) {
                left--;
            }
            while (right < n - 1 && arr[right] > arr[right + 1]) {
                right++;
            }
            maxLength = Math.max(maxLength, right - left + 1);
            i = right;
        } else {
            i++;
        }
    }
    return maxLength;
}
```
1. Initialize `max_length` to zero and `i` to 1. We'll use it to iterate through the input array `arr`.
2. Use a while loop to iterate through the array until we reach the second last element.
   - Check if the current element `i` is a peak (i.e., `arr[i-1] < arr[i] > arr[i+1]`).
   - If it's a peak, find the left and right boundaries of the mountain by:
       - Iterate left as long as the slope keeps ascending (`arr[left - 1] < arr[left]`).
       - Iterate right as long as the slope keeps descending (`arr[right] > arr[right + 1]`).
   - When both left and right boundaries are found, calculate the mountain length (`right - left + 1`) and compare it to the current `max_length`. Update `max_length` if the new mountain is bigger.
   - Move `i` to the right boundary and continue the loop.
   - If it's not a peak, just increment `i`.
3. Return the `max_length` of the mountains.

## A solution in C++

```cpp
#include <vector>
int longestMountain(std::vector<int>& arr) {
    int n = arr.size();
    int max_length = 0;
    int i = 1;
    while (i < n - 1) {
        if (arr[i - 1] < arr[i] && arr[i] > arr[i + 1]) {
            int left = i - 1;
            int right = i + 1;
            while (left > 0 && arr[left - 1] < arr[left]) {
                left--;
            }
            while (right < n - 1 && arr[right] > arr[right + 1]) {
                right++;
            }
            max_length = std::max(max_length, right - left + 1);
            i = right;
        } else {
            i++;
        }
    }
    return max_length;
}
```
1. Initialize `max_length` to zero and `i` to 1. We'll use it to iterate through the input array `arr`.
2. Use a while loop to iterate through the array until we reach the second last element.
   - Check if the current element `i` is a peak (i.e., `arr[i-1] < arr[i] > arr[i+1]`).
   - If it's a peak, find the left and right boundaries of the mountain by:
       - Iterate left as long as the slope keeps ascending (`arr[left - 1] < arr[left]`).
       - Iterate right as long as the slope keeps descending (`arr[right] > arr[right + 1]`).
   - When both left and right boundaries are found, calculate the mountain length (`right - left + 1`) and compare it to the current `max_length`. Update `max_length` if the new mountain is bigger.
   - Move `i` to the right boundary and continue the loop.
   - If it's not a peak, just increment `i`.
3. Return the `max_length` of the mountains.

## A solution in Python

```python
def longest_mountain(arr):
    n = len(arr)
    max_length = 0
    i = 1
    while i < n - 1:
        if arr[i - 1] < arr[i] and arr[i] > arr[i + 1]:
            left = i - 1
            right = i + 1
            while left > 0 and arr[left - 1] < arr[left]:
                left -= 1
            while right < n - 1 and arr[right] > arr[right + 1]:
                right += 1
            max_length = max(max_length, right - left + 1)
            i = right
        else:
            i += 1
    return max_length
```
1. Initialize `max_length` to zero and `i` to 1. We'll use it to iterate through the input array `arr`.
2. Use a while loop to iterate through the array until we reach the second last element.
   - Check if the current element `i` is a peak (i.e., `arr[i-1] < arr[i] > arr[i+1]`).
   - If it's a peak, find the left and right boundaries of the mountain by:
       - Iterate left as long as the slope keeps ascending (`arr[left - 1] < arr[left]`).
       - Iterate right as long as the slope keeps descending (`arr[right] > arr[right + 1]`).
   - When both left and right boundaries are found, calculate the mountain length (`right - left + 1`) and compare it to the current `max_length`. Update `max_length` if the new mountain is bigger.
   - Move `i` to the right boundary and continue the loop.
   - If it's not a peak, just increment `i`.
3. Return the `max_length` of the mountains.

## A solution in Javascript

```javascript
function longestMountain(arr) {
    let n = arr.length;
    let maxLength = 0;
    let i = 1;
    while (i < n - 1) {
        if (arr[i - 1] < arr[i] && arr[i] > arr[i + 1]) {
            let left = i - 1;
            let right = i + 1;
            while (left > 0 && arr[left - 1] < arr[left]) {
                left--;
            }
            while (right < n - 1 && arr[right] > arr[right + 1]) {
                right++;
            }
            maxLength = Math.max(maxLength, right - left + 1);
            i = right;
        } else {
            i++;
        }
    }
    return maxLength;
}
```
1. Initialize `max_length` to zero and `i` to 1. We'll use it to iterate through the input array `arr`.
2. Use a while loop to iterate through the array until we reach the second last element.
   - Check if the current element `i` is a peak (i.e., `arr[i-1] < arr[i] > arr[i+1]`).
   - If it's a peak, find the left and right boundaries of the mountain by:
       - Iterate left as long as the slope keeps ascending (`arr[left - 1] < arr[left]`).
       - Iterate right as long as the slope keeps descending (`arr[right] > arr[right + 1]`).
   - When both left and right boundaries are found, calculate the mountain length (`right - left + 1`) and compare it to the current `max_length`. Update `max_length` if the new mountain is bigger.
   - Move `i` to the right boundary and continue the loop.
   - If it's not a peak, just increment `i`.
3. Return the `max_length` of the mountains.


# Middle of the Linked List

- slug: middle-of-the-linked-list
- difficulty: Easy

Given the `head` of a singly linked list, return _the middle node of the linked list_.

If there are two middle nodes, return **the second middle** node.

**Example 1:**

**Input:** head = \[1,2,3,4,5\]
**Output:** \[3,4,5\]
**Explanation:** The middle node of the list is node 3.

**Example 2:**

**Input:** head = \[1,2,3,4,5,6\]
**Output:** \[4,5,6\]
**Explanation:** Since the list has two middle nodes with values 3 and 4, we return the second one.

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

public boolean isNStraightHand(int[] hand, int groupSize) {
    TreeMap<Integer, Integer> counts = new TreeMap<>();

    for (int card : hand) {
        counts.put(card, counts.getOrDefault(card, 0) + 1);
    }

    for (Integer key : counts.keySet()) {
        if (counts.get(key) > 0) {
            for (int i = groupSize - 1; i >= 0; --i) {
                if (counts.getOrDefault(key + i, 0) < counts.get(key)) {
                    return false;
                }
                counts.put(key + i, counts.get(key + i) - counts.get(key));
            }
        }
    }

    return true;
}
```
The algorithm uses a hashmap (Python's `Counter` class, or `Map` class in JavaScript) to count the occurrences of each card value in the hand. Then, it iterates through the card values in sorted order (using `sorted()` for Python and `sort()` for JavaScript). For each card value with positive count, it checks that it can form a group of consecutive cards of size `groupSize`. If any of these groups cannot be formed, it returns False, otherwise returns True. This approach takes advantage of the sorted order to ensure that the consecutive groups are formed in a optimal way.
\

## A solution in C++

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

bool isNStraightHand(vector<int>& hand, int groupSize) {
    map<int, int> counts;

    for (int card : hand) {
        counts[card]++;
    }

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

    return true;
}
```
The algorithm uses a hashmap (Python's `Counter` class, or `Map` class in JavaScript) to count the occurrences of each card value in the hand. Then, it iterates through the card values in sorted order (using `sorted()` for Python and `sort()` for JavaScript). For each card value with positive count, it checks that it can form a group of consecutive cards of size `groupSize`. If any of these groups cannot be formed, it returns False, otherwise returns True. This approach takes advantage of the sorted order to ensure that the consecutive groups are formed in a optimal way.
\

## A solution in Python

```python
from collections import Counter

def is_n_straight_hand(hand, group_size):
    counts = Counter(hand)

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

    return True
```
The algorithm uses a hashmap (Python's `Counter` class, or `Map` class in JavaScript) to count the occurrences of each card value in the hand. Then, it iterates through the card values in sorted order (using `sorted()` for Python and `sort()` for JavaScript). For each card value with positive count, it checks that it can form a group of consecutive cards of size `groupSize`. If any of these groups cannot be formed, it returns False, otherwise returns True. This approach takes advantage of the sorted order to ensure that the consecutive groups are formed in a optimal way.
\

## A solution in Javascript

```javascript
function isNStraightHand(hand, groupSize) {
    const counts = new Map();

    for (let card of hand) {
        counts.set(card, (counts.get(card) || 0) + 1);
    }

    for (let key of [...counts.keys()].sort((a, b) => a - b)) {
        if (counts.get(key) > 0) {
            for (let i = groupSize - 1; i >= 0; --i) {
                if ((counts.get(key + i) || 0) < counts.get(key)) {
                    return false;
                }
                counts.set(key + i, counts.get(key + i) - counts.get(key));
            }
        }
    }

    return true;
}
```
The algorithm uses a hashmap (Python's `Counter` class, or `Map` class in JavaScript) to count the occurrences of each card value in the hand. Then, it iterates through the card values in sorted order (using `sorted()` for Python and `sort()` for JavaScript). For each card value with positive count, it checks that it can form a group of consecutive cards of size `groupSize`. If any of these groups cannot be formed, it returns False, otherwise returns True. This approach takes advantage of the sorted order to ensure that the consecutive groups are formed in a optimal way.
\


# Stone Game

- slug: stone-game
- difficulty: Medium

Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`.

The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties.

Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**.

Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_.

**Example 1:**

**Input:** piles = \[5,3,4,5\]
**Output:** true
**Explanation:**
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes \[3, 4, 5\].
If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.

**Example 2:**

**Input:** piles = \[3,7,2,3\]
**Output:** true

**Constraints:**

*   `2 <= piles.length <= 500`
*   `piles.length` is **even**.
*   `1 <= piles[i] <= 500`
*   `sum(piles[i])` is **odd**.

## A solution in Java

```java
import java.util.*;

class Solution {
    public int shortestPathLength(int[][] graph) {
        int n = graph.length;
        Queue<int[]> q = new LinkedList<>();

        for(int i = 0; i < n; i++) {
            q.add(new int[]{i, 1 << i});
        }
        int steps = -1;
        boolean[][] visited = new boolean[n][1 << n];

        while(!q.isEmpty()) {
            steps++;
            int size = q.size();

            for(int k = 0; k < size; k++) {
                int[] curr = q.poll();
                int currNode = curr[0];
                int currVisits = curr[1];

                if(Integer.bitCount(currVisits) == n) return steps;

                for(int nextNode: graph[currNode]) {
                    int nextVisits = currVisits | (1 << nextNode);

                    if(!visited[nextNode][nextVisits]) {
                        visited[nextNode][nextVisits] = true;
                        q.add(new int[]{nextNode, nextVisits});
                    }
                }
            }
        }

        return -1;
    }
}
```
We will solve this problem using Breadth-First Search (BFS) algorithm with some modifications to account for visited nodes and edges. The basic idea is to start from every node, explore adjacent nodes in each step, and keep track of visited nodes and edges.

For each node, we will maintain a bitmask representing the visited nodes so far. We will create a queue data structure that will store the node along with its bitmask. Initially, push all nodes to the queue, each having only their own bit set in their bitmask.

Now, we perform the BFS algorithm. For the nodes in the current level of the queue, we retrieve the node and its bitmask. If the total number of set bits (1's) in the bitmask equals the total number of nodes (`n`), we return the current iteration counter as the shortest path length.

Otherwise, for each adjacent node, find the updated bitmask after visiting this neighbor by performing a bitwise OR operation with the current bitmask. If the updated bitmask for the neighbor hasn't been visited before, mark it as visited, and enqueue the neighbor with updated bitmask.

Repeat this process until the queue is empty or we find the shortest path length. If the queue becomes empty, return -1 as the result.

## A solution in C++

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

int shortestPathLength(vector<vector<int>>& graph) {
    int n = graph.size();
    queue<pair<int, bitset<12>>> q;

    for(int i = 0; i < n; i++) {
        q.push({i, 1 << i});
    }
    int steps = -1;
    vector<vector<bool>> visited(n, vector<bool>(1 << n));

    while(!q.empty()) {
        steps++;
        int size = q.size();

        for(int k = 0; k < size; k++) {
            int currNode = q.front().first;
            bitset<12> currVisits = q.front().second;
            q.pop();

            if(currVisits.count() == n) return steps;

            for(int nextNode: graph[currNode]) {
                bitset<12> nextVisits = currVisits;
                nextVisits.set(nextNode);

                if(!visited[nextNode][nextVisits.to_ulong()]) {
                    visited[nextNode][nextVisits.to_ulong()] = true;
                    q.push({nextNode, nextVisits});
                }
            }
        }
    }

    return -1;
}
```
We will solve this problem using Breadth-First Search (BFS) algorithm with some modifications to account for visited nodes and edges. The basic idea is to start from every node, explore adjacent nodes in each step, and keep track of visited nodes and edges.

For each node, we will maintain a bitmask representing the visited nodes so far. We will create a queue data structure that will store the node along with its bitmask. Initially, push all nodes to the queue, each having only their own bit set in their bitmask.

Now, we perform the BFS algorithm. For the nodes in the current level of the queue, we retrieve the node and its bitmask. If the total number of set bits (1's) in the bitmask equals the total number of nodes (`n`), we return the current iteration counter as the shortest path length.

Otherwise, for each adjacent node, find the updated bitmask after visiting this neighbor by performing a bitwise OR operation with the current bitmask. If the updated bitmask for the neighbor hasn't been visited before, mark it as visited, and enqueue the neighbor with updated bitmask.

Repeat this process until the queue is empty or we find the shortest path length. If the queue becomes empty, return -1 as the result.

## A solution in Python

```python
from collections import deque, defaultdict

def shortestPathLength(graph):
    n = len(graph)
    q = deque()

    for i in range(n):
        q.append((i, 1 << i))
    steps = -1
    visited = {i: set() for i in range(n)}

    while q:
        steps += 1
        for _ in range(len(q)):
            currNode, currVisits = q.popleft()

            if bin(currVisits).count('1') == n:
                return steps

            for nextNode in graph[currNode]:
                nextVisits = currVisits | (1 << nextNode)

                if nextVisits not in visited[nextNode]:
                    visited[nextNode].add(nextVisits)
                    q.append((nextNode, nextVisits))

    return -1
```
We will solve this problem using Breadth-First Search (BFS) algorithm with some modifications to account for visited nodes and edges. The basic idea is to start from every node, explore adjacent nodes in each step, and keep track of visited nodes and edges.

For each node, we will maintain a bitmask representing the visited nodes so far. We will create a queue data structure that will store the node along with its bitmask. Initially, push all nodes to the queue, each having only their own bit set in their bitmask.

Now, we perform the BFS algorithm. For the nodes in the current level of the queue, we retrieve the node and its bitmask. If the total number of set bits (1's) in the bitmask equals the total number of nodes (`n`), we return the current iteration counter as the shortest path length.

Otherwise, for each adjacent node, find the updated bitmask after visiting this neighbor by performing a bitwise OR operation with the current bitmask. If the updated bitmask for the neighbor hasn't been visited before, mark it as visited, and enqueue the neighbor with updated bitmask.

Repeat this process until the queue is empty or we find the shortest path length. If the queue becomes empty, return -1 as the result.

## A solution in Javascript

```javascript
function shortestPathLength(graph) {
    const n = graph.length;
    const q = [];

    for(let i = 0; i < n; i++) {
        q.push([i, 1 << i]);
    }
    let steps = -1;
    const visited = Array.from({length: n}, () => Array(1 << n).fill(false));

    while(q.length > 0) {
        steps++;
        const size = q.length;

        for(let k = 0; k < size; k++) {
            const [currNode, currVisits] = q.shift();

            if(currVisits.toString(2).split('').filter(v => v === '1').length === n) return steps;

            for(const nextNode of graph[currNode]) {
                const nextVisits = currVisits | (1 << nextNode);

                if(!visited[nextNode][nextVisits]) {
                    visited[nextNode][nextVisits] = true;
                    q.push([nextNode, nextVisits]);
                }
            }
        }
    }

    return -1;
}
```
We will solve this problem using Breadth-First Search (BFS) algorithm with some modifications to account for visited nodes and edges. The basic idea is to start from every node, explore adjacent nodes in each step, and keep track of visited nodes and edges.

For each node, we will maintain a bitmask representing the visited nodes so far. We will create a queue data structure that will store the node along with its bitmask. Initially, push all nodes to the queue, each having only their own bit set in their bitmask.

Now, we perform the BFS algorithm. For the nodes in the current level of the queue, we retrieve the node and its bitmask. If the total number of set bits (1's) in the bitmask equals the total number of nodes (`n`), we return the current iteration counter as the shortest path length.

Otherwise, for each adjacent node, find the updated bitmask after visiting this neighbor by performing a bitwise OR operation with the current bitmask. If the updated bitmask for the neighbor hasn't been visited before, mark it as visited, and enqueue the neighbor with updated bitmask.

Repeat this process until the queue is empty or we find the shortest path length. If the queue becomes empty, return -1 as the result.


# Nth Magical Number

- slug: nth-magical-number
- difficulty: Hard

A positive integer is _magical_ if it is divisible by either `a` or `b`.

Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.

**Example 1:**

**Input:** n = 1, a = 2, b = 3
**Output:** 2

**Example 2:**

**Input:** n = 4, a = 2, b = 3
**Output:** 6

**Constraints:**

*   `1 <= n <= 109`
*   `2 <= a, b <= 4 * 104`

## A solution in Java

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

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

        return new String(result);
    }
}
```
First, we update the shifts array by iterating it from right to left and adding the next element in the array, mod 26, to the current element. This way, we accumulate the total shifts required for each character in the array.

Then, we create an empty result string or array (depending on the language) and iterate through the input string. For each character, we calculate the new character after shifting and append/insert it to the result string.

Finally, we return the resulting string.

## A solution in C++

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

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

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

    return s;
}
```
First, we update the shifts array by iterating it from right to left and adding the next element in the array, mod 26, to the current element. This way, we accumulate the total shifts required for each character in the array.

Then, we create an empty result string or array (depending on the language) and iterate through the input string. For each character, we calculate the new character after shifting and append/insert it to the result string.

Finally, we return the resulting string.

## A solution in Python

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

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

    return "".join(result)
```
First, we update the shifts array by iterating it from right to left and adding the next element in the array, mod 26, to the current element. This way, we accumulate the total shifts required for each character in the array.

Then, we create an empty result string or array (depending on the language) and iterate through the input string. For each character, we calculate the new character after shifting and append/insert it to the result string.

Finally, we return the resulting string.

## A solution in Javascript

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

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

    return result;
}
```
First, we update the shifts array by iterating it from right to left and adding the next element in the array, mod 26, to the current element. This way, we accumulate the total shifts required for each character in the array.

Then, we create an empty result string or array (depending on the language) and iterate through the input string. For each character, we calculate the new character after shifting and append/insert it to the result string.

Finally, we return the resulting string.


# Profitable Schemes

- slug: profitable-schemes
- difficulty: Hard

There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime.

Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`.

Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`.

**Example 1:**

**Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\]
**Output:** 2
**Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.

**Example 2:**

**Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\]
**Output:** 7
**Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).

**Constraints:**

*   `1 <= n <= 100`
*   `0 <= minProfit <= 100`
*   `1 <= group.length <= 100`
*   `1 <= group[i] <= 100`
*   `profit.length == group.length`
*   `0 <= profit[i] <= 100`

## A solution in Java

```java
public int maxDistToClosest(int[] seats) {
    int maxDist = 0, lastPerson = -1;
    for (int i = 0; i < seats.length; ++i) {
        if (seats[i] == 1) {
            maxDist = lastPerson < 0 ? i : Math.max(maxDist, (i - lastPerson) / 2);
            lastPerson = i;
        }
    }
    return Math.max(maxDist, seats.length - 1 - lastPerson);
}
```
First, initialize `max_dist` to store the maximum distance encountered and `last_person` to store the index of the last person found in the array. Iterate through the array of `seats`, for each person encountered (seats[i] == 1), calculate the distance between the current index and the last person, divide it by 2, and update `max_dist` with the maximum of its current value, the distance calculated or the index (i) if it's the first person found. Update the last person index to the current index (i). Once the iteration is complete, return the maximum of `max_dist` and the distance between the last person and the end of the array.

## A solution in C++

```cpp
int maxDistToClosest(vector<int>& seats) {
    int max_dist = 0, last_person = -1;
    for (int i = 0; i < seats.size(); ++i) {
        if (seats[i] == 1) {
            max_dist = last_person < 0 ? i : max(max_dist, (i - last_person) / 2);
            last_person = i;
        }
    }
    return max(max_dist, (int)(seats.size() - 1 - last_person));
}
```
First, initialize `max_dist` to store the maximum distance encountered and `last_person` to store the index of the last person found in the array. Iterate through the array of `seats`, for each person encountered (seats[i] == 1), calculate the distance between the current index and the last person, divide it by 2, and update `max_dist` with the maximum of its current value, the distance calculated or the index (i) if it's the first person found. Update the last person index to the current index (i). Once the iteration is complete, return the maximum of `max_dist` and the distance between the last person and the end of the array.

## A solution in Python

```python
def max_dist_to_closest(seats):
    max_dist = 0
    last_person = -1
    for i, seat in enumerate(seats):
        if seat == 1:
            max_dist = i if last_person < 0 else max(max_dist, (i - last_person) // 2)
            last_person = i
    return max(max_dist, len(seats) - 1 - last_person)
```
First, initialize `max_dist` to store the maximum distance encountered and `last_person` to store the index of the last person found in the array. Iterate through the array of `seats`, for each person encountered (seats[i] == 1), calculate the distance between the current index and the last person, divide it by 2, and update `max_dist` with the maximum of its current value, the distance calculated or the index (i) if it's the first person found. Update the last person index to the current index (i). Once the iteration is complete, return the maximum of `max_dist` and the distance between the last person and the end of the array.

## A solution in Javascript

```javascript
function maxDistToClosest(seats) {
    let maxDist = 0, lastPerson = -1;
    for (let i = 0; i < seats.length; ++i) {
        if (seats[i] == 1) {
            maxDist = lastPerson < 0 ? i : Math.max(maxDist, ((i - lastPerson) / 2) | 0);
            lastPerson = i;
        }
    }
    return Math.max(maxDist, seats.length - 1 - lastPerson);
}
```
First, initialize `max_dist` to store the maximum distance encountered and `last_person` to store the index of the last person found in the array. Iterate through the array of `seats`, for each person encountered (seats[i] == 1), calculate the distance between the current index and the last person, divide it by 2, and update `max_dist` with the maximum of its current value, the distance calculated or the index (i) if it's the first person found. Update the last person index to the current index (i). Once the iteration is complete, return the maximum of `max_dist` and the distance between the last person and the end of the array.