# Get Biggest Three Rhombus Sums in a Grid

- slug: get-biggest-three-rhombus-sums-in-a-grid
- difficulty: Medium

You are given an `m x n` integer matrix `grid`.

A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each **rhombus sum**:

Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.

Return _the biggest three **distinct rhombus sums** in the_ `grid` _in **descending order**__. If there are less than three distinct values, return all of them_.

**Example 1:**

**Input:** grid = \[\[3,4,5,1,3\],\[3,3,4,2,3\],\[20,30,200,40,10\],\[1,5,5,4,1\],\[4,3,2,2,5\]\]
**Output:** \[228,216,211\]
**Explanation:** The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 20 + 3 + 200 + 5 = 228
- Red: 200 + 2 + 10 + 4 = 216
- Green: 5 + 200 + 4 + 2 = 211

**Example 2:**

**Input:** grid = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[20,9,8\]
**Explanation:** The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 4 + 2 + 6 + 8 = 20
- Red: 9 (area 0 rhombus in the bottom right corner)
- Green: 8 (area 0 rhombus in the bottom middle)

**Example 3:**

**Input:** grid = \[\[7,7,7\]\]
**Output:** \[7\]
**Explanation:** All three possible rhombus sums are the same, so return \[7\].

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 50`
*   `1 <= grid[i][j] <= 105`

## A solution in Java

```java
public boolean check(int[] nums) {
    int count = 0;
    for (int i = 1; i < nums.length; ++i) {
        if (nums[i] < nums[i - 1]) {
            ++count;
        }
        if (count > 1) {
            return false;
        }
    }
    return count == 1 || nums[0] >= nums[nums.length - 1];
}
```
The algorithm iterates through the array and checks if the current element is less than the previous element. If it is, this creates a count variable incrementing by 1. If the count is greater than 1, it means there is more than one place where the array is not in non-decreasing order, so return false.

If the count is not greater than 1 after the iteration and is equal to 1 or the first element of the array is greater than or equal to the last element, it's a rotated non-decreasing array, so return true.

## A solution in C++

```cpp
bool check(vector<int>& nums) {
    int count = 0;
    for (int i = 1; i < nums.size(); ++i) {
        if (nums[i] < nums[i - 1]) {
            ++count;
        }
        if (count > 1) {
            return false;
        }
    }
    return (count == 1) || (nums.front() >= nums.back());
}
```
The algorithm iterates through the array and checks if the current element is less than the previous element. If it is, this creates a count variable incrementing by 1. If the count is greater than 1, it means there is more than one place where the array is not in non-decreasing order, so return false.

If the count is not greater than 1 after the iteration and is equal to 1 or the first element of the array is greater than or equal to the last element, it's a rotated non-decreasing array, so return true.

## A solution in Python

```python
def check(nums):
    count = 0
    for i in range(1, len(nums)):
        if nums[i] < nums[i - 1]:
            count += 1
        if count > 1:
            return False
    return count == 1 or nums[0] >= nums[-1]
```
The algorithm iterates through the array and checks if the current element is less than the previous element. If it is, this creates a count variable incrementing by 1. If the count is greater than 1, it means there is more than one place where the array is not in non-decreasing order, so return false.

If the count is not greater than 1 after the iteration and is equal to 1 or the first element of the array is greater than or equal to the last element, it's a rotated non-decreasing array, so return true.

## A solution in Javascript

```javascript
function check(nums) {
    let count = 0;
    for (let i = 1; i < nums.length; ++i) {
        if (nums[i] < nums[i - 1]) {
            ++count;
        }
        if (count > 1) {
            return false;
        }
    }
    return count === 1 || nums[0] >= nums[nums.length - 1];
}
```
The algorithm iterates through the array and checks if the current element is less than the previous element. If it is, this creates a count variable incrementing by 1. If the count is greater than 1, it means there is more than one place where the array is not in non-decreasing order, so return false.

If the count is not greater than 1 after the iteration and is equal to 1 or the first element of the array is greater than or equal to the last element, it's a rotated non-decreasing array, so return true.


# Minimum XOR Sum of Two Arrays

- slug: minimum-xor-sum-of-two-arrays
- difficulty: Hard

You are given two integer arrays `nums1` and `nums2` of length `n`.

The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**).

*   For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4`.

Rearrange the elements of `nums2` such that the resulting **XOR sum** is **minimized**.

Return _the **XOR sum** after the rearrangement_.

**Example 1:**

**Input:** nums1 = \[1,2\], nums2 = \[2,3\]
**Output:** 2
**Explanation:** Rearrange `nums2` so that it becomes `[3,2]`.
The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.

**Example 2:**

**Input:** nums1 = \[1,0,3\], nums2 = \[5,3,4\]
**Output:** 8
**Explanation:** Rearrange `nums2` so that it becomes `[5,4,3]`.
The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.

**Constraints:**

*   `n == nums1.length`
*   `n == nums2.length`
*   `1 <= n <= 14`
*   `0 <= nums1[i], nums2[i] <= 107`

## A solution in Java

```java
public int maxScore(int a, int b, int c) {
    return (a + b + c - Math.max(a, Math.max(b, c))) / 2;
}
```
The algorithm works by calculating the sum of all three piles `a`, `b`, and `c` and subtracting the size of the largest pile. Since we can only take stones from two different piles at a time, we cannot take stones from the largest pile after we've equalized the stones in the other two piles. So, by subtracting the size of the largest pile, we're essentially finding out the sum of the stones in the other two piles that can be used for scoring points. Finally, we divide our result by 2 since we need two stones to score a point. In Python, we use integer division `//` to get the result as an integer.

The key insight is that the optimal strategy is to always take stones from the two largest piles in every turn. This way, the pile sizes remain as matched as possible, ensuring we maximize the number of moves available to us. Since each move reduces the sum of the two largest piles by one, we can simplify the calculation as described above without enumerating each move explicitly.

## A solution in C++

```cpp
int maxScore(int a, int b, int c) {
    return (a + b + c - std::max({a, b, c})) / 2;
}
```
The algorithm works by calculating the sum of all three piles `a`, `b`, and `c` and subtracting the size of the largest pile. Since we can only take stones from two different piles at a time, we cannot take stones from the largest pile after we've equalized the stones in the other two piles. So, by subtracting the size of the largest pile, we're essentially finding out the sum of the stones in the other two piles that can be used for scoring points. Finally, we divide our result by 2 since we need two stones to score a point. In Python, we use integer division `//` to get the result as an integer.

The key insight is that the optimal strategy is to always take stones from the two largest piles in every turn. This way, the pile sizes remain as matched as possible, ensuring we maximize the number of moves available to us. Since each move reduces the sum of the two largest piles by one, we can simplify the calculation as described above without enumerating each move explicitly.

## A solution in Python

```python
def max_score(a: int, b: int, c: int) -> int:
    return (a + b + c - max(a, b, c)) // 2
```
The algorithm works by calculating the sum of all three piles `a`, `b`, and `c` and subtracting the size of the largest pile. Since we can only take stones from two different piles at a time, we cannot take stones from the largest pile after we've equalized the stones in the other two piles. So, by subtracting the size of the largest pile, we're essentially finding out the sum of the stones in the other two piles that can be used for scoring points. Finally, we divide our result by 2 since we need two stones to score a point. In Python, we use integer division `//` to get the result as an integer.

The key insight is that the optimal strategy is to always take stones from the two largest piles in every turn. This way, the pile sizes remain as matched as possible, ensuring we maximize the number of moves available to us. Since each move reduces the sum of the two largest piles by one, we can simplify the calculation as described above without enumerating each move explicitly.

## A solution in Javascript

```javascript
function maxScore(a, b, c) {
    return (a + b + c - Math.max(a, Math.max(b, c))) / 2;
}
```
The algorithm works by calculating the sum of all three piles `a`, `b`, and `c` and subtracting the size of the largest pile. Since we can only take stones from two different piles at a time, we cannot take stones from the largest pile after we've equalized the stones in the other two piles. So, by subtracting the size of the largest pile, we're essentially finding out the sum of the stones in the other two piles that can be used for scoring points. Finally, we divide our result by 2 since we need two stones to score a point. In Python, we use integer division `//` to get the result as an integer.

The key insight is that the optimal strategy is to always take stones from the two largest piles in every turn. This way, the pile sizes remain as matched as possible, ensuring we maximize the number of moves available to us. Since each move reduces the sum of the two largest piles by one, we can simplify the calculation as described above without enumerating each move explicitly.


# Check if Word Equals Summation of Two Words

- slug: check-if-word-equals-summation-of-two-words
- difficulty: Easy

The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.).

The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an integer.

*   For example, if `s = "acb "`, we concatenate each letter's letter value, resulting in `"021 "`. After converting it, we get `21`.

You are given three strings `firstWord`, `secondWord`, and `targetWord`, each consisting of lowercase English letters `'a'` through `'j'` **inclusive**.

Return `true` _if the **summation** of the **numerical values** of_ `firstWord` _and_ `secondWord` _equals the **numerical value** of_ `targetWord`_, or_ `false` _otherwise._

**Example 1:**

**Input:** firstWord =  "acb ", secondWord =  "cba ", targetWord =  "cdb "
**Output:** true
**Explanation:**
The numerical value of firstWord is  "acb " ->  "021 " -> 21.
The numerical value of secondWord is  "cba " ->  "210 " -> 210.
The numerical value of targetWord is  "cdb " ->  "231 " -> 231.
We return true because 21 + 210 == 231.

**Example 2:**

**Input:** firstWord =  "aaa ", secondWord =  "a ", targetWord =  "aab "
**Output:** false
**Explanation:**
The numerical value of firstWord is  "aaa " ->  "000 " -> 0.
The numerical value of secondWord is  "a " ->  "0 " -> 0.
The numerical value of targetWord is  "aab " ->  "001 " -> 1.
We return false because 0 + 0 != 1.

**Example 3:**

**Input:** firstWord =  "aaa ", secondWord =  "a ", targetWord =  "aaaa "
**Output:** true
**Explanation:**
The numerical value of firstWord is  "aaa " ->  "000 " -> 0.
The numerical value of secondWord is  "a " ->  "0 " -> 0.
The numerical value of targetWord is  "aaaa " ->  "0000 " -> 0.
We return true because 0 + 0 == 0.

