# The Number of Weak Characters in the Game

- slug: the-number-of-weak-characters-in-the-game
- difficulty: Medium

You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game.

A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`.

Return _the number of **weak** characters_.

**Example 1:**

**Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\]
**Output:** 0
**Explanation:** No character has strictly greater attack and defense than the other.

**Example 2:**

**Input:** properties = \[\[2,2\],\[3,3\]\]
**Output:** 1
**Explanation:** The first character is weak because the second character has a strictly greater attack and defense.

**Example 3:**

**Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\]
**Output:** 1
**Explanation:** The third character is weak because the second character has a strictly greater attack and defense.

**Constraints:**

*   `2 <= properties.length <= 105`
*   `properties[i].length == 2`
*   `1 <= attacki, defensei <= 105`

## A solution in Java

```java
int numberOfSticks(int n, int k) {
    final int MOD = (int) 1e9 + 7;
    if (n < k) return 0;
    int[][] dp = new int[n+1][n+1];

    for (int i = 1; i <= n; i++) {
        dp[i][1] = 1;
        for (int j = 2; j <= i; j++)
            dp[i][j] = (dp[i-1][j-1] + (i-1) * dp[i-1][j]) % MOD;
    }
    return dp[n][k];
}
```
We will use dynamic programming to solve this problem. We will have a 2D array `dp[i][j]` that represents the number of ways to arrange i sticks such that exactly j sticks are visible from the left. We initialize `dp[i][1] = 1` for all i, because there is always 1 way to arrange i sticks such that only 1 stick is visible from the left (placing the largest stick at the beginning).

Now let's fill out the dp array iteratively. At each step, we can either make the current stick visible or not visible. If we make the stick visible, there would be `dp[i-1][j-1]` ways to arrange the remaining sticks, since there are now j-1 visible sticks needed for the first i-1 sticks. If we don't make the stick visible, there would be `(i-1) * dp[i-1][j]` ways to arrange the remaining sticks, because there are still j visible sticks needed but there are now i-1 positions to place the current stick (it can be placed behind any of the first i-1 sticks). We add these two cases together and take the result modulo 10^9+7.

The function returns `dp[n][k]` as the final result.

## A solution in C++

```cpp
int numberOfSticks(int n, int k) {
    const int MOD = 1e9 + 7;
    if (n < k) return 0;
    int dp[n+1][n+1];
    memset(dp, 0, sizeof(dp));

    for (int i = 1; i <= n; i++) {
        dp[i][1] = 1;
        for (int j = 2; j <= i; j++)
            dp[i][j] = (dp[i-1][j-1] + (i-1) * dp[i-1][j]) % MOD;
    }
    return dp[n][k];
}
```
We will use dynamic programming to solve this problem. We will have a 2D array `dp[i][j]` that represents the number of ways to arrange i sticks such that exactly j sticks are visible from the left. We initialize `dp[i][1] = 1` for all i, because there is always 1 way to arrange i sticks such that only 1 stick is visible from the left (placing the largest stick at the beginning).

Now let's fill out the dp array iteratively. At each step, we can either make the current stick visible or not visible. If we make the stick visible, there would be `dp[i-1][j-1]` ways to arrange the remaining sticks, since there are now j-1 visible sticks needed for the first i-1 sticks. If we don't make the stick visible, there would be `(i-1) * dp[i-1][j]` ways to arrange the remaining sticks, because there are still j visible sticks needed but there are now i-1 positions to place the current stick (it can be placed behind any of the first i-1 sticks). We add these two cases together and take the result modulo 10^9+7.

The function returns `dp[n][k]` as the final result.

## A solution in Python

```python
def numberOfSticks(n, k):
    MOD = 10**9 + 7
    if n < k: return 0
    dp = [[0] * (n+1) for _ in range(n+1)]

    for i in range(1, n+1):
        dp[i][1] = 1
        for j in range(2, i+1):
            dp[i][j] = (dp[i-1][j-1] + (i-1) * dp[i-1][j]) % MOD

    return dp[n][k]
```
We will use dynamic programming to solve this problem. We will have a 2D array `dp[i][j]` that represents the number of ways to arrange i sticks such that exactly j sticks are visible from the left. We initialize `dp[i][1] = 1` for all i, because there is always 1 way to arrange i sticks such that only 1 stick is visible from the left (placing the largest stick at the beginning).

Now let's fill out the dp array iteratively. At each step, we can either make the current stick visible or not visible. If we make the stick visible, there would be `dp[i-1][j-1]` ways to arrange the remaining sticks, since there are now j-1 visible sticks needed for the first i-1 sticks. If we don't make the stick visible, there would be `(i-1) * dp[i-1][j]` ways to arrange the remaining sticks, because there are still j visible sticks needed but there are now i-1 positions to place the current stick (it can be placed behind any of the first i-1 sticks). We add these two cases together and take the result modulo 10^9+7.

The function returns `dp[n][k]` as the final result.

## A solution in Javascript

```javascript
function numberOfSticks(n, k) {
    const MOD = 1e9 + 7;
    if (n < k) return 0;
    let dp = Array.from({ length: n+1 }, () => Array(n+1).fill(0));

    for (let i = 1; i <= n; i++) {
        dp[i][1] = 1;
        for (let j = 2; j <= i; j++)
            dp[i][j] = (dp[i-1][j-1] + (i-1) * dp[i-1][j]) % MOD;
    }
    return dp[n][k];
}
```
We will use dynamic programming to solve this problem. We will have a 2D array `dp[i][j]` that represents the number of ways to arrange i sticks such that exactly j sticks are visible from the left. We initialize `dp[i][1] = 1` for all i, because there is always 1 way to arrange i sticks such that only 1 stick is visible from the left (placing the largest stick at the beginning).

Now let's fill out the dp array iteratively. At each step, we can either make the current stick visible or not visible. If we make the stick visible, there would be `dp[i-1][j-1]` ways to arrange the remaining sticks, since there are now j-1 visible sticks needed for the first i-1 sticks. If we don't make the stick visible, there would be `(i-1) * dp[i-1][j]` ways to arrange the remaining sticks, because there are still j visible sticks needed but there are now i-1 positions to place the current stick (it can be placed behind any of the first i-1 sticks). We add these two cases together and take the result modulo 10^9+7.

The function returns `dp[n][k]` as the final result.


# First Day Where You Have Been in All the Rooms

- slug: first-day-where-you-have-been-in-all-the-rooms
- difficulty: Medium

There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day.

Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `nextVisit` of length `n`:

*   Assuming that on a day, you visit room `i`,
*   if you have been in room `i` an **odd** number of times (**including** the current visit), on the **next** day you will visit a room with a **lower or equal room number** specified by `nextVisit[i]` where `0 <= nextVisit[i] <= i`;
*   if you have been in room `i` an **even** number of times (**including** the current visit), on the **next** day you will visit room `(i + 1) mod n`.

Return _the label of the **first** day where you have been in **all** the rooms_. It can be shown that such a day exists. Since the answer may be very large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** nextVisit = \[0,0\]
**Output:** 2
**Explanation:**
- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.
  On the next day you will visit room nextVisit\[0\] = 0
- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.
  On the next day you will visit room (0 + 1) mod 2 = 1
- On day 2, you visit room 1. This is the first day where you have been in all the rooms.

**Example 2:**

**Input:** nextVisit = \[0,0,2\]
**Output:** 6
**Explanation:**
Your room visiting order for each day is: \[0,0,1,0,0,1,2,...\].
Day 6 is the first day where you have been in all the rooms.

**Example 3:**

**Input:** nextVisit = \[0,1,2,0\]
**Output:** 6
**Explanation:**
Your room visiting order for each day is: \[0,0,1,1,2,2,3,...\].
Day 6 is the first day where you have been in all the rooms.

**Constraints:**

*   `n == nextVisit.length`
*   `2 <= n <= 105`
*   `0 <= nextVisit[i] <= i`

## A solution in Java

```java
public int firstDayBeenInAllRooms(int[] nextVisit) {
    int n = nextVisit.length;
    long ans = 0;
    long MOD = 1000000007;
    long[] dp = new long[n];

    for (int i = 1; i < n; ++i) {
        dp[i] = (dp[i - 1] * 2 - dp[nextVisit[i - 1]] + 2) % MOD;
    }

    return (int)dp[n - 1];
}
```
The algorithm can be solved using Dynamic Programming - specifically, by keeping track of the first day when the room `i` is visited in a `dp` array.

We can calculate the value of `dp[i]` based on `dp[i-1]` and `dp[nextVisit[i-1]]`._visit[i-1]]. RootStateRoomTime - startTime[nextVisit[i - 1]]+2[DP[i++]=dp[i-1]*2-DP[nextVisit[i-1]]+2%MOD.

The result will be the value in `dp` at index `n-1`

## A solution in C++

```cpp
int firstDayBeenInAllRooms(vector<int>& nextVisit) {
    int n = nextVisit.size();
    long long ans = 0, MOD = 1e9 + 7;
    vector<long long> dp(n, 0);

    for (int i = 1; i < n; ++i) {
        dp[i] = (dp[i - 1] * 2 - dp[nextVisit[i - 1]] + 2) % MOD;
    }

    return dp[n - 1];
}
```
The algorithm can be solved using Dynamic Programming - specifically, by keeping track of the first day when the room `i` is visited in a `dp` array.

We can calculate the value of `dp[i]` based on `dp[i-1]` and `dp[nextVisit[i-1]]`._visit[i-1]]. RootStateRoomTime - startTime[nextVisit[i - 1]]+2[DP[i++]=dp[i-1]*2-DP[nextVisit[i-1]]+2%MOD.

The result will be the value in `dp` at index `n-1`

## A solution in Python

```python
def firstDayBeenInAllRooms(nextVisit):
    n = len(nextVisit)
    MOD = 10**9 + 7
    dp = [0] * n

    for i in range(1, n):
        dp[i] = (dp[i - 1] * 2 - dp[nextVisit[i - 1]] + 2) % MOD

    return dp[n - 1]