**Constraints:**

*   `1 <= firstWord.length,` `secondWord.length,` `targetWord.length <= 8`
*   `firstWord`, `secondWord`, and `targetWord` consist of lowercase English letters from `'a'` to `'j'` **inclusive**.

## A solution in Java

```java
public String largestMerge(String word1, String word2) {
    StringBuilder merge = new StringBuilder();
    while (!word1.isEmpty() || !word2.isEmpty()) {
        if (word1.compareTo(word2) > 0) {
            merge.append(word1.charAt(0));
            word1 = word1.substring(1);
        } else {
            merge.append(word2.charAt(0));
            word2 = word2.substring(1);
        }
    }
    return merge.toString();
}
```
The algorithm starts with two given strings, `word1` and `word2`. The goal is to create the lexicographically largest `merge` string by choosing characters from either of the input strings. The algorithm operates in a `while` loop that continues until both input strings are empty.

In each iteration of the loop, the algorithm compares the input strings lexicographically. If `word1` is lexicographically larger, it takes the first character of `word1`, appends it to the `merge` string, and removes it from the input string. If `word2` is lexicographically larger or equal, it does the same operation for `word2`.

This process continues until both input strings are empty, resulting in the lexicographically largest possible `merge` string. Then the `merge` string is returned.

## A solution in C++

```cpp
#include <string>

std::string largestMerge(std::string word1, std::string word2) {
    std::string merge = "";
    while (!word1.empty() || !word2.empty()) {
        if (word1 > word2) {
            merge += word1[0];
            word1 = word1.substr(1);
        } else {
            merge += word2[0];
            word2 = word2.substr(1);
        }
    }
    return merge;
}
```
The algorithm starts with two given strings, `word1` and `word2`. The goal is to create the lexicographically largest `merge` string by choosing characters from either of the input strings. The algorithm operates in a `while` loop that continues until both input strings are empty.

In each iteration of the loop, the algorithm compares the input strings lexicographically. If `word1` is lexicographically larger, it takes the first character of `word1`, appends it to the `merge` string, and removes it from the input string. If `word2` is lexicographically larger or equal, it does the same operation for `word2`.

This process continues until both input strings are empty, resulting in the lexicographically largest possible `merge` string. Then the `merge` string is returned.

## A solution in Python

```python
def largest_merge(word1: str, word2: str) -> str:
    merge = []
    while word1 or word2:
        if word1 > word2:
            merge.append(word1[0])
            word1 = word1[1:]
        else:
            merge.append(word2[0])
            word2 = word2[1:]
    return ''.join(merge)
```
The algorithm starts with two given strings, `word1` and `word2`. The goal is to create the lexicographically largest `merge` string by choosing characters from either of the input strings. The algorithm operates in a `while` loop that continues until both input strings are empty.

In each iteration of the loop, the algorithm compares the input strings lexicographically. If `word1` is lexicographically larger, it takes the first character of `word1`, appends it to the `merge` string, and removes it from the input string. If `word2` is lexicographically larger or equal, it does the same operation for `word2`.

This process continues until both input strings are empty, resulting in the lexicographically largest possible `merge` string. Then the `merge` string is returned.

## A solution in Javascript

```javascript
function largestMerge(word1, word2) {
    let merge = "";
    while (word1.length > 0 || word2.length > 0) {
        if (word1.localeCompare(word2) > 0) {
            merge += word1[0];
            word1 = word1.slice(1);
        } else {
            merge += word2[0];
            word2 = word2.slice(1);
        }
    }
    return merge;
}
```
The algorithm starts with two given strings, `word1` and `word2`. The goal is to create the lexicographically largest `merge` string by choosing characters from either of the input strings. The algorithm operates in a `while` loop that continues until both input strings are empty.

In each iteration of the loop, the algorithm compares the input strings lexicographically. If `word1` is lexicographically larger, it takes the first character of `word1`, appends it to the `merge` string, and removes it from the input string. If `word2` is lexicographically larger or equal, it does the same operation for `word2`.

This process continues until both input strings are empty, resulting in the lexicographically largest possible `merge` string. Then the `merge` string is returned.


# Maximum Value after Insertion

- slug: maximum-value-after-insertion
- difficulty: Medium

You are given a very large integer `n`, represented as a string, and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number.

You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal representation of `n`. You **cannot** insert `x` to the left of the negative sign.

*   For example, if `n = 73` and `x = 6`, it would be best to insert it between `7` and `3`, making `n = 763`.
*   If `n = -55` and `x = 2`, it would be best to insert it before the first `5`, making `n = -255`.

Return _a string representing the **maximum** value of_ `n`_ after the insertion_.

**Example 1:**

**Input:** n =  "99 ", x = 9
**Output:**  "999 "
**Explanation:** The result is the same regardless of where you insert 9.

**Example 2:**

**Input:** n =  "-13 ", x = 2
**Output:**  "-123 "
**Explanation:** You can make n one of {-213, -123, -132}, and the largest of those three is -123.

**Constraints:**

*   `1 <= n.length <= 105`
*   `1 <= x <= 9`
*   The digits in `n` are in the range `[1, 9]`.
*   `n` is a valid representation of an integer.
*   In the case of a negative `n`, it will begin with `'-'`.

## A solution in Java

```java
import java.util.TreeSet;

public int minAbsDifference(int[] nums, int goal) {
    int n = nums.length;
    int half = n / 2;
    int[] left = Arrays.copyOfRange(nums, 0, half);
    int[] right = Arrays.copyOfRange(nums, half, n);
    TreeSet<Integer> sums = new TreeSet<>();

    for (int mask = 0; mask < (1 << left.length); ++mask) {
        int sum = 0;
        for (int i = 0; i < left.length; ++i) {
            if ((mask & (1 << i)) != 0) {
                sum += left[i];
            }
        }
        sums.add(sum);
    }

    int ans = Math.abs(goal);

    for (int mask = 0; mask < (1 << right.length); ++mask) {
        int sum = 0;
        for (int i = 0; i < right.length; ++i) {
            if ((mask & (1 << i)) != 0) {
                sum += right[i];
            }
        }
        Integer ceiling = sums.ceiling(goal - sum);
        if (ceiling != null) {
            ans = Math.min(ans, Math.abs(ceiling + sum - goal));
        }
        Integer floor = sums.floor(goal - sum);
        if (floor != null) {
            ans = Math.min(ans, Math.abs(floor + sum - goal));
        }
    }

    return ans;
}
```
The algorithm first splits the input array `nums` into two roughly equal halves, `left` and `right`. Then, it computes all possible sums for each of the half arrays by checking all subsequences using binary masks. For the left half array, it saves all possible sums in a set (`sums`).

Once all possible sums for the left half are saved, it computes all possible sums for the `right` half. For each sum in the right half, it finds the sum in the left half that is closest to the remaining value needed to reach the `goal`. In C++ and Java, this is done using `lower_bound` and `ceiling/floor` functions respectively, whereas in Python and JavaScript, this is done using the `min` function with an appropriate key or the `reduce` function.

The algorithm then updates the candidate answer by taking the minimum absolute difference between the current best answer and the calculated sum from both halves of the array. Finally, it returns the minimum absolute difference found.

## A solution in C++

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

int minAbsDifference(std::vector<int>& nums, int goal) {
    int n = nums.size();
    std::vector<int> left(nums.begin(), nums.begin() + n / 2);
    std::vector<int> right(nums.begin() + n / 2, nums.end());
    std::set<int> sums;

    for (int mask = 0; mask < (1 << left.size()); ++mask) {
        int sum = 0;
        for (int i = 0; i < left.size(); ++i) {
            if (mask & (1 << i)) {
                sum += left[i];
            }
        }
        sums.insert(sum);
    }

    int ans = std::abs(goal);

    for (int mask = 0; mask < (1 << right.size()); ++mask) {
        int sum = 0;
        for (int i = 0; i < right.size(); ++i) {
            if (mask & (1 << i)) {
                sum += right[i];
            }
        }
        auto it = sums.lower_bound(goal - sum);
        if (it != sums.end()) {
            ans = std::min(ans, std::abs((*it) + sum - goal));
        }
        if (it != sums.begin()) {
            ans = std::min(ans, std::abs((*std::prev(it)) + sum - goal));
        }
    }

    return ans;
}
```
The algorithm first splits the input array `nums` into two roughly equal halves, `left` and `right`. Then, it computes all possible sums for each of the half arrays by checking all subsequences using binary masks. For the left half array, it saves all possible sums in a set (`sums`).

Once all possible sums for the left half are saved, it computes all possible sums for the `right` half. For each sum in the right half, it finds the sum in the left half that is closest to the remaining value needed to reach the `goal`. In C++ and Java, this is done using `lower_bound` and `ceiling/floor` functions respectively, whereas in Python and JavaScript, this is done using the `min` function with an appropriate key or the `reduce` function.

The algorithm then updates the candidate answer by taking the minimum absolute difference between the current best answer and the calculated sum from both halves of the array. Finally, it returns the minimum absolute difference found.

## A solution in Python

```python
from itertools import combinations

def minAbsDifference(nums, goal):
    n = len(nums)
    left = nums[:n//2]
    right = nums[n//2:]

    sums_left = set()

    for i in range(len(left) + 1):
        for comb in combinations(left, i):
            sums_left.add(sum(comb))

    ans = abs(goal)

    for i in range(len(right) + 1):
        for comb in combinations(right, i):
            sum_r = sum(comb)
            sum_goal = goal - sum_r
            sum_l = min(sums_left, key=lambda x: abs(x - sum_goal))

            ans = min(ans, abs(sum_l + sum_r - goal))

    return ans
```
The algorithm first splits the input array `nums` into two roughly equal halves, `left` and `right`. Then, it computes all possible sums for each of the half arrays by checking all subsequences using binary masks. For the left half array, it saves all possible sums in a set (`sums`).

Once all possible sums for the left half are saved, it computes all possible sums for the `right` half. For each sum in the right half, it finds the sum in the left half that is closest to the remaining value needed to reach the `goal`. In C++ and Java, this is done using `lower_bound` and `ceiling/floor` functions respectively, whereas in Python and JavaScript, this is done using the `min` function with an appropriate key or the `reduce` function.

The algorithm then updates the candidate answer by taking the minimum absolute difference between the current best answer and the calculated sum from both halves of the array. Finally, it returns the minimum absolute difference found.

## A solution in Javascript

```javascript
function minAbsDifference(nums, goal) {
    const n = nums.length;
    const left = nums.slice(0, n / 2);
    const right = nums.slice(n / 2);
    const sums = new Set();

    for (let mask = 0; mask < (1 << left.length); ++mask) {
        let sum = 0;
        for (let i = 0; i < left.length; ++i) {
            if (mask & (1 << i)) {
                sum += left[i];
            }
        }
        sums.add(sum);
    }

    let ans = Math.abs(goal);

    for (let mask = 0; mask < (1 << right.length); ++mask) {
        let sum = 0;
        for (let i = 0; i < right.length; ++i) {
            if (mask & (1 << i)) {
                sum += right[i];
            }
        }
        const target = goal - sum;
        const candidate = [...sums].reduce((a, b) => Math.abs(b - target) < Math.abs(a - target) ? b : a);

        ans = Math.min(ans, Math.abs(candidate + sum - goal));
    }

    return ans;
}
```
The algorithm first splits the input array `nums` into two roughly equal halves, `left` and `right`. Then, it computes all possible sums for each of the half arrays by checking all subsequences using binary masks. For the left half array, it saves all possible sums in a set (`sums`).

Once all possible sums for the left half are saved, it computes all possible sums for the `right` half. For each sum in the right half, it finds the sum in the left half that is closest to the remaining value needed to reach the `goal`. In C++ and Java, this is done using `lower_bound` and `ceiling/floor` functions respectively, whereas in Python and JavaScript, this is done using the `min` function with an appropriate key or the `reduce` function.

The algorithm then updates the candidate answer by taking the minimum absolute difference between the current best answer and the calculated sum from both halves of the array. Finally, it returns the minimum absolute difference found.


# Process Tasks Using Servers

- slug: process-tasks-using-servers
- difficulty: Medium

You are given two **0-indexed** integer arrays `servers` and `tasks` of lengths `n` and `m` respectively. `servers[i]` is the **weight** of the `ith` server, and `tasks[j]` is the **time needed** to process the `jth` task **in seconds**.

Tasks are assigned to the servers using a **task queue**. Initially, all servers are free, and the queue is **empty**.

At second `j`, the `jth` task is **inserted** into the queue (starting with the `0th` task being inserted at second `0`). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the **smallest weight**, and in case of a tie, it is assigned to a free server with the **smallest index**.

If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned **in order of insertion** following the weight and index priorities above.

A server that is assigned task `j` at second `t` will be free again at second `t + tasks[j]`.

Build an array `ans` of length `m`, where `ans[j]` is the **index** of the server the `jth` task will be assigned to.

Return _the array_ `ans`.

**Example 1:**

**Input:** servers = \[3,3,2\], tasks = \[1,2,3,2,1,2\]
**Output:** \[2,2,0,2,1,2\]
**Explanation:** Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 2 until second 1.
- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.
- At second 2, task 2 is added and processed using server 0 until second 5.
- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.
- At second 4, task 4 is added and processed using server 1 until second 5.
- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.

**Example 2:**

**Input:** servers = \[5,1,4,3,2\], tasks = \[2,1,2,4,5,2,1\]
**Output:** \[1,4,1,4,1,3,2\]
**Explanation:** Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 1 until second 2.
- At second 1, task 1 is added and processed using server 4 until second 2.
- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4.
- At second 3, task 3 is added and processed using server 4 until second 7.
- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9.
- At second 5, task 5 is added and processed using server 3 until second 7.
- At second 6, task 6 is added and processed using server 2 until second 7.

**Constraints:**

*   `servers.length == n`
*   `tasks.length == m`
*   `1 <= n, m <= 2 * 105`
*   `1 <= servers[i], tasks[j] <= 2 * 105`

## A solution in Java

```java
import java.util.*;

public int[] assignTasks(int[] servers, int[] tasks) {
    int[] result = new int[tasks.length];
    PriorityQueue<int[]> freeServers = new PriorityQueue<>((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
    PriorityQueue<int[]> busyServers = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));

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

    int time = 0;
    int taskIndex = 0;

    while (taskIndex < tasks.length) {
        while (!busyServers.isEmpty() && busyServers.peek()[0] <= time) {
            freeServers.offer(busyServers.poll());
        }

        while (!freeServers.isEmpty() && taskIndex <= time && taskIndex < tasks.length) {
            int[] server = freeServers.poll();
            result[taskIndex] = server[1];
            busyServers.offer(new int[] {time + tasks[taskIndex], server[0], server[1]});
            taskIndex++;
        }

        time++;
    }

    return result;
}
```
The algorithm implemented for each programming languages follows the same logic described below:

1. Create two priority queues called `free_servers` and `busy_servers`. The `free_servers` priority queue will store the free servers following the minimum weight and index order. The `busy_servers` priority queue will store the busy servers following the order of their release time.
2. Add all servers to the `free_servers` priority queue.
3. Iterate through the tasks array using a variable `t` representing the time step.
4. For each time step `t`, check if there is any server in `busy_servers` that became free (i.e., its release time equals the current time step `t`). If there is any, remove it from `busy_servers` and add it back to the `free_servers` queue.
5. If at the current time step `t` there is a task and there is any free server in the `free_servers` queue, assign the task to the smallest free server and add it to the `busy_servers` queue with the updated release time (`t + tasks[i]`, where `i` is the current task index).
6. Continue the loop until all tasks are assigned.

Time complexity: O(n * log(n) + m * log(n)) - At most we are sorting and looping through each server and task in the algorithm.
Space complexity: O(n + m) - We are storing free and busy servers, which have a space complexity proportional to n and the result array which has space complexity proportional to m.

## A solution in C++

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

std::vector<int> assignTasks(std::vector<int>& servers, std::vector<int>& tasks) {
    std::vector<int> res(tasks.size());
    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> free_servers;
    std::priority_queue<std::pair<int, std::pair<int, int>>, std::vector<std::pair<int, std::pair<int, int>>>, std::greater<std::pair<int, std::pair<int, int>>>> busy_servers;

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

    for (int t = 0, i = 0; i < tasks.size(); ++t) {
        while (!busy_servers.empty() && busy_servers.top().first == t) {
            auto [server, job] = busy_servers.top().second;
            free_servers.push({server, job});
            busy_servers.pop();
        }
        if (t < tasks.size() && !free_servers.empty()) {
            res[i] = free_servers.top().second;
            busy_servers.push({t + tasks[i], {servers[res[i]], res[i]}});
            free_servers.pop();
            ++i;
        }
    }

    return res;
}
```
The algorithm implemented for each programming languages follows the same logic described below:

1. Create two priority queues called `free_servers` and `busy_servers`. The `free_servers` priority queue will store the free servers following the minimum weight and index order. The `busy_servers` priority queue will store the busy servers following the order of their release time.
2. Add all servers to the `free_servers` priority queue.
3. Iterate through the tasks array using a variable `t` representing the time step.
4. For each time step `t`, check if there is any server in `busy_servers` that became free (i.e., its release time equals the current time step `t`). If there is any, remove it from `busy_servers` and add it back to the `free_servers` queue.
5. If at the current time step `t` there is a task and there is any free server in the `free_servers` queue, assign the task to the smallest free server and add it to the `busy_servers` queue with the updated release time (`t + tasks[i]`, where `i` is the current task index).
6. Continue the loop until all tasks are assigned.

Time complexity: O(n * log(n) + m * log(n)) - At most we are sorting and looping through each server and task in the algorithm.
Space complexity: O(n + m) - We are storing free and busy servers, which have a space complexity proportional to n and the result array which has space complexity proportional to m.

## A solution in Python

```python
import heapq
from typing import List

def assignTasks(servers: List[int], tasks: List[int]) -> List[int]:
    free_servers = [(servers[i], i) for i in range(len(servers))]
    heapq.heapify(free_servers)
    busy_servers = []
    result = [0] * len(tasks)

    for time in range(len(tasks)):
        while busy_servers and busy_servers[0][0] <= time:
            _, server_elem = heapq.heappop(busy_servers)
            heapq.heappush(free_servers, server_elem)

        if free_servers:
            server_elem = heapq.heappop(free_servers)
            result[time] = server_elem[1]
            heapq.heappush(busy_servers, (time + tasks[time], server_elem))

    return result
```
The algorithm implemented for each programming languages follows the same logic described below:

1. Create two priority queues called `free_servers` and `busy_servers`. The `free_servers` priority queue will store the free servers following the minimum weight and index order. The `busy_servers` priority queue will store the busy servers following the order of their release time.
2. Add all servers to the `free_servers` priority queue.
3. Iterate through the tasks array using a variable `t` representing the time step.
4. For each time step `t`, check if there is any server in `busy_servers` that became free (i.e., its release time equals the current time step `t`). If there is any, remove it from `busy_servers` and add it back to the `free_servers` queue.
5. If at the current time step `t` there is a task and there is any free server in the `free_servers` queue, assign the task to the smallest free server and add it to the `busy_servers` queue with the updated release time (`t + tasks[i]`, where `i` is the current task index).
6. Continue the loop until all tasks are assigned.

Time complexity: O(n * log(n) + m * log(n)) - At most we are sorting and looping through each server and task in the algorithm.
Space complexity: O(n + m) - We are storing free and busy servers, which have a space complexity proportional to n and the result array which has space complexity proportional to m.

## A solution in Javascript

```javascript
function assignTasks(servers, tasks) {
    const result = new Array(tasks.length);
    const freeServers = [];
    for (let i = 0; i < servers.length; i++) {
        freeServers.push([servers[i], i]);
    }
    freeServers.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
    const busyServers = [];

    let time = 0;
    let taskIndex = 0;

    while (taskIndex < tasks.length) {
        while (busyServers.length && busyServers[0][0] <= time) {
            const server = busyServers.shift()[1];
            freeServers.push(server);
            freeServers.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
        }

        while (freeServers.length && taskIndex <= time && taskIndex < tasks.length) {
            const server = freeServers.shift();
            result[taskIndex] = server[1];
            busyServers.push([time + tasks[taskIndex], server]);
            busyServers.sort((a, b) => a[0] - b[0] || a[1][1] - b[1][1]);
            taskIndex++;
        }

        time++;
    }

    return result;
}
```
The algorithm implemented for each programming languages follows the same logic described below:

1. Create two priority queues called `free_servers` and `busy_servers`. The `free_servers` priority queue will store the free servers following the minimum weight and index order. The `busy_servers` priority queue will store the busy servers following the order of their release time.
2. Add all servers to the `free_servers` priority queue.
3. Iterate through the tasks array using a variable `t` representing the time step.
4. For each time step `t`, check if there is any server in `busy_servers` that became free (i.e., its release time equals the current time step `t`). If there is any, remove it from `busy_servers` and add it back to the `free_servers` queue.
5. If at the current time step `t` there is a task and there is any free server in the `free_servers` queue, assign the task to the smallest free server and add it to the `busy_servers` queue with the updated release time (`t + tasks[i]`, where `i` is the current task index).
6. Continue the loop until all tasks are assigned.

Time complexity: O(n * log(n) + m * log(n)) - At most we are sorting and looping through each server and task in the algorithm.
Space complexity: O(n + m) - We are storing free and busy servers, which have a space complexity proportional to n and the result array which has space complexity proportional to m.


# Minimum Skips to Arrive at Meeting On Time

- slug: minimum-skips-to-arrive-at-meeting-on-time
- difficulty: Hard

You are given an integer `hoursBefore`, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through `n` roads. The road lengths are given as an integer array `dist` of length `n`, where `dist[i]` describes the length of the `ith` road in **kilometers**. In addition, you are given an integer `speed`, which is the speed (in **km/h**) you will travel at.

After you travel road `i`, you must rest and wait for the **next integer hour** before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.

*   For example, if traveling a road takes `1.4` hours, you must wait until the `2` hour mark before traveling the next road. If traveling a road takes exactly `2` hours, you do not need to wait.

However, you are allowed to **skip** some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.

*   For example, suppose traveling the first road takes `1.4` hours and traveling the second road takes `0.6` hours. Skipping the rest after the first road will mean you finish traveling the second road right at the `2` hour mark, letting you start traveling the third road immediately.

Return _the **minimum number of skips required** to arrive at the meeting on time, or_ `-1` _if it is **impossible**_.

**Example 1:**

**Input:** dist = \[1,3,2\], speed = 4, hoursBefore = 2
**Output:** 1
**Explanation:**
Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.
You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.
Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.

**Example 2:**

**Input:** dist = \[7,3,5,5\], speed = 2, hoursBefore = 10
**Output:** 2
**Explanation:**
Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.
You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.

**Example 3:**

**Input:** dist = \[7,3,5,5\], speed = 1, hoursBefore = 10
**Output:** -1
**Explanation:** It is impossible to arrive at the meeting on time even if you skip all the rests.

**Constraints:**

*   `n == dist.length`
*   `1 <= n <= 1000`
*   `1 <= dist[i] <= 105`
*   `1 <= speed <= 106`
*   `1 <= hoursBefore <= 107`

## A solution in Java

```java
public int minSkips(int[] dist, int speed, int hoursBefore) {
    int n = dist.length;
    double[][] dp = new double[n + 1][n + 1];

    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= n; j++) {
            dp[i][j] = 1e9;
        }
    }
    dp[0][0] = 0;

    for (int i = 0; i < n; i++) {
        for (int j = -1; j < i; j++) {
            double t = dist[i] / (double)speed + (j != -1 ? 1 : 0);
            dp[i + 1][j + 1] = Math.min(dp[i + 1][j + 1], dp[i][j] + t);
            double skipped_t = Math.ceil(dp[i][j] + dist[i] / (double)speed) - dp[i][j];
            dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j] + skipped_t);
        }
    }

    for (int i = 0; i <= n; i++) {
        if (dp[n][i] <= hoursBefore) {
            return i;
        }
    }
    return -1;
}
```
We will use dynamic programming to solve this problem. Our approach is to create a 2D DP array `dp`, where `dp[i][j]` will store the minimum time to reach road `i` by skipping `j` rest times.

1. Initialize the DP array `dp` with a very large value (1e9) for all `i` and `j`, and set `dp[0][0]` to `0`, because initially we are at the starting point and have not skipped any rests.
2. Iterate through all the roads `i` from `0` to `n-1`. For each road `i`, iterate through the number of rests skipped `j` from `-1` to `i-1` (inclusive).
    1. Calculate the time `t` to travel the current road, taking into consideration whether we should wait for the next integer hour or not after completing the previous road. If `j` is equal to `-1`, there is no wait needed, otherwise there is a wait of `1` hour.
    2. Update `dp[i+1][j+1]` by taking the minimum of its current value and the sum of `dp[i][j]` and `t`.
    3. Calculate the time `skipped_t` to travel the current road if we skip the rest, which is equal to the ceiling of the sum of `dp[i][j]` and the travel time of the current road minus `dp[i][j]`.
    4. Update `dp[i+1][j]` by taking the minimum of its current value and the sum of `dp[i][j]` and `skipped_t`.
3. Iterate through the DP array `dp[n][i]` for all `i`, and find the minimum number of skips required to arrive at the meeting on time. If the time is less than or equal to `hoursBefore`, return `i`. If not found, return `-1`.

Time complexity of this approach is O(n^2), and space complexity is also O(n^2) due to the DP array.

## A solution in C++

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

int minSkips(vector<int>& dist, int speed, int hoursBefore) {
    int n = dist.size();
    vector<vector<double>> dp(n + 1, vector<double>(n + 1, 1e9));
    dp[0][0] = 0;

    for (int i = 0; i < n; ++i) {
        for (int j = -1; j < i; ++j) {
            double t = dist[i] / double(speed) + (j != -1);
            dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + t);
            double skipped_t = ceil(dp[i][j] + dist[i] / double(speed)) - dp[i][j];
            dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + skipped_t);
        }
    }

    for (int i = 0; i <= n; ++i) {
        if (dp[n][i] <= hoursBefore) return i;
    }
    return -1;
}
```
We will use dynamic programming to solve this problem. Our approach is to create a 2D DP array `dp`, where `dp[i][j]` will store the minimum time to reach road `i` by skipping `j` rest times.

1. Initialize the DP array `dp` with a very large value (1e9) for all `i` and `j`, and set `dp[0][0]` to `0`, because initially we are at the starting point and have not skipped any rests.
2. Iterate through all the roads `i` from `0` to `n-1`. For each road `i`, iterate through the number of rests skipped `j` from `-1` to `i-1` (inclusive).
    1. Calculate the time `t` to travel the current road, taking into consideration whether we should wait for the next integer hour or not after completing the previous road. If `j` is equal to `-1`, there is no wait needed, otherwise there is a wait of `1` hour.
    2. Update `dp[i+1][j+1]` by taking the minimum of its current value and the sum of `dp[i][j]` and `t`.
    3. Calculate the time `skipped_t` to travel the current road if we skip the rest, which is equal to the ceiling of the sum of `dp[i][j]` and the travel time of the current road minus `dp[i][j]`.
    4. Update `dp[i+1][j]` by taking the minimum of its current value and the sum of `dp[i][j]` and `skipped_t`.
3. Iterate through the DP array `dp[n][i]` for all `i`, and find the minimum number of skips required to arrive at the meeting on time. If the time is less than or equal to `hoursBefore`, return `i`. If not found, return `-1`.

Time complexity of this approach is O(n^2), and space complexity is also O(n^2) due to the DP array.

## A solution in Python

```python
def minSkips(dist, speed, hoursBefore):
    n = len(dist)
    dp = [[1e9] * (n + 1) for _ in range(n + 1)]
    dp[0][0] = 0

    for i in range(n):
        for j in range(i+1):
            t = dist[i] / speed + (1 if j else 0)
            dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + t)
            skipped_t = -(-dist[i] / speed) - dp[i][j]
            dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + skipped_t)

    for i in range(n + 1):
        if dp[n][i] <= hoursBefore:
            return i
    return -1