```
The algorithm can be solved using Dynamic Programming - specifically, by keeping track of the first day when the room `i` is visited in a `dp` array.

We can calculate the value of `dp[i]` based on `dp[i-1]` and `dp[nextVisit[i-1]]`._visit[i-1]]. RootStateRoomTime - startTime[nextVisit[i - 1]]+2[DP[i++]=dp[i-1]*2-DP[nextVisit[i-1]]+2%MOD.

The result will be the value in `dp` at index `n-1`

## A solution in Javascript

```javascript
function firstDayBeenInAllRooms(nextVisit) {
    let n = nextVisit.length;
    let ans = 0, MOD = BigInt(1e9 + 7);
    let dp = new Array(n).fill(BigInt(0));

    for (let i = 1; i < n; ++i) {
        dp[i] = (dp[i - 1] * BigInt(2) - dp[nextVisit[i - 1]] + BigInt(2)) % MOD;
    }

    return parseInt(dp[n - 1]);
}
```
The algorithm can be solved using Dynamic Programming - specifically, by keeping track of the first day when the room `i` is visited in a `dp` array.

We can calculate the value of `dp[i]` based on `dp[i-1]` and `dp[nextVisit[i-1]]`._visit[i-1]]. RootStateRoomTime - startTime[nextVisit[i - 1]]+2[DP[i++]=dp[i-1]*2-DP[nextVisit[i-1]]+2%MOD.

The result will be the value in `dp` at index `n-1`


# GCD Sort of an Array

- slug: gcd-sort-of-an-array
- difficulty: Hard

You are given an integer array `nums`, and you can perform the following operation **any** number of times on `nums`:

*   Swap the positions of two elements `nums[i]` and `nums[j]` if `gcd(nums[i], nums[j]) > 1` where `gcd(nums[i], nums[j])` is the **greatest common divisor** of `nums[i]` and `nums[j]`.

Return `true` _if it is possible to sort_ `nums` _in **non-decreasing** order using the above swap method, or_ `false` _otherwise._

**Example 1:**

**Input:** nums = \[7,21,3\]
**Output:** true
**Explanation:** We can sort \[7,21,3\] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = \[**21**,**7**,3\]
- Swap 21 and 3 because gcd(21,3) = 3. nums = \[**3**,7,**21**\]

**Example 2:**

**Input:** nums = \[5,2,6,2\]
**Output:** false
**Explanation:** It is impossible to sort the array because 5 cannot be swapped with any other element.

**Example 3:**

**Input:** nums = \[10,5,9,3,15\]
**Output:** true
We can sort \[10,5,9,3,15\] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = \[**15**,5,9,3,**10**\]
- Swap 15 and 3 because gcd(15,3) = 3. nums = \[**3**,5,9,**15**,10\]
- Swap 10 and 15 because gcd(10,15) = 5. nums = \[3,5,9,**10**,**15**\]

**Constraints:**

*   `1 <= nums.length <= 3 * 104`
*   `2 <= nums[i] <= 105`

## A solution in Java

```java
import java.util.Arrays;

public boolean canBeSorted(int[] nums) {
    int[] sorted_nums = Arrays.copyOf(nums, nums.length);
    Arrays.sort(sorted_nums);
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] != sorted_nums[i] && gcd(nums[i], sorted_nums[i]) == 1) {
            return false;
        }
    }
    return true;
}

private int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}
```
The first step is to create a sorted copy of the input array `nums`. Then, iterate through the input array and check if each element matches the corresponding element in the sorted copy. If an element in both arrays is different, calculate the gcd of these elements. If the gcd is 1, return false because the two elements cannot be swapped. Otherwise, move on to the next element. If the loop finishes without finding a pair of numbers with a gcd of 1, return true.

## A solution in C++

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

bool canBeSorted(std::vector<int>& nums) {
    std::vector<int> sorted_nums = nums;
    sort(sorted_nums.begin(), sorted_nums.end());
    for (size_t i = 0; i < nums.size(); ++i) {
        if (nums[i] != sorted_nums[i] && std::gcd(nums[i], sorted_nums[i]) == 1) {
            return false;
        }
    }
    return true;
}
```
The first step is to create a sorted copy of the input array `nums`. Then, iterate through the input array and check if each element matches the corresponding element in the sorted copy. If an element in both arrays is different, calculate the gcd of these elements. If the gcd is 1, return false because the two elements cannot be swapped. Otherwise, move on to the next element. If the loop finishes without finding a pair of numbers with a gcd of 1, return true.

## A solution in Python

```python
from math import gcd

def can_be_sorted(nums):
    sorted_nums = sorted(nums)
    for i in range(len(nums)):
        if nums[i] != sorted_nums[i] and gcd(nums[i], sorted_nums[i]) == 1:
            return False
    return True
```
The first step is to create a sorted copy of the input array `nums`. Then, iterate through the input array and check if each element matches the corresponding element in the sorted copy. If an element in both arrays is different, calculate the gcd of these elements. If the gcd is 1, return false because the two elements cannot be swapped. Otherwise, move on to the next element. If the loop finishes without finding a pair of numbers with a gcd of 1, return true.

## A solution in Javascript

```javascript
function canBeSorted(nums) {
    const sorted_nums = nums.slice().sort((a, b) => a - b);
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] !== sorted_nums[i] && gcd(nums[i], sorted_nums[i]) === 1) {
            return false;
        }
    }
    return true;
}

function gcd(a, b) {
    let temp;
    while (b !== 0) {
        temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}
```
The first step is to create a sorted copy of the input array `nums`. Then, iterate through the input array and check if each element matches the corresponding element in the sorted copy. If an element in both arrays is different, calculate the gcd of these elements. If the gcd is 1, return false because the two elements cannot be swapped. Otherwise, move on to the next element. If the loop finishes without finding a pair of numbers with a gcd of 1, return true.


# Smallest Greater Multiple Made of Two Digits

- slug: smallest-greater-multiple-made-of-two-digits
- difficulty: Medium

Given three integers, `k`, `digit1`, and `digit2`, you want to find the **smallest** integer that is:

*   **Larger** than `k`,
*   A **multiple** of `k`, and
*   Comprised of **only** the digits `digit1` and/or `digit2`.

Return _the **smallest** such integer. If no such integer exists or the integer exceeds the limit of a signed 32-bit integer (_`231 - 1`_), return_ `-1`.

**Example 1:**

**Input:** k = 2, digit1 = 0, digit2 = 2
**Output:** 20
**Explanation:**
20 is the first integer larger than 2, a multiple of 2, and comprised of only the digits 0 and/or 2.

**Example 2:**

**Input:** k = 3, digit1 = 4, digit2 = 2
**Output:** 24
**Explanation:**
24 is the first integer larger than 3, a multiple of 3, and comprised of only the digits 4 and/or 2.

**Example 3:**

**Input:** k = 2, digit1 = 0, digit2 = 0
**Output:** -1
**Explanation:**
No integer meets the requirements so return -1.

**Constraints:**

*   `1 <= k <= 1000`
*   `0 <= digit1 <= 9`
*   `0 <= digit2 <= 9`

## A solution in Java

```java
public boolean checkZeroOnes(String s) {
    int longestZero = 0;
    int longestOne = 0;
    int currentZero = 0;
    int currentOne = 0;

    for (char c : s.toCharArray()) {
        if (c == '0') {
            currentZero++;
            longestZero = Math.max(longestZero, currentZero);
            currentOne = 0;
        } else {
            currentOne++;
            longestOne = Math.max(longestOne, currentOne);
            currentZero = 0;
        }
    }
    return longestOne > longestZero;
}
```
1. Initialize variables for tracking the lengths of the longest and current segments of 0's and 1's.
2. Iterate through the string.
3. For each character, update the corresponding current segment length and compare it with the longest segment length.
   a. If the current character is '0', increment the current segment of 0's, update the longest segment of 0's if necessary, and reset the current segment of 1's.
   b. If the current character is '1', increment the current segment of 1's, update the longest segment of 1's if necessary, and reset the current segment of 0's.
4. After the iteration, compare the lengths of the longest segments of 0's and 1's and return the result as a boolean.

## A solution in C++

```cpp
bool checkZeroOnes(std::string s) {
    int longestZero = 0;
    int longestOne = 0;
    int currentZero = 0;
    int currentOne = 0;

    for (char c : s) {
        if (c == '0') {
            currentZero++;
            longestZero = std::max(longestZero, currentZero);
            currentOne = 0;
        } else {
            currentOne++;
            longestOne = std::max(longestOne, currentOne);
            currentZero = 0;
        }
    }
    return longestOne > longestZero;
}
```
1. Initialize variables for tracking the lengths of the longest and current segments of 0's and 1's.
2. Iterate through the string.
3. For each character, update the corresponding current segment length and compare it with the longest segment length.
   a. If the current character is '0', increment the current segment of 0's, update the longest segment of 0's if necessary, and reset the current segment of 1's.
   b. If the current character is '1', increment the current segment of 1's, update the longest segment of 1's if necessary, and reset the current segment of 0's.
4. After the iteration, compare the lengths of the longest segments of 0's and 1's and return the result as a boolean.

## A solution in Python

```python
def checkZeroOnes(s: str) -> bool:
    longest_zero = longest_one = current_zero = current_one = 0

    for c in s:
        if c == '0':
            current_zero += 1
            longest_zero = max(longest_zero, current_zero)
            current_one = 0
        else:
            current_one += 1
            longest_one = max(longest_one, current_one)
            current_zero = 0

    return longest_one > longest_zero
```
1. Initialize variables for tracking the lengths of the longest and current segments of 0's and 1's.
2. Iterate through the string.
3. For each character, update the corresponding current segment length and compare it with the longest segment length.
   a. If the current character is '0', increment the current segment of 0's, update the longest segment of 0's if necessary, and reset the current segment of 1's.
   b. If the current character is '1', increment the current segment of 1's, update the longest segment of 1's if necessary, and reset the current segment of 0's.
4. After the iteration, compare the lengths of the longest segments of 0's and 1's and return the result as a boolean.

## A solution in Javascript

```javascript
function checkZeroOnes(s) {
    let longestZero = 0;
    let longestOne = 0;
    let currentZero = 0;
    let currentOne = 0;

    for (let c of s) {
        if (c === '0') {
            currentZero++;
            longestZero = Math.max(longestZero, currentZero);
            currentOne = 0;
        } else {
            currentOne++;
            longestOne = Math.max(longestOne, currentOne);
            currentZero = 0;
        }
    }
    return longestOne > longestZero;
}
```
1. Initialize variables for tracking the lengths of the longest and current segments of 0's and 1's.
2. Iterate through the string.
3. For each character, update the corresponding current segment length and compare it with the longest segment length.
   a. If the current character is '0', increment the current segment of 0's, update the longest segment of 0's if necessary, and reset the current segment of 1's.
   b. If the current character is '1', increment the current segment of 1's, update the longest segment of 1's if necessary, and reset the current segment of 0's.
4. After the iteration, compare the lengths of the longest segments of 0's and 1's and return the result as a boolean.


# Reverse Prefix of Word

- slug: reverse-prefix-of-word
- difficulty: Easy

Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing.

*   For example, if `word = "abcdefd "` and `ch = "d "`, then you should **reverse** the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd "`.

Return _the resulting string_.

**Example 1:**

**Input:** word =  "abcdefd ", ch =  "d "
**Output:**  "dcbaefd "
**Explanation:** The first occurrence of  "d " is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is  "dcbaefd ".

**Example 2:**