```
We will use dynamic programming to solve this problem. Our approach is to create a 2D DP array `dp`, where `dp[i][j]` will store the minimum time to reach road `i` by skipping `j` rest times.

1. Initialize the DP array `dp` with a very large value (1e9) for all `i` and `j`, and set `dp[0][0]` to `0`, because initially we are at the starting point and have not skipped any rests.
2. Iterate through all the roads `i` from `0` to `n-1`. For each road `i`, iterate through the number of rests skipped `j` from `-1` to `i-1` (inclusive).
    1. Calculate the time `t` to travel the current road, taking into consideration whether we should wait for the next integer hour or not after completing the previous road. If `j` is equal to `-1`, there is no wait needed, otherwise there is a wait of `1` hour.
    2. Update `dp[i+1][j+1]` by taking the minimum of its current value and the sum of `dp[i][j]` and `t`.
    3. Calculate the time `skipped_t` to travel the current road if we skip the rest, which is equal to the ceiling of the sum of `dp[i][j]` and the travel time of the current road minus `dp[i][j]`.
    4. Update `dp[i+1][j]` by taking the minimum of its current value and the sum of `dp[i][j]` and `skipped_t`.
3. Iterate through the DP array `dp[n][i]` for all `i`, and find the minimum number of skips required to arrive at the meeting on time. If the time is less than or equal to `hoursBefore`, return `i`. If not found, return `-1`.

Time complexity of this approach is O(n^2), and space complexity is also O(n^2) due to the DP array.

## A solution in Javascript

```javascript
function minSkips(dist, speed, hoursBefore) {
    const n = dist.length;
    const dp = Array.from({ length: n + 1 }, () => Array(n + 1).fill(1e9));
    dp[0][0] = 0;

    for (let i = 0; i < n; i++) {
        for (let j = -1; j < i; j++) {
            const t = dist[i] / speed + (j != -1 ? 1 : 0);
            dp[i + 1][j + 1] = Math.min(dp[i + 1][j + 1], dp[i][j] + t);
            const skipped_t = Math.ceil(dp[i][j] + dist[i] / speed) - dp[i][j];
            dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j] + skipped_t);
        }
    }

    for (let i = 0; i <= n; i++) {
        if (dp[n][i] <= hoursBefore) {
            return i;
        }
    }
    return -1;
}
```
We will use dynamic programming to solve this problem. Our approach is to create a 2D DP array `dp`, where `dp[i][j]` will store the minimum time to reach road `i` by skipping `j` rest times.

1. Initialize the DP array `dp` with a very large value (1e9) for all `i` and `j`, and set `dp[0][0]` to `0`, because initially we are at the starting point and have not skipped any rests.
2. Iterate through all the roads `i` from `0` to `n-1`. For each road `i`, iterate through the number of rests skipped `j` from `-1` to `i-1` (inclusive).
    1. Calculate the time `t` to travel the current road, taking into consideration whether we should wait for the next integer hour or not after completing the previous road. If `j` is equal to `-1`, there is no wait needed, otherwise there is a wait of `1` hour.
    2. Update `dp[i+1][j+1]` by taking the minimum of its current value and the sum of `dp[i][j]` and `t`.
    3. Calculate the time `skipped_t` to travel the current road if we skip the rest, which is equal to the ceiling of the sum of `dp[i][j]` and the travel time of the current road minus `dp[i][j]`.
    4. Update `dp[i+1][j]` by taking the minimum of its current value and the sum of `dp[i][j]` and `skipped_t`.
3. Iterate through the DP array `dp[n][i]` for all `i`, and find the minimum number of skips required to arrive at the meeting on time. If the time is less than or equal to `hoursBefore`, return `i`. If not found, return `-1`.

Time complexity of this approach is O(n^2), and space complexity is also O(n^2) due to the DP array.


# Egg Drop With 2 Eggs and N Floors

- slug: egg-drop-with-2-eggs-and-n-floors
- difficulty: Medium

You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.

You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.

In each move, you may take an **unbroken** egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves.

Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is.

**Example 1:**

**Input:** n = 2
**Output:** 2
**Explanation:** We can drop the first egg from floor 1 and the second egg from floor 2.
If the first egg breaks, we know that f = 0.
If the second egg breaks but the first egg didn't, we know that f = 1.
Otherwise, if both eggs survive, we know that f = 2.

**Example 2:**

**Input:** n = 100
**Output:** 14
**Explanation:** One optimal strategy is:
- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.
- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.
- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.
Regardless of the outcome, it takes at most 14 drops to determine f.

**Constraints:**

*   `1 <= n <= 1000`

## A solution in Java

```java
public int minOperationsToAlternate(String s) {
    int countA = 0, countB = 0;
    for (int i = 0; i < s.length(); i++) {
        if (i % 2 == 0) {
            if (s.charAt(i) == '0') countA++;
            else countB++;
        } else {
            if (s.charAt(i) == '0') countB++;
            else countA++;
        }
    }
    return Math.min(countA, countB);
}
```
To solve this problem, we loop through each character in the input string and count how many characters that are '0' and '1'. We should count them separately for odd and even indices. Then we compare the counts for both possible alternating patterns (starting with '0' and starting with '1') and return the minimum count.

1. Initialize two variables `count_a` and `count_b` to 0.
2. Loop through the characters in the string `s`.
    - If the character index is even:
        - Increment `count_a` if the character is '0'.
        - Increment `count_b` if the character is '1'.
    - If the character index is odd:
        - Increment `count_a` if the character is '1'.
        - Increment `count_b` if the character is '0'.
3. Return the minimum of `count_a` and `count_b` as the result.

## A solution in C++

```cpp
int min_operations_to_alternate(const std::string& s) {
    int count_a = 0, count_b = 0;
    for (std::size_t i = 0; i < s.size(); ++i) {
        if (i % 2 == 0) {
            if (s[i] == '0') count_a++;
            else count_b++;
        } else {
            if (s[i] == '0') count_b++;
            else count_a++;
        }
    }
    return std::min(count_a, count_b);
}
```
To solve this problem, we loop through each character in the input string and count how many characters that are '0' and '1'. We should count them separately for odd and even indices. Then we compare the counts for both possible alternating patterns (starting with '0' and starting with '1') and return the minimum count.

1. Initialize two variables `count_a` and `count_b` to 0.
2. Loop through the characters in the string `s`.
    - If the character index is even:
        - Increment `count_a` if the character is '0'.
        - Increment `count_b` if the character is '1'.
    - If the character index is odd:
        - Increment `count_a` if the character is '1'.
        - Increment `count_b` if the character is '0'.
3. Return the minimum of `count_a` and `count_b` as the result.

## A solution in Python

```python
def min_operations_to_alternate(s: str) -> int:
    count_a, count_b = 0, 0
    for i, c in enumerate(s):
        if i % 2 == 0:
            if c == '0':
                count_a += 1
            else:
                count_b += 1
        else:
            if c == '0':
                count_b += 1
            else:
                count_a += 1
    return min(count_a, count_b)
```
To solve this problem, we loop through each character in the input string and count how many characters that are '0' and '1'. We should count them separately for odd and even indices. Then we compare the counts for both possible alternating patterns (starting with '0' and starting with '1') and return the minimum count.

1. Initialize two variables `count_a` and `count_b` to 0.
2. Loop through the characters in the string `s`.
    - If the character index is even:
        - Increment `count_a` if the character is '0'.
        - Increment `count_b` if the character is '1'.
    - If the character index is odd:
        - Increment `count_a` if the character is '1'.
        - Increment `count_b` if the character is '0'.
3. Return the minimum of `count_a` and `count_b` as the result.

## A solution in Javascript

```javascript
function minOperationsToAlternate(s) {
    let countA = 0, countB = 0;
    for (let i = 0; i < s.length; i++) {
        if (i % 2 === 0) {
            if (s[i] === '0') countA++;
            else countB++;
        } else {
            if (s[i] === '0') countB++;
            else countA++;
        }
    }
    return Math.min(countA, countB);
}
```
To solve this problem, we loop through each character in the input string and count how many characters that are '0' and '1'. We should count them separately for odd and even indices. Then we compare the counts for both possible alternating patterns (starting with '0' and starting with '1') and return the minimum count.

1. Initialize two variables `count_a` and `count_b` to 0.
2. Loop through the characters in the string `s`.
    - If the character index is even:
        - Increment `count_a` if the character is '0'.
        - Increment `count_b` if the character is '1'.
    - If the character index is odd:
        - Increment `count_a` if the character is '1'.
        - Increment `count_b` if the character is '0'.
3. Return the minimum of `count_a` and `count_b` as the result.


# Count Pairs in Two Arrays

- slug: count-pairs-in-two-arrays
- difficulty: Medium

Given two integer arrays `nums1` and `nums2` of length `n`, count the pairs of indices `(i, j)` such that `i < j` and `nums1[i] + nums1[j] > nums2[i] + nums2[j]`.

Return _the **number of pairs** satisfying the condition._

**Example 1:**

**Input:** nums1 = \[2,1,2,1\], nums2 = \[1,2,1,2\]
**Output:** 1
**Explanation**: The pairs satisfying the condition are:
- (0, 2) where 2 + 2 > 1 + 1.

**Example 2:**

**Input:** nums1 = \[1,10,6,2\], nums2 = \[1,4,1,5\]
**Output:** 5
**Explanation**: The pairs satisfying the condition are:
- (0, 1) where 1 + 10 > 1 + 4.
- (0, 2) where 1 + 6 > 1 + 1.
- (1, 2) where 10 + 6 > 4 + 1.
- (1, 3) where 10 + 2 > 4 + 5.
- (2, 3) where 6 + 2 > 1 + 5.

**Constraints:**

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

## A solution in Java

```java
int countHomogenous(String s) {
    int res = 0, count = 1, mod = 1000000007;
    for (int i = 1; i < s.length(); ++i) {
        count = (s.charAt(i) == s.charAt(i - 1)) ? count + 1 : 1;
        res = (res + count) % mod;
    }
    return res;
}
```
The algorithm to solve this problem involves iterating through the given string and keeping track of counts for similar contiguous characters. Initialize a result variable, a count variable and the modulo for 10^9 + 7 to avoid large number problems.

Loop through the string starting from the second character. Compare the current character to the previous character. If the characters are the same, increment the count, otherwise reset it to 1. Add the count value to the result and perform modulo on the result after the addition.

After looping through the entire string, return the result. This approach has a time complexity of O(n), where n is the length of the input string.

## A solution in C++

```cpp
int countHomogenous(std::string s) {
    int res = 0, count = 1, mod = 1e9 + 7;
    for (int i = 1; i < s.size(); ++i) {
        count = (s[i] == s[i - 1]) ? count + 1 : 1;
        res = (res + count) % mod;
    }
    return res;
}
```
The algorithm to solve this problem involves iterating through the given string and keeping track of counts for similar contiguous characters. Initialize a result variable, a count variable and the modulo for 10^9 + 7 to avoid large number problems.

Loop through the string starting from the second character. Compare the current character to the previous character. If the characters are the same, increment the count, otherwise reset it to 1. Add the count value to the result and perform modulo on the result after the addition.

After looping through the entire string, return the result. This approach has a time complexity of O(n), where n is the length of the input string.

## A solution in Python

```python
def count_homogenous(s: str) -> int:
    res, count, mod = 0, 1, 10**9 + 7
    for i in range(1, len(s)):
        count = count + 1 if s[i] == s[i - 1] else 1
        res = (res + count) % mod
    return res