**Input:** word =  "xyxzxe ", ch =  "z "
**Output:**  "zxyxxe "
**Explanation:** The first and only occurrence of  "z " is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is  "zxyxxe ".

**Example 3:**

**Input:** word =  "abcd ", ch =  "z "
**Output:**  "abcd "
**Explanation:**  "z " does not exist in word.
You should not do any reverse operation, the resulting string is  "abcd ".

**Constraints:**

*   `1 <= word.length <= 250`
*   `word` consists of lowercase English letters.
*   `ch` is a lowercase English letter.

## A solution in Java

```java
class Solution {
    public int minimumSpeed(int n, float hour, int[] dist) {
        if (n > Math.ceil(hour)) return -1;
        int low = 1, high = 10000000, mid, speed;

        while (low <= high) {
            mid = low + (high - low) / 2;
            float time = 0;
            for (int i = 0; i < n; ++i) {
                time += Math.ceil(dist[i] * 1.0 / mid);
            }
            if (time <= hour) {
                speed = mid;
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }

        return speed;
    }
}
```
The algorithm uses a binary search approach to find the minimum positive integer speed required for all trains to be on time. At first, we check if it's impossible to reach on time by counting if the number of distinct integer hours is less than the number of trains, if so we return `-1`. Then, we initialize the search space to be from 1 to (10^7). Within this search space, we calculate the sum of the time for each set of speeds from the middle of the search space. If this total time is less than or equal to the given hour, we choose the middle speed and reduce the search space to the left (since we are looking for the minimum speed). If the time is greater than the given hour, we increase the search space to the right. The process continues in this manner until we find the minimum speed required for the trains.

## A solution in C++

```cpp
#include <cmath>
#include <vector>
int minimumSpeed(int n, float hour, std::vector<int>& dist) {
    if (n > ceil(hour)) return -1;
    int low = 1, high = 1e7, mid, speed;

    while (low <= high) {
        mid = low + (high - low) / 2;
        float time = 0;
        for (int i = 0; i < n; ++i) {
            time += ceil(dist[i] * 1.0 / mid);
        }
        if (time <= hour) {
            speed = mid;
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    return speed;
}
```
The algorithm uses a binary search approach to find the minimum positive integer speed required for all trains to be on time. At first, we check if it's impossible to reach on time by counting if the number of distinct integer hours is less than the number of trains, if so we return `-1`. Then, we initialize the search space to be from 1 to (10^7). Within this search space, we calculate the sum of the time for each set of speeds from the middle of the search space. If this total time is less than or equal to the given hour, we choose the middle speed and reduce the search space to the left (since we are looking for the minimum speed). If the time is greater than the given hour, we increase the search space to the right. The process continues in this manner until we find the minimum speed required for the trains.

## A solution in Python

```python
import math
def minimum_speed(n, hour, dist):
    if n > math.ceil(hour): return -1
    low, high = 1, int(1e7)

    while low <= high:
        mid = low + (high - low) // 2
        time = sum(math.ceil(d / mid) for d in dist)
        if time <= hour:
            speed = mid
            high = mid - 1
        else:
            low = mid + 1

    return speed
```
The algorithm uses a binary search approach to find the minimum positive integer speed required for all trains to be on time. At first, we check if it's impossible to reach on time by counting if the number of distinct integer hours is less than the number of trains, if so we return `-1`. Then, we initialize the search space to be from 1 to (10^7). Within this search space, we calculate the sum of the time for each set of speeds from the middle of the search space. If this total time is less than or equal to the given hour, we choose the middle speed and reduce the search space to the left (since we are looking for the minimum speed). If the time is greater than the given hour, we increase the search space to the right. The process continues in this manner until we find the minimum speed required for the trains.

## A solution in Javascript

```javascript
function minimumSpeed(n, hour, dist) {
    if (n > Math.ceil(hour)) return -1;
    let low = 1, high = 1e7, mid, speed;

    while (low <= high) {
        mid = low + Math.floor((high - low) / 2);
        let time = 0;
        for (let i = 0; i < n; ++i) {
            time += Math.ceil(dist[i] * 1.0 / mid);
        }
        if (time <= hour) {
            speed = mid;
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }

    return speed;
}
```
The algorithm uses a binary search approach to find the minimum positive integer speed required for all trains to be on time. At first, we check if it's impossible to reach on time by counting if the number of distinct integer hours is less than the number of trains, if so we return `-1`. Then, we initialize the search space to be from 1 to (10^7). Within this search space, we calculate the sum of the time for each set of speeds from the middle of the search space. If this total time is less than or equal to the given hour, we choose the middle speed and reduce the search space to the left (since we are looking for the minimum speed). If the time is greater than the given hour, we increase the search space to the right. The process continues in this manner until we find the minimum speed required for the trains.


# Number of Pairs of Interchangeable Rectangles

- slug: number-of-pairs-of-interchangeable-rectangles
- difficulty: Medium

You are given `n` rectangles represented by a **0-indexed** 2D integer array `rectangles`, where `rectangles[i] = [widthi, heighti]` denotes the width and height of the `ith` rectangle.

Two rectangles `i` and `j` (`i < j`) are considered **interchangeable** if they have the **same** width-to-height ratio. More formally, two rectangles are **interchangeable** if `widthi/heighti == widthj/heightj` (using decimal division, not integer division).

Return _the **number** of pairs of **interchangeable** rectangles in_ `rectangles`.

**Example 1:**

**Input:** rectangles = \[\[4,8\],\[3,6\],\[10,20\],\[15,30\]\]
**Output:** 6
**Explanation:** The following are the interchangeable pairs of rectangles by index (0-indexed):
- Rectangle 0 with rectangle 1: 4/8 == 3/6.
- Rectangle 0 with rectangle 2: 4/8 == 10/20.
- Rectangle 0 with rectangle 3: 4/8 == 15/30.
- Rectangle 1 with rectangle 2: 3/6 == 10/20.
- Rectangle 1 with rectangle 3: 3/6 == 15/30.
- Rectangle 2 with rectangle 3: 10/20 == 15/30.

**Example 2:**

**Input:** rectangles = \[\[4,5\],\[7,8\]\]
**Output:** 0
**Explanation:** There are no interchangeable pairs of rectangles.

**Constraints:**

*   `n == rectangles.length`
*   `1 <= n <= 105`
*   `rectangles[i].length == 2`
*   `1 <= widthi, heighti <= 105`

## A solution in Java

```java
public boolean canReach(String s, int minJump, int maxJump) {
    int n = s.length();
    boolean[] dp = new boolean[n];
    dp[0] = true;
    int pre = 0;
    for (int i = 1; i < n; i++) {
        if (i >= minJump) pre += dp[i - minJump] ? 1 : 0;
        if (i > maxJump) pre -= dp[i - maxJump - 1] ? 1 : 0;
        dp[i] = pre > 0 && s.charAt(i) == '0';
    }
    return dp[n - 1];
}
```
The algorithm uses dynamic programming to determine whether it is possible to reach the end of the string. The `dp` array keeps track of the positions that can be reached. At each position, it checks whether it is possible to reach this position using valid jumps. Then, it calculates the prefix sum `pre` to keep track of the number of ways to reach the current position using valid jumps. If it is reachable, it sets the `dp` value of that position to true. Finally, it returns the `dp` value of `s.length - 1`. If it is true, you can reach the end of the string, otherwise, you cannot.

## A solution in C++

```cpp
bool canReach(string s, int minJump, int maxJump) {
    int n = s.size();
    vector<bool> dp(n, false);
    dp[0] = true;
    int pre = 0;
    for (int i = 1; i < n; ++i) {
        if (i >= minJump) pre += dp[i - minJump];
        if (i > maxJump) pre -= dp[i - maxJump - 1];
        dp[i] = pre > 0 && s[i] == '0';
    }
    return dp[n - 1];
}
```
The algorithm uses dynamic programming to determine whether it is possible to reach the end of the string. The `dp` array keeps track of the positions that can be reached. At each position, it checks whether it is possible to reach this position using valid jumps. Then, it calculates the prefix sum `pre` to keep track of the number of ways to reach the current position using valid jumps. If it is reachable, it sets the `dp` value of that position to true. Finally, it returns the `dp` value of `s.length - 1`. If it is true, you can reach the end of the string, otherwise, you cannot.

## A solution in Python

```python
def canReach(s: str, minJump: int, maxJump: int) -> bool:
    n = len(s)
    dp = [False] * n
    dp[0] = True
    pre = 0
    for i in range(1, n):
        if i >= minJump:
            pre += dp[i - minJump]
        if i > maxJump:
            pre -= dp[i - maxJump - 1]
        dp[i] = pre > 0 and s[i] == '0'
    return dp[n - 1]
```
The algorithm uses dynamic programming to determine whether it is possible to reach the end of the string. The `dp` array keeps track of the positions that can be reached. At each position, it checks whether it is possible to reach this position using valid jumps. Then, it calculates the prefix sum `pre` to keep track of the number of ways to reach the current position using valid jumps. If it is reachable, it sets the `dp` value of that position to true. Finally, it returns the `dp` value of `s.length - 1`. If it is true, you can reach the end of the string, otherwise, you cannot.

## A solution in Javascript

```javascript
function canReach(s, minJump, maxJump) {
    let n = s.length;
    let dp = new Array(n).fill(false);
    dp[0] = true;
    let pre = 0;
    for (let i = 1; i < n; i++) {
        if (i >= minJump) pre += dp[i - minJump];
        if (i > maxJump) pre -= dp[i - maxJump - 1];
        dp[i] = pre > 0 && s[i] === '0';
    }
    return dp[n - 1];
}
```
The algorithm uses dynamic programming to determine whether it is possible to reach the end of the string. The `dp` array keeps track of the positions that can be reached. At each position, it checks whether it is possible to reach this position using valid jumps. Then, it calculates the prefix sum `pre` to keep track of the number of ways to reach the current position using valid jumps. If it is reachable, it sets the `dp` value of that position to true. Finally, it returns the `dp` value of `s.length - 1`. If it is true, you can reach the end of the string, otherwise, you cannot.


# Maximum Product of the Length of Two Palindromic Subsequences

- slug: maximum-product-of-the-length-of-two-palindromic-subsequences
- difficulty: Medium

Given a string `s`, find two **disjoint palindromic subsequences** of `s` such that the **product** of their lengths is **maximized**. The two subsequences are **disjoint** if they do not both pick a character at the same index.

Return _the **maximum** possible **product** of the lengths of the two palindromic subsequences_.

A **subsequence** is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is **palindromic** if it reads the same forward and backward.

**Example 1:**

**Input:** s =  "leetcodecom "
**Output:** 9
**Explanation**: An optimal solution is to choose  "ete " for the 1st subsequence and  "cdc " for the 2nd subsequence.
The product of their lengths is: 3 \* 3 = 9.