```
The algorithm to solve this problem involves iterating through the given string and keeping track of counts for similar contiguous characters. Initialize a result variable, a count variable and the modulo for 10^9 + 7 to avoid large number problems.

Loop through the string starting from the second character. Compare the current character to the previous character. If the characters are the same, increment the count, otherwise reset it to 1. Add the count value to the result and perform modulo on the result after the addition.

After looping through the entire string, return the result. This approach has a time complexity of O(n), where n is the length of the input string.

## A solution in Javascript

```javascript
function countHomogenous(s) {
    let res = 0, count = 1, mod = 1e9 + 7;
    for (let i = 1; i < s.length; ++i) {
        count = (s[i] === s[i - 1]) ? count + 1 : 1;
        res = (res + count) % mod;
    }
    return res;
}
```
The algorithm to solve this problem involves iterating through the given string and keeping track of counts for similar contiguous characters. Initialize a result variable, a count variable and the modulo for 10^9 + 7 to avoid large number problems.

Loop through the string starting from the second character. Compare the current character to the previous character. If the characters are the same, increment the count, otherwise reset it to 1. Add the count value to the result and perform modulo on the result after the addition.

After looping through the entire string, return the result. This approach has a time complexity of O(n), where n is the length of the input string.


# Determine Whether Matrix Can Be Obtained By Rotation

- slug: determine-whether-matrix-can-be-obtained-by-rotation
- difficulty: Easy

Given two `n x n` binary matrices `mat` and `target`, return `true` _if it is possible to make_ `mat` _equal to_ `target` _by **rotating**_ `mat` _in **90-degree increments**, or_ `false` _otherwise._

**Example 1:**

**Input:** mat = \[\[0,1\],\[1,0\]\], target = \[\[1,0\],\[0,1\]\]
**Output:** true
**Explanation:** We can rotate mat 90 degrees clockwise to make mat equal target.

**Example 2:**

**Input:** mat = \[\[0,1\],\[1,1\]\], target = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** It is impossible to make mat equal to target by rotating mat.

**Example 3:**

**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\], target = \[\[1,1,1\],\[0,1,0\],\[0,0,0\]\]
**Output:** true
**Explanation:** We can rotate mat 90 degrees clockwise two times to make mat equal target.

**Constraints:**

*   `n == mat.length == target.length`
*   `n == mat[i].length == target[i].length`
*   `1 <= n <= 10`
*   `mat[i][j]` and `target[i][j]` are either `0` or `1`.

## A solution in Java

```java
import java.util.PriorityQueue;

public int minimumSize(int[] nums, int maxOperations) {
    PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
    for (int num : nums) {
        pq.offer(num);
    }
    while (maxOperations > 0) {
        int maxBalls = pq.poll();
        pq.offer(maxBalls / 2);
        pq.offer(maxBalls - (maxBalls / 2));
        maxOperations--;
    }
    return pq.peek();
}
```
The algorithm is based on using a priority queue (max heap) to store the number of balls in each bag. In each operation, we remove the largest (or maximum) number of balls from the queue, divide this number by 2, and push both divided parts back into the queue. This operation is performed for given `maxOperations` times, and then we return the maximum number of balls in the bag (i.e., the top of the max heap).

Since the priority queue maintains the order of elements, prioritizing the maximum number of balls, we can efficiently divide the balls in the largest bag in each operation, eventually minimizing the penalty after `maxOperations`.

## A solution in C++

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

int minimumSize(std::vector<int>& nums, int maxOperations) {
    std::priority_queue<int> pq(nums.begin(), nums.end());
    while (maxOperations > 0) {
        int maxBalls = pq.top();
        pq.pop();
        pq.push(maxBalls / 2);
        pq.push(maxBalls - (maxBalls / 2));
        maxOperations--;
    }
    return pq.top();
}
```
The algorithm is based on using a priority queue (max heap) to store the number of balls in each bag. In each operation, we remove the largest (or maximum) number of balls from the queue, divide this number by 2, and push both divided parts back into the queue. This operation is performed for given `maxOperations` times, and then we return the maximum number of balls in the bag (i.e., the top of the max heap).

Since the priority queue maintains the order of elements, prioritizing the maximum number of balls, we can efficiently divide the balls in the largest bag in each operation, eventually minimizing the penalty after `maxOperations`.

## A solution in Python

```python
import heapq

def minimumSize(nums, maxOperations):
    pq = [-num for num in nums] # Negative numbers to simulate max heap
    heapq.heapify(pq)
    while maxOperations > 0:
        maxBalls = -heapq.heappop(pq)
        heapq.heappush(pq, -maxBalls // 2)
        heapq.heappush(pq, -(maxBalls - (maxBalls // 2)))
        maxOperations -= 1
    return -pq[0]
```
The algorithm is based on using a priority queue (max heap) to store the number of balls in each bag. In each operation, we remove the largest (or maximum) number of balls from the queue, divide this number by 2, and push both divided parts back into the queue. This operation is performed for given `maxOperations` times, and then we return the maximum number of balls in the bag (i.e., the top of the max heap).

Since the priority queue maintains the order of elements, prioritizing the maximum number of balls, we can efficiently divide the balls in the largest bag in each operation, eventually minimizing the penalty after `maxOperations`.

## A solution in Javascript

```javascript
function minimumSize(nums, maxOperations) {
    const pq = new PriorityQueue((a, b) => b - a);
    for (const num of nums) {
        pq.offer(num);
    }
    while (maxOperations > 0) {
        const maxBalls = pq.poll();
        pq.offer(Math.floor(maxBalls / 2));
        pq.offer(maxBalls - Math.floor(maxBalls / 2));
        maxOperations--;
    }
    return pq.peek();
}

class PriorityQueue {
    constructor(comparator = (a, b) => a - b) {
        this._heap = [];
        this._comparator = comparator;
    }
    size() {
        return this._heap.length;
    }
    isEmpty() {
        return this.size() == 0;
    }
    peek() {
        return this._heap[0];
    }
    // Rest of the PriorityQueue implementation
}
```
The algorithm is based on using a priority queue (max heap) to store the number of balls in each bag. In each operation, we remove the largest (or maximum) number of balls from the queue, divide this number by 2, and push both divided parts back into the queue. This operation is performed for given `maxOperations` times, and then we return the maximum number of balls in the bag (i.e., the top of the max heap).

Since the priority queue maintains the order of elements, prioritizing the maximum number of balls, we can efficiently divide the balls in the largest bag in each operation, eventually minimizing the penalty after `maxOperations`.


# Reduction Operations to Make the Array Elements Equal

- slug: reduction-operations-to-make-the-array-elements-equal
- difficulty: Medium

Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:

1.  Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2.  Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`.
3.  Reduce `nums[i]` to `nextLargest`.

Return _the number of operations to make all elements in_ `nums` _equal_.

**Example 1:**

**Input:** nums = \[5,1,3\]
**Output:** 3
**Explanation:** It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\].

**Example 2:**

**Input:** nums = \[1,1,1\]
**Output:** 0
**Explanation:** All elements in nums are already equal.

**Example 3:**

**Input:** nums = \[1,1,2,2,3\]
**Output:** 4
**Explanation:** It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\].

**Constraints:**

*   `1 <= nums.length <= 5 * 104`
*   `1 <= nums[i] <= 5 * 104`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int minTrioDegree(int n, int[][] edges) {
        Map<Integer, Map<Integer, Boolean>> graph = new HashMap<>();
        int[] degree = new int[n + 1];

        for (int[] edge : edges) {
            graph.computeIfAbsent(edge[0], k -> new HashMap<>()).put(edge[1], true);
            graph.computeIfAbsent(edge[1], k -> new HashMap<>()).put(edge[0], true);
            degree[edge[0]]++;
            degree[edge[1]]++;
        }

        int minDegree = Integer.MAX_VALUE;
        for (int[] edge : edges) {
            int u = edge[0], v = edge[1];
            for (int w = 1; w <= n; ++w) {
                if (graph.get(u).get(w) != null && graph.get(v).get(w) != null) {
                    minDegree = Math.min(minDegree, degree[u] + degree[v] + degree[w] - 6);
                }
            }
        }

        return minDegree == Integer.MAX_VALUE ? -1 : minDegree;
    }
}
```
1. We first initialize the graph using an adjacency matrix or an adjacency list. We also initialize a degree counter for each node to store the degree of each node.
2. We then iterate through each edge in our graph.
3. For each edge (u, v), we iterate through all possible nodes i.e., 1 ≤ w ≤ n.
4. If nodes u, v, and w are all connected (meaning, u-w and v-w are also connected), we have a connected trio.
5. For this connected trio, we calculate the sum of the degrees of u, v, and w and subtract 6 (as there are 6 internal edges connecting u, v, and w in the connected trio). We then update the minimum degree if we get a smaller value.
6. After iterating through all edges and all possible nodes, if we haven't found any connected trios, we return -1; otherwise, we return the minimum degree found.

## A solution in C++

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

int minTrioDegree(int n, std::vector<std::vector<int>>& edges) {
    std::unordered_map<int, std::unordered_map<int, bool>> graph;
    std::vector<int> degree(n + 1, 0);

    for (auto& edge : edges) {
        graph[edge[0]][edge[1]] = graph[edge[1]][edge[0]] = true;
        degree[edge[0]]++;
        degree[edge[1]]++;
    }

    int minDegree = INT_MAX;
    for (auto& edge : edges) {
        int u = edge[0], v = edge[1];
        for (int w = 1; w <= n; ++w) {
            if (graph[u][w] && graph[v][w]) {
                minDegree = std::min(minDegree, degree[u] + degree[v] + degree[w] - 6);
            }
        }
    }

    return minDegree == INT_MAX ? -1 : minDegree;
}
```
1. We first initialize the graph using an adjacency matrix or an adjacency list. We also initialize a degree counter for each node to store the degree of each node.
2. We then iterate through each edge in our graph.
3. For each edge (u, v), we iterate through all possible nodes i.e., 1 ≤ w ≤ n.
4. If nodes u, v, and w are all connected (meaning, u-w and v-w are also connected), we have a connected trio.
5. For this connected trio, we calculate the sum of the degrees of u, v, and w and subtract 6 (as there are 6 internal edges connecting u, v, and w in the connected trio). We then update the minimum degree if we get a smaller value.
6. After iterating through all edges and all possible nodes, if we haven't found any connected trios, we return -1; otherwise, we return the minimum degree found.

## A solution in Python

```python
from collections import defaultdict

def min_trio_degree(n, edges):
    graph = defaultdict(dict)
    degree = [0] * (n + 1)

    for u, v in edges:
        graph[u][v] = graph[v][u] = True
        degree[u] += 1
        degree[v] += 1

    min_degree = float('inf')
    for u, v in edges:
        for w in range(1, n + 1):
            if graph[u].get(w) and graph[v].get(w):
                min_degree = min(min_degree, degree[u] + degree[v] + degree[w] - 6)

    return min_degree if min_degree != float('inf') else -1
```
1. We first initialize the graph using an adjacency matrix or an adjacency list. We also initialize a degree counter for each node to store the degree of each node.
2. We then iterate through each edge in our graph.
3. For each edge (u, v), we iterate through all possible nodes i.e., 1 ≤ w ≤ n.
4. If nodes u, v, and w are all connected (meaning, u-w and v-w are also connected), we have a connected trio.
5. For this connected trio, we calculate the sum of the degrees of u, v, and w and subtract 6 (as there are 6 internal edges connecting u, v, and w in the connected trio). We then update the minimum degree if we get a smaller value.
6. After iterating through all edges and all possible nodes, if we haven't found any connected trios, we return -1; otherwise, we return the minimum degree found.

## A solution in Javascript

```javascript
function minTrioDegree(n, edges) {
    const graph = {};
    const degree = new Array(n + 1).fill(0);

    for (const [u, v] of edges) {
        if (!graph[u]) graph[u] = {};
        if (!graph[v]) graph[v] = {};
        graph[u][v] = graph[v][u] = true;
        degree[u]++;
        degree[v]++;
    }

    let minDegree = Infinity;
    for (const [u, v] of edges) {
        for (let w = 1; w <= n; ++w) {
            if (graph[u][w] && graph[v][w]) {
                minDegree = Math.min(minDegree, degree[u] + degree[v] + degree[w] - 6);
            }
        }
    }

    return minDegree === Infinity ? -1 : minDegree;
}
```
1. We first initialize the graph using an adjacency matrix or an adjacency list. We also initialize a degree counter for each node to store the degree of each node.
2. We then iterate through each edge in our graph.
3. For each edge (u, v), we iterate through all possible nodes i.e., 1 ≤ w ≤ n.
4. If nodes u, v, and w are all connected (meaning, u-w and v-w are also connected), we have a connected trio.
5. For this connected trio, we calculate the sum of the degrees of u, v, and w and subtract 6 (as there are 6 internal edges connecting u, v, and w in the connected trio). We then update the minimum degree if we get a smaller value.
6. After iterating through all edges and all possible nodes, if we haven't found any connected trios, we return -1; otherwise, we return the minimum degree found.


# Minimum Number of Flips to Make the Binary String Alternating

- slug: minimum-number-of-flips-to-make-the-binary-string-alternating
- difficulty: Medium

You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:

*   **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
*   **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'0'` it becomes `'1'` and vice-versa.

Return _the **minimum** number of **type-2** operations you need to perform_ _such that_ `s` _becomes **alternating**._

The string is called **alternating** if no two adjacent characters are equal.

*   For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not.

**Example 1:**

**Input:** s =  "111000 "
**Output:** 2
**Explanation**: Use the first operation two times to make s =  "100011 ".
Then, use the second operation on the third and sixth elements to make s =  "101010 ".

**Example 2:**

**Input:** s =  "010 "
**Output:** 0
**Explanation**: The string is already alternating.

**Example 3:**

**Input:** s =  "1110 "
**Output:** 1
**Explanation**: Use the second operation on the second element to make s =  "1010 ".

**Constraints:**

*   `1 <= s.length <= 105`
*   `s[i]` is either `'0'` or `'1'`.

## A solution in Java

```java
public int nearestValidPoint(int x, int y, int[][] points) {
    int minDistance = Integer.MAX_VALUE;
    int minIndex = -1;

    for (int i = 0; i < points.length; i++) {
        if (x == points[i][0] || y == points[i][1]) {
            int distance = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]);
            if (distance < minDistance) {
                minDistance = distance;
                minIndex = i;
            }
        }
    }

    return minIndex;
}
```
The algorithm iterates through the array of points and checks, in each iteration, whether the point shares the same x-coordinate or the same y-coordinate with the given location. If it does, it calculates the Manhattan distance between the current point and the location. If this distance is smaller than the minimum distance found so far, the algorithm updates the minimum distance and the index of the point in the array.

In the end, if at least one valid point was found, the algorithm returns the index of the point with the smallest Manhattan distance. If no valid points were found, the algorithm returns -1.

## A solution in C++

```cpp
#include <vector>
#include <limits>

int nearestValidPoint(int x, int y, std::vector<std::vector<int>>& points) {
    int minDistance = std::numeric_limits<int>::max();
    int minIndex = -1;

    for (int i = 0; i < points.size(); ++i) {
        if (x == points[i][0] || y == points[i][1]) {
            int distance = std::abs(x - points[i][0]) + std::abs(y - points[i][1]);
            if (distance < minDistance) {
                minDistance = distance;
                minIndex = i;
            }
        }
    }

    return minIndex;
}
```
The algorithm iterates through the array of points and checks, in each iteration, whether the point shares the same x-coordinate or the same y-coordinate with the given location. If it does, it calculates the Manhattan distance between the current point and the location. If this distance is smaller than the minimum distance found so far, the algorithm updates the minimum distance and the index of the point in the array.

In the end, if at least one valid point was found, the algorithm returns the index of the point with the smallest Manhattan distance. If no valid points were found, the algorithm returns -1.

## A solution in Python

```python
def nearestValidPoint(x, y, points):
    min_distance = float('inf')
    min_index = -1

    for i, point in enumerate(points):
        if x == point[0] or y == point[1]:
            distance = abs(x - point[0]) + abs(y - point[1])
            if distance < min_distance:
                min_distance = distance
                min_index = i

    return min_index
```
The algorithm iterates through the array of points and checks, in each iteration, whether the point shares the same x-coordinate or the same y-coordinate with the given location. If it does, it calculates the Manhattan distance between the current point and the location. If this distance is smaller than the minimum distance found so far, the algorithm updates the minimum distance and the index of the point in the array.

In the end, if at least one valid point was found, the algorithm returns the index of the point with the smallest Manhattan distance. If no valid points were found, the algorithm returns -1.

## A solution in Javascript

```javascript
function nearestValidPoint(x, y, points) {
    let minDistance = Infinity;
    let minIndex = -1;

    for (let i = 0; i < points.length; i++) {
        if (x === points[i][0] || y === points[i][1]) {
            let distance = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]);
            if (distance < minDistance) {
                minDistance = distance;
                minIndex = i;
            }
        }
    }

    return minIndex;
}
```
The algorithm iterates through the array of points and checks, in each iteration, whether the point shares the same x-coordinate or the same y-coordinate with the given location. If it does, it calculates the Manhattan distance between the current point and the location. If this distance is smaller than the minimum distance found so far, the algorithm updates the minimum distance and the index of the point in the array.

In the end, if at least one valid point was found, the algorithm returns the index of the point with the smallest Manhattan distance. If no valid points were found, the algorithm returns -1.


# Minimum Space Wasted From Packaging

- slug: minimum-space-wasted-from-packaging
- difficulty: Hard

You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box.

The package sizes are given as an integer array `packages`, where `packages[i]` is the **size** of the `ith` package. The suppliers are given as a 2D integer array `boxes`, where `boxes[j]` is an array of **box sizes** that the `jth` supplier produces.

You want to choose a **single supplier** and use boxes from them such that the **total wasted space** is **minimized**. For each package in a box, we define the space **wasted** to be `size of the box - size of the package`. The **total wasted space** is the sum of the space wasted in **all** the boxes.

*   For example, if you have to fit packages with sizes `[2,3,5]` and the supplier offers boxes of sizes `[4,8]`, you can fit the packages of size-`2` and size-`3` into two boxes of size-`4` and the package with size-`5` into a box of size-`8`. This would result in a waste of `(4-2) + (4-3) + (8-5) = 6`.

Return _the **minimum total wasted space** by choosing the box supplier **optimally**, or_ `-1` _if it is **impossible** to fit all the packages inside boxes._ Since the answer may be **large**, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** packages = \[2,3,5\], boxes = \[\[4,8\],\[2,8\]\]
**Output:** 6
**Explanation**: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.
The total waste is (4-2) + (4-3) + (8-5) = 6.

**Example 2:**

**Input:** packages = \[2,3,5\], boxes = \[\[1,4\],\[2,3\],\[3,4\]\]
**Output:** -1
**Explanation:** There is no box that the package of size 5 can fit in.

**Example 3:**

**Input:** packages = \[3,5,8,10,11,12\], boxes = \[\[12\],\[11,9\],\[10,5,14\]\]
**Output:** 9
**Explanation:** It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.
The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.

**Constraints:**

*   `n == packages.length`
*   `m == boxes.length`
*   `1 <= n <= 105`
*   `1 <= m <= 105`
*   `1 <= packages[i] <= 105`
*   `1 <= boxes[j].length <= 105`
*   `1 <= boxes[j][k] <= 105`
*   `sum(boxes[j].length) <= 105`
*   The elements in `boxes[j]` are **distinct**.

## A solution in Java

```java
public boolean checkPowersOfThree(int n) {
    while (n > 0) {
        if (n % 3 == 2) return false;
        n /= 3;
    }
    return true;
}
```
The algorithm iteratively checks if it's possible to represent the given integer `n` as the sum of distinct powers of three. It does this by performing the following steps:
1. While `n` is greater than 0, perform steps 2 and 3.
2. If `n % 3` equals 2, return false. This means that the current integer cannot be represented as a distinct power of three since a power of 3 can only have a remainder of 0 or 1 when divided by 3.
3. Set `n` to `n / 3`, effectively testing the next power of 3.

If the function didn't return in step 2 during the loop, the given integer could be represented as the sum of distinct powers of three, and the function should return true.

## A solution in C++

```cpp
bool checkPowersOfThree(int n) {
    while (n > 0) {
        if (n % 3 == 2) return false;
        n /= 3;
    }
    return true;
}
```
The algorithm iteratively checks if it's possible to represent the given integer `n` as the sum of distinct powers of three. It does this by performing the following steps:
1. While `n` is greater than 0, perform steps 2 and 3.
2. If `n % 3` equals 2, return false. This means that the current integer cannot be represented as a distinct power of three since a power of 3 can only have a remainder of 0 or 1 when divided by 3.
3. Set `n` to `n / 3`, effectively testing the next power of 3.

If the function didn't return in step 2 during the loop, the given integer could be represented as the sum of distinct powers of three, and the function should return true.

## A solution in Python

```python
def check_powers_of_three(n: int) -> bool:
    while n > 0:
        if n % 3 == 2:
            return False
        n //= 3
    return True
```
The algorithm iteratively checks if it's possible to represent the given integer `n` as the sum of distinct powers of three. It does this by performing the following steps:
1. While `n` is greater than 0, perform steps 2 and 3.
2. If `n % 3` equals 2, return false. This means that the current integer cannot be represented as a distinct power of three since a power of 3 can only have a remainder of 0 or 1 when divided by 3.
3. Set `n` to `n / 3`, effectively testing the next power of 3.