**Example 2:**

**Input:** s =  "bb "
**Output:** 1
**Explanation**: An optimal solution is to choose  "b " (the first character) for the 1st subsequence and  "b " (the second character) for the 2nd subsequence.
The product of their lengths is: 1 \* 1 = 1.

**Example 3:**

**Input:** s =  "accbcaxxcxx "
**Output:** 25
**Explanation**: An optimal solution is to choose  "accca " for the 1st subsequence and  "xxcxx " for the 2nd subsequence.
The product of their lengths is: 5 \* 5 = 25.

**Constraints:**

*   `2 <= s.length <= 12`
*   `s` consists of lowercase English letters only.

## A solution in Java

```java
public int stoneGameVII(int[] stones) {
    int n = stones.length;
    int[][] dp = new int[n][n];

    for (int i = n - 1; i >= 0; i--)
        for (int j = i + 1; j < n; j++)
            dp[i][j] = Math.max(stones[i] - dp[i + 1][j], stones[j] - dp[i][j - 1]);

    return dp[0][n - 1];
}
```
The solution uses dynamic programming. We consider the difference in score at any given range [i, j] in the stones array as the max of two possibilities:

1. The value of the leftmost stone (stones[i]) minus the difference in the remaining range [i + 1, j].
2. The value of the rightmost stone (stones[j]) minus the difference in the remaining range [i, j - 1].

We fill up the dp[i][j] matrix with the maximum difference for each range [i, j], starting from the bottom right and moving towards the top left. Once the entire dp matrix is filled, the value in dp[0][n - 1] represents the maximum score difference between Alice and Bob.

All implementations work with a time complexity of O(n^2) since we iterate through all pairs of (i, j) possible in the array.

## A solution in C++

```cpp
int stoneGameDp(vector<int>& stones, int start, int end, vector<vector<int>>& dp) {
    if (start == end) return stones[start];

    if (dp[start][end] != 0) return dp[start][end];

    dp[start][end] = max(stones[start] - stoneGameDp(stones, start + 1, end, dp),
                         stones[end] - stoneGameDp(stones, start, end - 1, dp));
    return dp[start][end];
}

int stoneGameVII(vector<int>& stones) {
    int n = stones.size();
    vector<vector<int>> dp(n, vector<int>(n, 0));

    for (int i = n - 1; i >= 0; --i)
        for (int j = i + 1; j < n; ++j)
            dp[i][j] = max(stones[i] - dp[i + 1][j], stones[j] - dp[i][j - 1]);

    return dp[0][n - 1];
}
```
The solution uses dynamic programming. We consider the difference in score at any given range [i, j] in the stones array as the max of two possibilities:

1. The value of the leftmost stone (stones[i]) minus the difference in the remaining range [i + 1, j].
2. The value of the rightmost stone (stones[j]) minus the difference in the remaining range [i, j - 1].

We fill up the dp[i][j] matrix with the maximum difference for each range [i, j], starting from the bottom right and moving towards the top left. Once the entire dp matrix is filled, the value in dp[0][n - 1] represents the maximum score difference between Alice and Bob.

All implementations work with a time complexity of O(n^2) since we iterate through all pairs of (i, j) possible in the array.

## A solution in Python

```python
def stoneGameVII(stones):
    n = len(stones)
    dp = [[0] * n for _ in range(n)]

    for i in range(n - 1, -1, -1):
        for j in range(i + 1, n):
            dp[i][j] = max(stones[i] - dp[i + 1][j], stones[j] - dp[i][j - 1])

    return dp[0][n - 1]
```
The solution uses dynamic programming. We consider the difference in score at any given range [i, j] in the stones array as the max of two possibilities:

1. The value of the leftmost stone (stones[i]) minus the difference in the remaining range [i + 1, j].
2. The value of the rightmost stone (stones[j]) minus the difference in the remaining range [i, j - 1].

We fill up the dp[i][j] matrix with the maximum difference for each range [i, j], starting from the bottom right and moving towards the top left. Once the entire dp matrix is filled, the value in dp[0][n - 1] represents the maximum score difference between Alice and Bob.

All implementations work with a time complexity of O(n^2) since we iterate through all pairs of (i, j) possible in the array.

## A solution in Javascript

```javascript
function stoneGameVII(stones) {
    const n = stones.length;
    const dp = Array.from({ length: n }, () => new Array(n).fill(0));

    for (let i = n - 1; i >= 0; i--) {
        for (let j = i + 1; j < n; j++) {
            dp[i][j] = Math.max(stones[i] - dp[i + 1][j], stones[j] - dp[i][j - 1]);
        }
    }

    return dp[0][n - 1];
}
```
The solution uses dynamic programming. We consider the difference in score at any given range [i, j] in the stones array as the max of two possibilities:

1. The value of the leftmost stone (stones[i]) minus the difference in the remaining range [i + 1, j].
2. The value of the rightmost stone (stones[j]) minus the difference in the remaining range [i, j - 1].

We fill up the dp[i][j] matrix with the maximum difference for each range [i, j], starting from the bottom right and moving towards the top left. Once the entire dp matrix is filled, the value in dp[0][n - 1] represents the maximum score difference between Alice and Bob.

All implementations work with a time complexity of O(n^2) since we iterate through all pairs of (i, j) possible in the array.


# Smallest Missing Genetic Value in Each Subtree

- slug: smallest-missing-genetic-value-in-each-subtree
- difficulty: Hard

There is a **family tree** rooted at `0` consisting of `n` nodes numbered `0` to `n - 1`. You are given a **0-indexed** integer array `parents`, where `parents[i]` is the parent for node `i`. Since node `0` is the **root**, `parents[0] == -1`.

There are `105` genetic values, each represented by an integer in the **inclusive** range `[1, 105]`. You are given a **0-indexed** integer array `nums`, where `nums[i]` is a **distinct** genetic value for node `i`.

Return _an array_ `ans` _of length_ `n` _where_ `ans[i]` _is_ _the **smallest** genetic value that is **missing** from the subtree rooted at node_ `i`.

The **subtree** rooted at a node `x` contains node `x` and all of its **descendant** nodes.

**Example 1:**

**Input:** parents = \[-1,0,0,2\], nums = \[1,2,3,4\]
**Output:** \[5,1,1,1\]
**Explanation:** The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes \[0,1,2,3\] with values \[1,2,3,4\]. 5 is the smallest missing value.
- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.
- 2: The subtree contains nodes \[2,3\] with values \[3,4\]. 1 is the smallest missing value.
- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.

**Example 2:**

**Input:** parents = \[-1,0,1,0,3,3\], nums = \[5,4,6,2,1,3\]
**Output:** \[7,1,1,4,2,1\]
**Explanation:** The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes \[0,1,2,3,4,5\] with values \[5,4,6,2,1,3\]. 7 is the smallest missing value.
- 1: The subtree contains nodes \[1,2\] with values \[4,6\]. 1 is the smallest missing value.
- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.
- 3: The subtree contains nodes \[3,4,5\] with values \[2,1,3\]. 4 is the smallest missing value.
- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.
- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.

**Example 3:**

**Input:** parents = \[-1,2,3,0,2,4,1\], nums = \[2,3,4,5,6,7,8\]
**Output:** \[1,1,1,1,1,1,1\]
**Explanation:** The value 1 is missing from all the subtrees.

**Constraints:**

*   `n == parents.length == nums.length`
*   `2 <= n <= 105`
*   `0 <= parents[i] <= n - 1` for `i != 0`
*   `parents[0] == -1`
*   `parents` represents a valid tree.
*   `1 <= nums[i] <= 105`
*   Each `nums[i]` is distinct.

## A solution in Java

```java
import java.util.*;

class Solution {
    public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {
        int n = parents.length;
        List<Set<Integer>> children = new ArrayList<>();
        for (int i = 0; i < n; ++i) {
            children.add(new HashSet<>());
        }
        for (int i = 1; i < n; ++i) {
            children.get(parents[i]).add(nums[i]);
        }

        int[] ans = new int[n];
        dfs(0, parents, nums, children, ans);
        return ans;
    }

    private void dfs(int node, int[] parents, int[] nums, List<Set<Integer>> children, int[] ans) {
        for (int child : children.get(node)) {
            dfs(child, parents, nums, children, ans);
            children.get(node).remove(child);
            children.get(node).add(ans[child]);
        }
        Iterator<Integer> it = children.get(node).lower_bound(nums[node]);
        ans[node] = (it == children.get(node).end()) ? nums[node] + 1 : *it - 1;
    }
}
```
The algorithm performs a Depth First Search (DFS) on the family tree, using recursion. The DFS function takes in the following parameters: 'node', which is the subtree root, 'parents', 'nums', 'children', and 'ans'.

We first create a set of children nodes for each node in the tree. We start at the root node and iterate through its children nodes. For each child node, we call the DFS function recursively. Here, we remove the child node from the set of children nodes and insert the value of ans[child] as a new child node.

Then, we find the smallest higher value in the children set that is larger than the subtree root value (nums[node]). We calculate the smallest missing value by subtracting 1 from that found value or adding 1 to the root value if the found value equals to the root value plus one.

After the DFS is completed, we return the ans array. The ans array contains the smallest missing value for each subtree rooted at node i.

## A solution in C++

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

using namespace std;

void dfs(int node, const vector<int>& parents, const vector<int>& nums,
         vector<set<int>>& children, vector<int>& ans) {
    for (int child : children[node]) {
        dfs(child, parents, nums, children, ans);
        children[node].erase(child);
        children[node].insert(ans[child]);
    }
    auto it = children[node].lower_bound(nums[node]);
    ans[node] = (it == children[node].end()) ? nums[node] + 1 : *it - 1;
}

vector<int> smallestMissingValueSubtree(vector<int>& parents, vector<int>& nums) {
    int n = parents.size();
    vector<set<int>> children(n);
    for (int i = 1; i < n; ++i) {
        children[parents[i]].insert(nums[i]);
    }

    vector<int> ans(n);
    dfs(0, parents, nums, children, ans);
    return ans;
}
```
The algorithm performs a Depth First Search (DFS) on the family tree, using recursion. The DFS function takes in the following parameters: 'node', which is the subtree root, 'parents', 'nums', 'children', and 'ans'.

We first create a set of children nodes for each node in the tree. We start at the root node and iterate through its children nodes. For each child node, we call the DFS function recursively. Here, we remove the child node from the set of children nodes and insert the value of ans[child] as a new child node.

Then, we find the smallest higher value in the children set that is larger than the subtree root value (nums[node]). We calculate the smallest missing value by subtracting 1 from that found value or adding 1 to the root value if the found value equals to the root value plus one.

After the DFS is completed, we return the ans array. The ans array contains the smallest missing value for each subtree rooted at node i.

## A solution in Python

```python
from collections import defaultdict

def smallestMissingValueSubtree(parents, nums):
    n = len(parents)
    children = defaultdict(set)
    for i in range(1, n):
        children[parents[i]].add(nums[i])

    ans = [0] * n
    dfs(0, parents, nums, children, ans)
    return ans

def dfs(node, parents, nums, children, ans):
    for child in list(children[node]):
        dfs(child, parents, nums, children, ans)
        children[node].remove(child)
        children[node].add(ans[child])
    it = next((x for x in children[node] if x > nums[node]), nums[node] + 1)
    ans[node] = it - 1 if it != nums[node] + 1 else it
```
The algorithm performs a Depth First Search (DFS) on the family tree, using recursion. The DFS function takes in the following parameters: 'node', which is the subtree root, 'parents', 'nums', 'children', and 'ans'.

We first create a set of children nodes for each node in the tree. We start at the root node and iterate through its children nodes. For each child node, we call the DFS function recursively. Here, we remove the child node from the set of children nodes and insert the value of ans[child] as a new child node.

Then, we find the smallest higher value in the children set that is larger than the subtree root value (nums[node]). We calculate the smallest missing value by subtracting 1 from that found value or adding 1 to the root value if the found value equals to the root value plus one.

After the DFS is completed, we return the ans array. The ans array contains the smallest missing value for each subtree rooted at node i.

## A solution in Javascript

```javascript
function smallestMissingValueSubtree(parents, nums) {
    const n = parents.length;
    const children = [];
    for (let i = 0; i < n; ++i) {
        children.push(new Set());
    }
    for (let i = 1; i < n; ++i) {
        children[parents[i]].add(nums[i]);
    }

    const ans = new Array(n);
    dfs(0, parents, nums, children, ans);
    return ans;
}

function dfs(node, parents, nums, children, ans) {
    for (const child of children[node].values()) {
        dfs(child, parents, nums, children, ans);
        children[node].delete(child);
        children[node].add(ans[child]);
    }
    const it = firstLargerOrMissing(children[node], nums[node]);
    ans[node] = (it === nums[node] + 1) ? it - 1 : it;
}

function firstLargerOrMissing(set, target) {
    for (const el of set.values()) {
        if (el > target) return el;
    }
    return target + 1;
}
```
The algorithm performs a Depth First Search (DFS) on the family tree, using recursion. The DFS function takes in the following parameters: 'node', which is the subtree root, 'parents', 'nums', 'children', and 'ans'.

We first create a set of children nodes for each node in the tree. We start at the root node and iterate through its children nodes. For each child node, we call the DFS function recursively. Here, we remove the child node from the set of children nodes and insert the value of ans[child] as a new child node.

Then, we find the smallest higher value in the children set that is larger than the subtree root value (nums[node]). We calculate the smallest missing value by subtracting 1 from that found value or adding 1 to the root value if the found value equals to the root value plus one.

After the DFS is completed, we return the ans array. The ans array contains the smallest missing value for each subtree rooted at node i.


# Subtree Removal Game with Fibonacci Tree

- slug: subtree-removal-game-with-fibonacci-tree
- difficulty: Hard

A **Fibonacci** tree is a binary tree created using the order function `order(n)`:

*   `order(0)` is the empty tree.
*   `order(1)` is a binary tree with only **one node**.
*   `order(n)` is a binary tree that consists of a root node with the left subtree as `order(n - 2)` and the right subtree as `order(n - 1)`.

Alice and Bob are playing a game with a **Fibonacci** tree with Alice staring first. On each turn, a player selects a node and removes that node **and** its subtree. The player that is forced to delete `root` loses.

Given the integer `n`, return `true` if Alice wins the game or `false` if Bob wins, assuming both players play optimally.

A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself.

**Example 1:**

**Input:** n = 3
**Output:** true
**Explanation:**
Alice takes the node 1 in the right subtree.
Bob takes either the 1 in the left subtree or the 2 in the right subtree.
Alice takes whichever node Bob doesn't take.
Bob is forced to take the root node 3, so Bob will lose.
Return true because Alice wins.

**Example 2:**

**Input:** n = 1
**Output:** false
**Explanation:**
Alice is forced to take the root node 1, so Alice will lose.
Return false because Alice loses.

**Example 3:**

**Input:** n = 2
**Output:** true
**Explanation:**
Alice takes the node 1.
Bob is forced to take the root node 2, so Bob will lose.
Return true because Alice wins.

**Constraints:**

*   `1 <= n <= 100`

## A solution in Java

```java
public boolean isCovered(int[][] ranges, int left, int right) {
    for (int i = left; i <= right; i++) {
        boolean isCovered = false;
        for (int[] range : ranges) {
            if (i >= range[0] && i <= range[1]) {
                isCovered = true;
                break;
            }
        }
        if (!isCovered) return false;
    }
    return true;
}
```
The algorithm iterates through the range of integers from left to right (inclusive). For each integer, it checks if there is an interval in the given list `ranges` that covers it. If for any integer in the range, there is no interval that covers it, the algorithm returns false. If all the integers are covered by at least one interval, it returns true.

## A solution in C++

```cpp
#include <vector>

bool isCovered(std::vector<std::vector<int>>& ranges, int left, int right) {
    for (int i = left; i <= right; i++) {
        bool is_covered = false;
        for (const auto& range : ranges) {
            if (i >= range[0] && i <= range[1]) {
                is_covered = true;
                break;
            }
        }
        if (!is_covered) return false;
    }
    return true;
}
```
The algorithm iterates through the range of integers from left to right (inclusive). For each integer, it checks if there is an interval in the given list `ranges` that covers it. If for any integer in the range, there is no interval that covers it, the algorithm returns false. If all the integers are covered by at least one interval, it returns true.

## A solution in Python

```python
def is_covered(ranges, left, right):
    for i in range(left, right + 1):
        is_covered = False
        for range_ in ranges:
            if i >= range_[0] and i <= range_[1]:
                is_covered = True
                break
        if not is_covered:
            return False
    return True
```
The algorithm iterates through the range of integers from left to right (inclusive). For each integer, it checks if there is an interval in the given list `ranges` that covers it. If for any integer in the range, there is no interval that covers it, the algorithm returns false. If all the integers are covered by at least one interval, it returns true.

## A solution in Javascript

```javascript
function isCovered(ranges, left, right) {
    for (let i = left; i <= right; i++) {
        let isCovered = false;
        for (const range of ranges) {
            if (i >= range[0] && i <= range[1]) {
                isCovered = true;
                break;
            }
        }
        if (!isCovered) return false;
    }
    return true;
}
```
The algorithm iterates through the range of integers from left to right (inclusive). For each integer, it checks if there is an interval in the given list `ranges` that covers it. If for any integer in the range, there is no interval that covers it, the algorithm returns false. If all the integers are covered by at least one interval, it returns true.


# Count Number of Pairs With Absolute Difference K

- slug: count-number-of-pairs-with-absolute-difference-k
- difficulty: Easy

Given an integer array `nums` and an integer `k`, return _the number of pairs_ `(i, j)` _where_ `i < j` _such that_ `|nums[i] - nums[j]| == k`.

The value of `|x|` is defined as:

*   `x` if `x >= 0`.
*   `-x` if `x < 0`.

**Example 1:**

**Input:** nums = \[1,2,2,1\], k = 1
**Output:** 4
**Explanation:** The pairs with an absolute difference of 1 are:
- \[**1**,**2**,2,1\]
- \[**1**,2,**2**,1\]
- \[1,**2**,2,**1**\]
- \[1,2,**2**,**1**\]

**Example 2:**

**Input:** nums = \[1,3\], k = 3
**Output:** 0
**Explanation:** There are no pairs with an absolute difference of 3.

**Example 3:**

**Input:** nums = \[3,2,1,5,4\], k = 2
**Output:** 3
**Explanation:** The pairs with an absolute difference of 2 are:
- \[**3**,2,**1**,5,4\]
- \[**3**,2,1,**5**,4\]
- \[3,**2**,1,5,**4**\]

**Constraints:**

*   `1 <= nums.length <= 200`
*   `1 <= nums[i] <= 100`
*   `1 <= k <= 99`

## A solution in Java

```java
public int chalkReplacer(int[] chalk, int k) {
    long sum = 0;
    for (int i = 0; i < chalk.length; i++) {
        sum += chalk[i];
    }
    k %= sum;
    for (int i = 0; i < chalk.length; i++) {
        if (k < chalk[i]) {
            return i;
        }
        k -= chalk[i];
    }
    return 0;
}
```
1. Calculate the sum of all elements in the `chalk` array, representing the total chalk needed for one full cycle.
2. Calculate the remainder of `k` divided by the total chalk needed using modulo operation (`k %= sum`). This will determine the remaining chalk when the teacher starts the last cycle.
3. Iterate through the `chalk` array:
   - If the remaining chalk (`k`) is less than the chalk needed by the current student (`chalk[i]` for C++ and Java, or `val` for Python and JavaScript), return the index of this student.
   - Otherwise, update the remaining chalk by subtracting the chalk needed by the current student from `k`.

Repeat this process until a student is found who will replace the chalk.

## A solution in C++

```cpp
#include <vector>

int chalkReplacer(std::vector<int>& chalk, int k) {
    long long sum = 0;
    for (int i = 0; i < chalk.size(); i++) {
        sum += chalk[i];
    }
    k %= sum;
    for (int i = 0; i < chalk.size(); i++) {
        if (k < chalk[i]) {
            return i;
        }
        k -= chalk[i];
    }
    return 0;
}
```
1. Calculate the sum of all elements in the `chalk` array, representing the total chalk needed for one full cycle.
2. Calculate the remainder of `k` divided by the total chalk needed using modulo operation (`k %= sum`). This will determine the remaining chalk when the teacher starts the last cycle.
3. Iterate through the `chalk` array:
   - If the remaining chalk (`k`) is less than the chalk needed by the current student (`chalk[i]` for C++ and Java, or `val` for Python and JavaScript), return the index of this student.
   - Otherwise, update the remaining chalk by subtracting the chalk needed by the current student from `k`.

Repeat this process until a student is found who will replace the chalk.

## A solution in Python

```python
def chalk_replacer(chalk, k):
    total_chalk = sum(chalk)
    k %= total_chalk
    for i, val in enumerate(chalk):
        if k < val:
            return i
        k -= val
    return 0