If the function didn't return in step 2 during the loop, the given integer could be represented as the sum of distinct powers of three, and the function should return true.

## A solution in Javascript

```javascript
function checkPowersOfThree(n) {
    while (n > 0) {
        if (n % 3 === 2) return false;
        n = Math.floor(n / 3);
    }
    return true;
}
```
The algorithm iteratively checks if it's possible to represent the given integer `n` as the sum of distinct powers of three. It does this by performing the following steps:
1. While `n` is greater than 0, perform steps 2 and 3.
2. If `n % 3` equals 2, return false. This means that the current integer cannot be represented as a distinct power of three since a power of 3 can only have a remainder of 0 or 1 when divided by 3.
3. Set `n` to `n / 3`, effectively testing the next power of 3.

If the function didn't return in step 2 during the loop, the given integer could be represented as the sum of distinct powers of three, and the function should return true.


# Check if All the Integers in a Range Are Covered

- slug: check-if-all-the-integers-in-a-range-are-covered
- difficulty: Easy

You are given a 2D integer array `ranges` and two integers `left` and `right`. Each `ranges[i] = [starti, endi]` represents an **inclusive** interval between `starti` and `endi`.

Return `true` _if each integer in the inclusive range_ `[left, right]` _is covered by **at least one** interval in_ `ranges`. Return `false` _otherwise_.

An integer `x` is covered by an interval `ranges[i] = [starti, endi]` if `starti <= x <= endi`.

**Example 1:**

**Input:** ranges = \[\[1,2\],\[3,4\],\[5,6\]\], left = 2, right = 5
**Output:** true
**Explanation:** Every integer between 2 and 5 is covered:
- 2 is covered by the first range.
- 3 and 4 are covered by the second range.
- 5 is covered by the third range.

**Example 2:**

**Input:** ranges = \[\[1,10\],\[10,20\]\], left = 21, right = 21
**Output:** false
**Explanation:** 21 is not covered by any range.

**Constraints:**

*   `1 <= ranges.length <= 50`
*   `1 <= starti <= endi <= 50`
*   `1 <= left <= right <= 50`

## A solution in Java

```java
public boolean isCovered(int[][] ranges, int left, int right) {
    for (int i = left; i <= right; i++) {
        boolean found = false;
        for (int[] range : ranges) {
            if (i >= range[0] && i <= range[1]) {
                found = true;
                break;
            }
        }
        if (!found) return false;
    }
    return true;
}
```
The algorithm iterates through the inclusive range `[left, right]` and checks if each integer is covered by at least one interval. To accomplish this, it iterates through each interval in `ranges` and checks if the current integer is within an interval in `ranges`. If the integer is within an interval, the loop breaks, and the next integer will be checked. If an integer is not within any of the intervals, the function returns `false`. Otherwise, the function returns `true` after all integers have been checked.

## A solution in C++

```cpp
bool isCovered(vector<vector<int>>& ranges, int left, int right) {
    for (int i = left; i <= right; i++) {
        bool found = false;
        for (const auto& range : ranges) {
            if (i >= range[0] && i <= range[1]) {
                found = true;
                break;
            }
        }
        if (!found) return false;
    }
    return true;
}
```
The algorithm iterates through the inclusive range `[left, right]` and checks if each integer is covered by at least one interval. To accomplish this, it iterates through each interval in `ranges` and checks if the current integer is within an interval in `ranges`. If the integer is within an interval, the loop breaks, and the next integer will be checked. If an integer is not within any of the intervals, the function returns `false`. Otherwise, the function returns `true` after all integers have been checked.

## A solution in Python

```python
def isCovered(ranges: List[List[int]], left: int, right: int) -> bool:
    for i in range(left, right + 1):
        found = False
        for _range in ranges:
            if _range[0] <= i <= _range[1]:
                found = True
                break
        if not found:
            return False
    return True
```
The algorithm iterates through the inclusive range `[left, right]` and checks if each integer is covered by at least one interval. To accomplish this, it iterates through each interval in `ranges` and checks if the current integer is within an interval in `ranges`. If the integer is within an interval, the loop breaks, and the next integer will be checked. If an integer is not within any of the intervals, the function returns `false`. Otherwise, the function returns `true` after all integers have been checked.

## A solution in Javascript

```javascript
function isCovered(ranges, left, right) {
    for (let i = left; i <= right; i++) {
        let found = false;
        for (const range of ranges) {
            if (i >= range[0] && i <= range[1]) {
                found = true;
                break;
            }
        }
        if (!found) return false;
    }
    return true;
}
```
The algorithm iterates through the inclusive range `[left, right]` and checks if each integer is covered by at least one interval. To accomplish this, it iterates through each interval in `ranges` and checks if the current integer is within an interval in `ranges`. If the integer is within an interval, the loop breaks, and the next integer will be checked. If an integer is not within any of the intervals, the function returns `false`. Otherwise, the function returns `true` after all integers have been checked.


# Find the Student that Will Replace the Chalk

- slug: find-the-student-that-will-replace-the-chalk
- difficulty: Medium

There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student number `0` again.

You are given a **0-indexed** integer array `chalk` and an integer `k`. There are initially `k` pieces of chalk. When the student number `i` is given a problem to solve, they will use `chalk[i]` pieces of chalk to solve that problem. However, if the current number of chalk pieces is **strictly less** than `chalk[i]`, then the student number `i` will be asked to **replace** the chalk.

Return _the **index** of the student that will **replace** the chalk pieces_.

**Example 1:**

**Input:** chalk = \[5,1,5\], k = 22
**Output:** 0
**Explanation:** The students go in turns as follows:
- Student number 0 uses 5 chalk, so k = 17.
- Student number 1 uses 1 chalk, so k = 16.
- Student number 2 uses 5 chalk, so k = 11.
- Student number 0 uses 5 chalk, so k = 6.
- Student number 1 uses 1 chalk, so k = 5.
- Student number 2 uses 5 chalk, so k = 0.
Student number 0 does not have enough chalk, so they will have to replace it.

**Example 2:**

**Input:** chalk = \[3,4,1,2\], k = 25
**Output:** 1
**Explanation:** The students go in turns as follows:
- Student number 0 uses 3 chalk so k = 22.
- Student number 1 uses 4 chalk so k = 18.
- Student number 2 uses 1 chalk so k = 17.
- Student number 3 uses 2 chalk so k = 15.
- Student number 0 uses 3 chalk so k = 12.
- Student number 1 uses 4 chalk so k = 8.
- Student number 2 uses 1 chalk so k = 7.
- Student number 3 uses 2 chalk so k = 5.
- Student number 0 uses 3 chalk so k = 2.
Student number 1 does not have enough chalk, so they will have to replace it.

**Constraints:**

*   `chalk.length == n`
*   `1 <= n <= 105`
*   `1 <= chalk[i] <= 105`
*   `1 <= k <= 109`

## A solution in Java

```java
public String mergeAlternately(String word1, String word2) {
    StringBuilder merged = new StringBuilder();
    int i = 0, j = 0;
    while (i < word1.length() || j < word2.length()) {
        if (i < word1.length()) merged.append(word1.charAt(i++));
        if (j < word2.length()) merged.append(word2.charAt(j++));
    }
    return merged.toString();
}
```
The algorithm initializes two pointers, i and j, starting from 0. We will move through word1 with i and word2 with j. The merged string is initialized as an empty string or a list of characters, depending on the language.

In a while loop, we check if either i or j is still within its respective string length. Inside the loop, we first check if i is within the length of word1. If so, we append the character at position i in word1 to the merged string and increment i. Similarly, we check if j is within the length of word2. If so, we append the character at position j in word2 to the merged string and increment j.

After both i and j have reached the end of their respective strings, we return the merged string.

## A solution in C++

```cpp
#include <string>

std::string mergeAlternately(std::string word1, std::string word2) {
    std::string merged = "";
    int i = 0, j = 0;
    while (i < word1.size() || j < word2.size()) {
        if (i < word1.size()) merged += word1[i++];
        if (j < word2.size()) merged += word2[j++];
    }
    return merged;
}
```
The algorithm initializes two pointers, i and j, starting from 0. We will move through word1 with i and word2 with j. The merged string is initialized as an empty string or a list of characters, depending on the language.

In a while loop, we check if either i or j is still within its respective string length. Inside the loop, we first check if i is within the length of word1. If so, we append the character at position i in word1 to the merged string and increment i. Similarly, we check if j is within the length of word2. If so, we append the character at position j in word2 to the merged string and increment j.

After both i and j have reached the end of their respective strings, we return the merged string.

## A solution in Python

```python
def merge_alternately(word1, word2):
    merged = []
    i, j = 0, 0
    while i < len(word1) or j < len(word2):
        if i < len(word1):
            merged.append(word1[i])
            i += 1
        if j < len(word2):
            merged.append(word2[j])
            j += 1
    return "".join(merged)
```
The algorithm initializes two pointers, i and j, starting from 0. We will move through word1 with i and word2 with j. The merged string is initialized as an empty string or a list of characters, depending on the language.

In a while loop, we check if either i or j is still within its respective string length. Inside the loop, we first check if i is within the length of word1. If so, we append the character at position i in word1 to the merged string and increment i. Similarly, we check if j is within the length of word2. If so, we append the character at position j in word2 to the merged string and increment j.

After both i and j have reached the end of their respective strings, we return the merged string.

## A solution in Javascript

```javascript
function mergeAlternately(word1, word2) {
    let merged = "";
    let i = 0, j = 0;
    while (i < word1.length || j < word2.length) {
        if (i < word1.length) merged += word1[i++];
        if (j < word2.length) merged += word2[j++];
    }
    return merged;
}
```
The algorithm initializes two pointers, i and j, starting from 0. We will move through word1 with i and word2 with j. The merged string is initialized as an empty string or a list of characters, depending on the language.

In a while loop, we check if either i or j is still within its respective string length. Inside the loop, we first check if i is within the length of word1. If so, we append the character at position i in word1 to the merged string and increment i. Similarly, we check if j is within the length of word2. If so, we append the character at position j in word2 to the merged string and increment j.

After both i and j have reached the end of their respective strings, we return the merged string.