```
1. Calculate the sum of all elements in the `chalk` array, representing the total chalk needed for one full cycle.
2. Calculate the remainder of `k` divided by the total chalk needed using modulo operation (`k %= sum`). This will determine the remaining chalk when the teacher starts the last cycle.
3. Iterate through the `chalk` array:
   - If the remaining chalk (`k`) is less than the chalk needed by the current student (`chalk[i]` for C++ and Java, or `val` for Python and JavaScript), return the index of this student.
   - Otherwise, update the remaining chalk by subtracting the chalk needed by the current student from `k`.

Repeat this process until a student is found who will replace the chalk.

## A solution in Javascript

```javascript
function chalkReplacer(chalk, k) {
    let sum = chalk.reduce((a, b) => a + b, 0);
    k %= sum;
    for (let i = 0; i < chalk.length; i++) {
        if (k < chalk[i]) {
            return i;
        }
        k -= chalk[i];
    }
    return 0;
}
```
1. Calculate the sum of all elements in the `chalk` array, representing the total chalk needed for one full cycle.
2. Calculate the remainder of `k` divided by the total chalk needed using modulo operation (`k %= sum`). This will determine the remaining chalk when the teacher starts the last cycle.
3. Iterate through the `chalk` array:
   - If the remaining chalk (`k`) is less than the chalk needed by the current student (`chalk[i]` for C++ and Java, or `val` for Python and JavaScript), return the index of this student.
   - Otherwise, update the remaining chalk by subtracting the chalk needed by the current student from `k`.

Repeat this process until a student is found who will replace the chalk.


# Find Original Array From Doubled Array

- slug: find-original-array-from-doubled-array
- difficulty: Medium

An integer array `original` is transformed into a **doubled** array `changed` by appending **twice the value** of every element in `original`, and then randomly **shuffling** the resulting array.

Given an array `changed`, return `original` _if_ `changed` _is a **doubled** array. If_ `changed` _is not a **doubled** array, return an empty array. The elements in_ `original` _may be returned in **any** order_.

**Example 1:**

**Input:** changed = \[1,3,4,2,6,8\]
**Output:** \[1,3,4\]
**Explanation:** One possible original array could be \[1,3,4\]:
- Twice the value of 1 is 1 \* 2 = 2.
- Twice the value of 3 is 3 \* 2 = 6.
- Twice the value of 4 is 4 \* 2 = 8.
Other original arrays could be \[4,3,1\] or \[3,1,4\].

**Example 2:**

**Input:** changed = \[6,3,0,1\]
**Output:** \[\]
**Explanation:** changed is not a doubled array.

**Example 3:**

**Input:** changed = \[1\]
**Output:** \[\]
**Explanation:** changed is not a doubled array.

**Constraints:**

*   `1 <= changed.length <= 105`
*   `0 <= changed[i] <= 105`

## A solution in Java

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

public int[] findOriginalArray(int[] changed) {
    if (changed.length % 2 != 0) return new int[0];

    Map<Integer, Integer> count = new HashMap<>();
    for (int num : changed) {
        count.put(num, count.getOrDefault(num, 0) + 1);
    }

    ArrayList<Integer> original = new ArrayList<>();
    for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
        int num = entry.getKey();
        int freq = entry.getValue();
        if (freq > count.getOrDefault(num * 2, 0)) return new int[0];

        for (int i = 0; i < freq; ++i) {
            original.add(num);
        }
    }

    return original.stream().mapToInt(Integer::intValue).toArray();
}
```
1. First, check if the length of the `changed` array is odd. If it is, return an empty array as it cannot be a doubled array.
2. Create a counter for the numbers in `changed` using a map or dictionary depending on the language.
3. Iterate through the counter and for each number present, check if its doubled value has equal or more count than itself. If not, return an empty array as it is not a doubled array.
4. In the same loop, add the current number to the `original` array as many times as it appears in the counter.
5. Return the `original` array.

This will solve the problem because we are verifying that each element in the `original` array has its double in the `changed` array. The elements in the `original` array can be returned in any order, so we don't need to construct a specific order. The time complexity of this algorithm is O(n), where n is the length of the `changed` array.

## A solution in C++

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

std::vector<int> findOriginalArray(std::vector<int>& changed) {
    if (changed.size() % 2 != 0) return {};

    std::map<int, int> count;
    for (int num : changed) {
        count[num]++;
    }

    std::vector<int> original;
    for (const auto& [num, freq] : count) {
        if (freq > count[num * 2]) return {};

        for (int i = 0; i < freq; ++i) {
            original.push_back(num);
        }
    }

    return original;
}
```
1. First, check if the length of the `changed` array is odd. If it is, return an empty array as it cannot be a doubled array.
2. Create a counter for the numbers in `changed` using a map or dictionary depending on the language.
3. Iterate through the counter and for each number present, check if its doubled value has equal or more count than itself. If not, return an empty array as it is not a doubled array.
4. In the same loop, add the current number to the `original` array as many times as it appears in the counter.
5. Return the `original` array.

This will solve the problem because we are verifying that each element in the `original` array has its double in the `changed` array. The elements in the `original` array can be returned in any order, so we don't need to construct a specific order. The time complexity of this algorithm is O(n), where n is the length of the `changed` array.

## A solution in Python

```python
def find_original_array(changed):
    if len(changed) % 2 != 0:
        return []

    count = {}
    for num in changed:
        count[num] = count.get(num, 0) + 1

    original = []
    for num, freq in count.items():
        if freq > count.get(num * 2, 0):
            return []

        for _ in range(freq):
            original.append(num)

    return original
```
1. First, check if the length of the `changed` array is odd. If it is, return an empty array as it cannot be a doubled array.
2. Create a counter for the numbers in `changed` using a map or dictionary depending on the language.
3. Iterate through the counter and for each number present, check if its doubled value has equal or more count than itself. If not, return an empty array as it is not a doubled array.
4. In the same loop, add the current number to the `original` array as many times as it appears in the counter.
5. Return the `original` array.

This will solve the problem because we are verifying that each element in the `original` array has its double in the `changed` array. The elements in the `original` array can be returned in any order, so we don't need to construct a specific order. The time complexity of this algorithm is O(n), where n is the length of the `changed` array.

## A solution in Javascript

```javascript
function findOriginalArray(changed) {
    if (changed.length % 2 !== 0) return [];

    const count = new Map();
    for (const num of changed) {
        count.set(num, (count.get(num) || 0) + 1);
    }

    const original = [];
    for (const [num, freq] of count.entries()) {
        if (freq > (count.get(num * 2) || 0)) return [];

        for (let i = 0; i < freq; ++i) {
            original.push(num);
        }
    }

    return original;
}
```
1. First, check if the length of the `changed` array is odd. If it is, return an empty array as it cannot be a doubled array.
2. Create a counter for the numbers in `changed` using a map or dictionary depending on the language.
3. Iterate through the counter and for each number present, check if its doubled value has equal or more count than itself. If not, return an empty array as it is not a doubled array.
4. In the same loop, add the current number to the `original` array as many times as it appears in the counter.
5. Return the `original` array.

This will solve the problem because we are verifying that each element in the `original` array has its double in the `changed` array. The elements in the `original` array can be returned in any order, so we don't need to construct a specific order. The time complexity of this algorithm is O(n), where n is the length of the `changed` array.


# Maximum Earnings From Taxi

- slug: maximum-earnings-from-taxi
- difficulty: Medium

There are `n` points on a road you are driving your taxi on. The `n` points on the road are labeled from `1` to `n` in the direction you are going, and you want to drive from point `1` to point `n` to make money by picking up passengers. You cannot change the direction of the taxi.

The passengers are represented by a **0-indexed** 2D integer array `rides`, where `rides[i] = [starti, endi, tipi]` denotes the `ith` passenger requesting a ride from point `starti` to point `endi` who is willing to give a `tipi` dollar tip.

For **each** passenger `i` you pick up, you **earn** `endi - starti + tipi` dollars. You may only drive **at most one** passenger at a time.

Given `n` and `rides`, return _the **maximum** number of dollars you can earn by picking up the passengers optimally._

**Note:** You may drop off a passenger and pick up a different passenger at the same point.

**Example 1:**

**Input:** n = 5, rides = \[\[2,5,4\],\[1,5,1\]\]
**Output:** 7
**Explanation:** We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.

**Example 2:**

**Input:** n = 20, rides = \[\[1,6,1\],\[3,10,2\],\[10,12,3\],\[11,12,2\],\[12,15,2\],\[13,18,1\]\]
**Output:** 20
**Explanation:** We will pick up the following passengers:
- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.
- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.
- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.
We earn 9 + 5 + 6 = 20 dollars in total.

**Constraints:**

*   `1 <= n <= 105`
*   `1 <= rides.length <= 3 * 104`
*   `rides[i].length == 3`
*   `1 <= starti < endi <= n`
*   `1 <= tipi <= 105`

## A solution in Java

```java
import java.util.Stack;

public int minOperationsToFlip(String expression) {
    Stack<Integer> zero = new Stack<>(), one = new Stack<>(), op = new Stack<>();
    zero.push(0);
    one.push(0);
    for (char c : expression.toCharArray()) {
        if (c == '&') op.push(1);
        else if (c == '|') op.push(2);
        else if (Character.isDigit(c)) {
            if (c == '0') {
                one.push(1);
                zero.push(0);
            } else {
                zero.push(1);
                one.push(0);
            }
        } else if (c == ')') {
            int cur_op = op.pop();
            int new_zero, new_one;
            int x = zero.pop();
            int y = one.pop() + 1;
            if (cur_op == 1) {
                new_zero = Math.max(x, y);
                new_one = one.peek() + Math.min(x, zero.peek());
            } else {
                new_zero = zero.peek() + Math.min(x, one.peek());
                new_one = Math.max(y, one.peek());
            }
            zero.pop();
            one.pop();
            zero.push(new_zero);
            one.push(new_one);
        }
    }
    return zero.peek() + 1;
}
```
1. Create three stacks for zero, one, and operation.
2. Iterate through the characters in the expression.
3. For each character, follow the rules:
   * If it is '&', push the value 1 to the operation stack.
   * If it is '|', push the value 2 to the operation stack.
   * If it is a digit (0 or 1), update the one and zero stacks accordingly.
   * If it is a closing parentheses, retrieve the operation and update the one and zero stacks based on the operation value.
4. At the end of the iteration, the last value in the zero stack + 1 is the required minimum cost to change the final value of the expression.

## A solution in C++

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

int minOperationsToFlip(string expression) {
    vector<int> zero(1), one(1), op;
    for (const auto& c : expression) {
        if (c == '&') op.push_back(1);
        else if (c == '|') op.push_back(2);
        else if (isdigit(c)) {
            if (c == '0') {
                one.push_back(1);
                zero.push_back(0);
            } else {
                zero.push_back(1);
                one.push_back(0);
            }
        } else if (c == ')') {
            int cur_op = op.back(); op.pop_back();
            int new_zero, new_one;
            int x = zero.back(); zero.pop_back();
            int y = one.back() + 1; one.pop_back();
            if (cur_op == 1) {
                new_zero = max(x, y);
                new_one = one.back() + min(x, zero.back());
            } else {
                new_zero = zero.back() + min(x, one.back());
                new_one = max(y, one.back());
            }
            zero.pop_back(); one.pop_back();
            zero.push_back(new_zero);
            one.push_back(new_one);
        }
    }
    return zero.back() + 1;
}
```
1. Create three stacks for zero, one, and operation.
2. Iterate through the characters in the expression.
3. For each character, follow the rules:
   * If it is '&', push the value 1 to the operation stack.
   * If it is '|', push the value 2 to the operation stack.
   * If it is a digit (0 or 1), update the one and zero stacks accordingly.
   * If it is a closing parentheses, retrieve the operation and update the one and zero stacks based on the operation value.
4. At the end of the iteration, the last value in the zero stack + 1 is the required minimum cost to change the final value of the expression.

## A solution in Python

```python
def minOperationsToFlip(expression: str) -> int:
    zero, one, op = [0], [0], []
    for c in expression:
        if c == '&':
            op.append(1)
        elif c == '|':
            op.append(2)
        elif c.isdigit():
            if c == '0':
                one.append(1)
                zero.append(0)
            else:
                zero.append(1)
                one.append(0)
        elif c == ')':
            cur_op = op.pop()
            x = zero.pop()
            y = one.pop() + 1
            if cur_op == 1:
                new_zero = max(x, y)
                new_one = one[-1] + min(x, zero[-1])
            else:
                new_zero = zero[-1] + min(x, one[-1])
                new_one = max(y, one[-1])
            zero.pop()
            one.pop()
            zero.append(new_zero)
            one.append(new_one)
    return zero[-1] + 1
```
1. Create three stacks for zero, one, and operation.
2. Iterate through the characters in the expression.
3. For each character, follow the rules:
   * If it is '&', push the value 1 to the operation stack.
   * If it is '|', push the value 2 to the operation stack.
   * If it is a digit (0 or 1), update the one and zero stacks accordingly.
   * If it is a closing parentheses, retrieve the operation and update the one and zero stacks based on the operation value.
4. At the end of the iteration, the last value in the zero stack + 1 is the required minimum cost to change the final value of the expression.

## A solution in Javascript

```javascript
var minOperationsToFlip = function(expression) {
    let zero = [0], one = [0], op = [];
    for (let c of expression) {
        if (c == '&') op.push(1);
        else if (c == '|') op.push(2);
        else if (c == '0' || c == '1') {
            if (c == '0') {
                one.push(1);
                zero.push(0);
            } else {
                zero.push(1);
                one.push(0);
            }
        } else if (c == ')') {
            let cur_op = op.pop();
            let x = zero.pop();
            let y = one.pop() + 1;
            let new_zero, new_one;
            if (cur_op == 1) {
                new_zero = Math.max(x, y);
                new_one = one[one.length - 1] + Math.min(x, zero[zero.length - 1]);
            } else {
                new_zero = zero[zero.length - 1] + Math.min(x, one[one.length - 1]);
                new_one = Math.max(y, one[one.length - 1]);
            }
            zero.pop();
            one.pop();
            zero.push(new_zero);
            one.push(new_one);
        }
    }
    return zero[zero.length-1] + 1;
};
```
1. Create three stacks for zero, one, and operation.
2. Iterate through the characters in the expression.
3. For each character, follow the rules:
   * If it is '&', push the value 1 to the operation stack.
   * If it is '|', push the value 2 to the operation stack.
   * If it is a digit (0 or 1), update the one and zero stacks accordingly.
   * If it is a closing parentheses, retrieve the operation and update the one and zero stacks based on the operation value.
4. At the end of the iteration, the last value in the zero stack + 1 is the required minimum cost to change the final value of the expression.


# Minimum Number of Operations to Make Array Continuous

- slug: minimum-number-of-operations-to-make-array-continuous
- difficulty: Hard

You are given an integer array `nums`. In one operation, you can replace **any** element in `nums` with **any** integer.

`nums` is considered **continuous** if both of the following conditions are fulfilled:

*   All elements in `nums` are **unique**.
*   The difference between the **maximum** element and the **minimum** element in `nums` equals `nums.length - 1`.

For example, `nums = [4, 2, 5, 3]` is **continuous**, but `nums = [1, 2, 3, 5, 6]` is **not continuous**.

Return _the **minimum** number of operations to make_ `nums` **_continuous_**.

**Example 1:**

**Input:** nums = \[4,2,5,3\]
**Output:** 0
**Explanation:** nums is already continuous.

**Example 2:**

**Input:** nums = \[1,2,3,5,6\]
**Output:** 1
**Explanation:** One possible solution is to change the last element to 4.
The resulting array is \[1,2,3,5,4\], which is continuous.

**Example 3:**

**Input:** nums = \[1,10,100,1000\]
**Output:** 3
**Explanation:** One possible solution is to:
- Change the second element to 2.
- Change the third element to 3.
- Change the fourth element to 4.
The resulting array is \[1,2,3,4\], which is continuous.

**Constraints:**

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

## A solution in Java

```java
public int minOperations(int[] nums) {
    int n = nums.length;
    Set<Integer> set = new HashSet<>();
    for (int num : nums) {
        set.add(num);
    }
    List<Integer> list = new ArrayList<>(set);
    Collections.sort(list);
    int res = Integer.MAX_VALUE;
    int j = 0;

    for (int i = 0; i < list.size(); ++i) {
        while (j < list.size() && list.get(j) <= list.get(i) + n - 1) {
            ++j;
        }
        res = Math.min(res, n - (j - i));
    }
    return res;
}
```
The algorithm first finds and sorts the unique elements in the input array. Then, it performs a two-pointer iteration through the unique elements. The first pointer, `i`, iterates from the beginning to the end of the unique elements array. The second pointer, `j`, starts at the beginning and moves forward while the difference between the currently pointed elements and `n - 1` is not exceeded. The difference between the two pointers gives us the number of elements that are already continuous in the input array. The result is the minimum number of operations required to make the input array continuous. The algorithm updates the result as the min value between the previous result and `n - (j - i)` during the iterations.

## A solution in C++

```cpp
int min_operations(vector<int>& nums) {
    int n = nums.size();
    set<int> s(nums.begin(), nums.end());
    vector<int> v(s.begin(), s.end());
    int res = INT_MAX;
    int j = 0;

    for (int i = 0; i < v.size(); ++i) {
        while (j < v.size() && v[j] <= v[i] + n - 1) {
            ++j;
        }
        res = min(res, n - (j - i));
    }
    return res;
}
```
The algorithm first finds and sorts the unique elements in the input array. Then, it performs a two-pointer iteration through the unique elements. The first pointer, `i`, iterates from the beginning to the end of the unique elements array. The second pointer, `j`, starts at the beginning and moves forward while the difference between the currently pointed elements and `n - 1` is not exceeded. The difference between the two pointers gives us the number of elements that are already continuous in the input array. The result is the minimum number of operations required to make the input array continuous. The algorithm updates the result as the min value between the previous result and `n - (j - i)` during the iterations.

## A solution in Python

```python
def min_operations(nums):
    n = len(nums)
    s = sorted(set(nums))
    res = float('inf')
    j = 0

    for i in range(len(s)):
        while j < len(s) and s[j] <= s[i] + n - 1:
            j += 1
        res = min(res, n - (j - i))

    return res
```
The algorithm first finds and sorts the unique elements in the input array. Then, it performs a two-pointer iteration through the unique elements. The first pointer, `i`, iterates from the beginning to the end of the unique elements array. The second pointer, `j`, starts at the beginning and moves forward while the difference between the currently pointed elements and `n - 1` is not exceeded. The difference between the two pointers gives us the number of elements that are already continuous in the input array. The result is the minimum number of operations required to make the input array continuous. The algorithm updates the result as the min value between the previous result and `n - (j - i)` during the iterations.

## A solution in Javascript

```javascript
function minOperations(nums) {
    const n = nums.length;
    const s = [...new Set(nums)].sort((a, b) => a - b);
    let res = Infinity;
    let j = 0;

    for (let i = 0; i < s.length; ++i) {
        while (j < s.length && s[j] <= s[i] + n - 1) {
            ++j;
        }
        res = Math.min(res, n - (j - i));
    }
    return res;
}
```
The algorithm first finds and sorts the unique elements in the input array. Then, it performs a two-pointer iteration through the unique elements. The first pointer, `i`, iterates from the beginning to the end of the unique elements array. The second pointer, `j`, starts at the beginning and moves forward while the difference between the currently pointed elements and `n - 1` is not exceeded. The difference between the two pointers gives us the number of elements that are already continuous in the input array. The result is the minimum number of operations required to make the input array continuous. The algorithm updates the result as the min value between the previous result and `n - (j - i)` during the iterations.


# Final Value of Variable After Performing Operations

- slug: final-value-of-variable-after-performing-operations
- difficulty: Easy

There is a programming language with only **four** operations and **one** variable `X`:

*   `++X` and `X++` **increments** the value of the variable `X` by `1`.
*   `--X` and `X--` **decrements** the value of the variable `X` by `1`.

Initially, the value of `X` is `0`.

Given an array of strings `operations` containing a list of operations, return _the **final** value of_ `X` _after performing all the operations_.

**Example 1:**

**Input:** operations = \[ "--X ", "X++ ", "X++ "\]
**Output:** 1
**Explanation:** The operations are performed as follows:
Initially, X = 0.
--X: X is decremented by 1, X =  0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 =  0.
X++: X is incremented by 1, X =  0 + 1 =  1.

**Example 2:**

**Input:** operations = \[ "++X ", "++X ", "X++ "\]
**Output:** 3
**Explanation:** The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.

**Example 3:**

**Input:** operations = \[ "X++ ", "++X ", "--X ", "X-- "\]
**Output:** 0
**Explanation:** The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
--X: X is decremented by 1, X = 2 - 1 = 1.
X--: X is decremented by 1, X = 1 - 1 = 0.

**Constraints:**

*   `1 <= operations.length <= 100`
*   `operations[i]` will be either `"++X "`, `"X++ "`, `"--X "`, or `"X-- "`.

## A solution in Java

```java
public String maxValue(String n, int x) {
    boolean is_negative = n.charAt(0) == '-';
    int pos = is_negative ? 1 : 0;

    while (pos < n.length()) {
        if (is_negative && n.charAt(pos) - '0' > x || !is_negative && n.charAt(pos) - '0' < x) {
            break;
        }
        pos++;
    }

    return n.substring(0, pos) + Integer.toString(x) + n.substring(pos);
}
```
The algorithm starts by checking if the given integer `n` is negative or not, and initializes the position `pos` where we want to insert the integer `x`. It then iterates through the digits of `n`. For negative numbers, it checks to find the first digit that is greater than `x`. For positive numbers, it looks for the first digit that is smaller than `x`. If found, we break out of the loop.

Finally, we return the new string by concatenating the substring before the position `pos`, the digit `x`, and the substring after the position.

The algorithm has a complexity of O(n) where n is the length of the input string.

## A solution in C++

```cpp
#include <string>

std::string maxValue(std::string n, int x) {
    bool is_negative = n[0] == '-';
    int pos = is_negative ? 1 : 0;

    while (pos < n.size()) {
        if (is_negative && n[pos] - '0' > x || !is_negative && n[pos] - '0' < x) {
            break;
        }
        pos++;
    }

    return n.substr(0, pos) + std::to_string(x) + n.substr(pos);
}
```
The algorithm starts by checking if the given integer `n` is negative or not, and initializes the position `pos` where we want to insert the integer `x`. It then iterates through the digits of `n`. For negative numbers, it checks to find the first digit that is greater than `x`. For positive numbers, it looks for the first digit that is smaller than `x`. If found, we break out of the loop.

Finally, we return the new string by concatenating the substring before the position `pos`, the digit `x`, and the substring after the position.

The algorithm has a complexity of O(n) where n is the length of the input string.

## A solution in Python

```python
def max_value(n: str, x: int) -> str:
    is_negative = n[0] == '-'
    pos = 1 if is_negative else 0

    while pos < len(n):
        if (is_negative and int(n[pos]) > x) or (not is_negative and int(n[pos]) < x):
            break
        pos += 1

    return n[:pos] + str(x) + n[pos:]
```
The algorithm starts by checking if the given integer `n` is negative or not, and initializes the position `pos` where we want to insert the integer `x`. It then iterates through the digits of `n`. For negative numbers, it checks to find the first digit that is greater than `x`. For positive numbers, it looks for the first digit that is smaller than `x`. If found, we break out of the loop.

Finally, we return the new string by concatenating the substring before the position `pos`, the digit `x`, and the substring after the position.

The algorithm has a complexity of O(n) where n is the length of the input string.

## A solution in Javascript

```javascript
function maxValue(n, x) {
    const isNegative = n[0] === '-';
    let pos = isNegative ? 1 : 0;

    while (pos < n.length) {
        if ((isNegative && parseInt(n[pos], 10) > x) || (!isNegative && parseInt(n[pos], 10) < x)) {
            break;
        }
        pos++;
    }

    return n.slice(0, pos) + x.toString() + n.slice(pos);
}
```
The algorithm starts by checking if the given integer `n` is negative or not, and initializes the position `pos` where we want to insert the integer `x`. It then iterates through the digits of `n`. For negative numbers, it checks to find the first digit that is greater than `x`. For positive numbers, it looks for the first digit that is smaller than `x`. If found, we break out of the loop.

Finally, we return the new string by concatenating the substring before the position `pos`, the digit `x`, and the substring after the position.

The algorithm has a complexity of O(n) where n is the length of the input string.


# Sum of Beauty in the Array

- slug: sum-of-beauty-in-the-array
- difficulty: Medium

You are given a **0-indexed** integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the **beauty** of `nums[i]` equals:

*   `2`, if `nums[j] < nums[i] < nums[k]`, for **all** `0 <= j < i` and for **all** `i < k <= nums.length - 1`.
*   `1`, if `nums[i - 1] < nums[i] < nums[i + 1]`, and the previous condition is not satisfied.
*   `0`, if none of the previous conditions holds.

Return _the **sum of beauty** of all_ `nums[i]` _where_ `1 <= i <= nums.length - 2`.

**Example 1:**

**Input:** nums = \[1,2,3\]
**Output:** 2
**Explanation:** For each index i in the range 1 <= i <= 1:
- The beauty of nums\[1\] equals 2.

**Example 2:**

**Input:** nums = \[2,4,6,4\]
**Output:** 1
**Explanation:** For each index i in the range 1 <= i <= 2:
- The beauty of nums\[1\] equals 1.
- The beauty of nums\[2\] equals 0.

**Example 3:**

**Input:** nums = \[3,2,1\]
**Output:** 0
**Explanation:** For each index i in the range 1 <= i <= 1:
- The beauty of nums\[1\] equals 0.

**Constraints:**

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

## A solution in Java

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

public class Solution {
    public int[] assignTasks(int[] servers, int[] tasks) {
        int n = servers.length, m = tasks.length;
        int[] ans = new int[m];
        PriorityQueue<int[]> freeServers = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]).thenComparingInt(a -> a[1]));

        for (int i = 0; i < n; i++) {
            freeServers.offer(new int[]{servers[i], i});
        }

        PriorityQueue<int[]> busyServers = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]).thenComparingInt(a -> a[1]));
        int currentTask = 0;

        while (currentTask < m) {
            while (!busyServers.isEmpty() && busyServers.peek()[0] <= currentTask) {
                freeServers.offer(new int[]{servers[busyServers.peek()[1]], busyServers.peek()[1]});
                busyServers.poll();
            }

            while (!freeServers.isEmpty() && currentTask < m) {
                ans[currentTask] = freeServers.peek()[1];
                busyServers.offer(new int[]{currentTask + tasks[currentTask], freeServers.peek()[1]});
                freeServers.poll();
                currentTask++;
            }

            if(freeServers.isEmpty()) {
                currentTask = busyServers.peek()[0];
            }
        }

        return ans;
    }
}
```
The algorithm works as follows:
1. Create two priority queues, one for free servers and one for busy servers. Both queues use server weight and index as their sorting criteria.
2. Initially, add all servers to the freeServers queue.
3. Loop through the tasks as `currentTask` and do the following:
   - If there are any busy servers that have become free, move them from the `busyServers` queue to the `freeServers` queue.
   - Assign tasks to free servers from the `freeServers` queue and add the assigned servers to the `busyServers` queue.
   - If no free servers are available, wait until a server becomes free and repeat the process.
4. The final answer will be stored in the `ans` variable, which holds the index of the server assigned to each task.

## A solution in C++

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

std::vector<int> assignTasks(std::vector<int>& servers, std::vector<int>& tasks) {
    int n = servers.size(), m = tasks.size();
    std::vector<int> ans(m);
    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> freeServers;

    for (int i = 0; i < n; ++i) {
        freeServers.push({servers[i], i});
    }

    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> busyServers;
    int currentTask = 0;

    while (currentTask < m) {
        while (!busyServers.empty() && busyServers.top().first <= currentTask) {
            freeServers.push({servers[busyServers.top().second], busyServers.top().second});
            busyServers.pop();
        }

        while (!freeServers.empty() && currentTask < m) {
            ans[currentTask] = freeServers.top().second;
            busyServers.push({currentTask + tasks[currentTask], freeServers.top().second});
            freeServers.pop();
            currentTask++;
        }

        if(freeServers.empty()) {
            currentTask = busyServers.top().first;
        }
    }

    return ans;
}
```
The algorithm works as follows:
1. Create two priority queues, one for free servers and one for busy servers. Both queues use server weight and index as their sorting criteria.
2. Initially, add all servers to the freeServers queue.
3. Loop through the tasks as `currentTask` and do the following:
   - If there are any busy servers that have become free, move them from the `busyServers` queue to the `freeServers` queue.
   - Assign tasks to free servers from the `freeServers` queue and add the assigned servers to the `busyServers` queue.
   - If no free servers are available, wait until a server becomes free and repeat the process.
4. The final answer will be stored in the `ans` variable, which holds the index of the server assigned to each task.

## A solution in Python

```python
from queue import PriorityQueue

def assignTasks(servers, tasks):
    n, m = len(servers), len(tasks)
    ans = [0] * m
    freeServers = PriorityQueue()

    for i in range(n):
        freeServers.put((servers[i], i))

    busyServers = PriorityQueue()
    currentTask = 0

    while currentTask < m:
        while not busyServers.empty() and busyServers.queue[0][0] <= currentTask:
            _, idx = busyServers.get()
            freeServers.put((servers[idx], idx))

        while not freeServers.empty() and currentTask < m:
            _, idx = freeServers.get()
            ans[currentTask] = idx
            busyServers.put((currentTask + tasks[currentTask], idx))
            currentTask += 1

        if freeServers.empty():
            currentTask = busyServers.queue[0][0]

    return ans
```
The algorithm works as follows:
1. Create two priority queues, one for free servers and one for busy servers. Both queues use server weight and index as their sorting criteria.
2. Initially, add all servers to the freeServers queue.
3. Loop through the tasks as `currentTask` and do the following:
   - If there are any busy servers that have become free, move them from the `busyServers` queue to the `freeServers` queue.
   - Assign tasks to free servers from the `freeServers` queue and add the assigned servers to the `busyServers` queue.
   - If no free servers are available, wait until a server becomes free and repeat the process.
4. The final answer will be stored in the `ans` variable, which holds the index of the server assigned to each task.

## A solution in Javascript

```javascript
function assignTasks(servers, tasks) {
    const n = servers.length;
    const m = tasks.length;
    const ans = Array(m);
    const freeServers = new PriorityQueue((a, b) => a[0] - b[0] || a[1] - b[1]);

    for (let i = 0; i < n; i++) {
        freeServers.push([servers[i], i]);
    }

    const busyServers = new PriorityQueue((a, b) => a[0] - b[0] || a[1] - b[1]);
    let currentTask = 0;

    while (currentTask < m) {
        while (busyServers.size() > 0 && busyServers.peek()[0] <= currentTask) {
            const [_, idx] = busyServers.pop();
            freeServers.push([servers[idx], idx]);
        }

        while (!freeServers.isEmpty() && currentTask < m) {
            const [_, idx] = freeServers.pop();
            ans[currentTask] = idx;
            busyServers.push([currentTask + tasks[currentTask], idx]);
            currentTask++;
        }

        if (freeServers.isEmpty()) {
            currentTask = busyServers.peek()[0];
        }
    }

    return ans;
}

class PriorityQueue {
    constructor(comparator) {
        this.data = [];
        this.compare = comparator || ((a, b) => a - b);
    }

    push(value) { this.data.push(value); this.data.sort(this.compare); }
    pop() { return this.data.shift(); }
    peek() { return this.data[0]; }
    size() { return this.data.length; }
    isEmpty() { return this.data.length === 0; }
}
```
The algorithm works as follows:
1. Create two priority queues, one for free servers and one for busy servers. Both queues use server weight and index as their sorting criteria.
2. Initially, add all servers to the freeServers queue.
3. Loop through the tasks as `currentTask` and do the following:
   - If there are any busy servers that have become free, move them from the `busyServers` queue to the `freeServers` queue.
   - Assign tasks to free servers from the `freeServers` queue and add the assigned servers to the `busyServers` queue.
   - If no free servers are available, wait until a server becomes free and repeat the process.
4. The final answer will be stored in the `ans` variable, which holds the index of the server assigned to each task.