# Check if Every Row and Column Contains All Numbers

- slug: check-if-every-row-and-column-contains-all-numbers
- difficulty: Easy

An `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**).

Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`.

**Example 1:**

**Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\]
**Output:** true
**Explanation:** In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.
Hence, we return true.

**Example 2:**

**Input:** matrix = \[\[1,1,1\],\[1,2,3\],\[1,2,3\]\]
**Output:** false
**Explanation:** In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.
Hence, we return false.

**Constraints:**

*   `n == matrix.length == matrix[i].length`
*   `1 <= n <= 100`
*   `1 <= matrix[i][j] <= n`

## A solution in Java

```java
import java.util.List;

public int countPairs(List<String> nums, String target) {
    int count = 0;
    for (int i = 0; i < nums.size(); i++) {
        for (int j = i + 1; j < nums.size(); j++) {
            if (nums.get(i).concat(nums.get(j)).equals(target) || nums.get(j).concat(nums.get(i)).equals(target)) {
                count++;
            }
        }
    }
    return count;
}
```
The algorithm iterates through all possible pairs of indices i and j where `i != j` by using nested loops. For each pair, we check if the concatenation of `nums[i] + nums[j]` or `nums[j] + nums[i]` equals the `target`. If either condition is true, we increment the count. Finally, we return the count of such pairs. This solution has a complexity of O(n^2).

## A solution in C++

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

int countPairs(const std::vector<std::string>& nums, const std::string& target) {
    int count = 0;
    for (size_t i = 0; i < nums.size(); ++i) {
        for (size_t j = i + 1; j < nums.size(); ++j) {
            if (nums[i] + nums[j] == target || nums[j] + nums[i] == target) {
                ++count;
            }
        }
    }
    return count;
}
```
The algorithm iterates through all possible pairs of indices i and j where `i != j` by using nested loops. For each pair, we check if the concatenation of `nums[i] + nums[j]` or `nums[j] + nums[i]` equals the `target`. If either condition is true, we increment the count. Finally, we return the count of such pairs. This solution has a complexity of O(n^2).

## A solution in Python

```python
def count_pairs(nums, target):
    count = 0
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target or nums[j] + nums[i] == target:
                count += 1
    return count
```
The algorithm iterates through all possible pairs of indices i and j where `i != j` by using nested loops. For each pair, we check if the concatenation of `nums[i] + nums[j]` or `nums[j] + nums[i]` equals the `target`. If either condition is true, we increment the count. Finally, we return the count of such pairs. This solution has a complexity of O(n^2).

## A solution in Javascript

```javascript
function countPairs(nums, target) {
    let count = 0;
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target || nums[j] + nums[i] === target) {
                count++;
            }
        }
    }
    return count;
}
```
The algorithm iterates through all possible pairs of indices i and j where `i != j` by using nested loops. For each pair, we check if the concatenation of `nums[i] + nums[j]` or `nums[j] + nums[i]` equals the `target`. If either condition is true, we increment the count. Finally, we return the count of such pairs. This solution has a complexity of O(n^2).


# Minimum Swaps to Group All 1's Together II

- slug: minimum-swaps-to-group-all-1s-together-ii
- difficulty: Medium

A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them.

A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**.

Given a **binary** **circular** array `nums`, return _the minimum number of swaps required to group all_ `1`_'s present in the array together at **any location**_.

**Example 1:**

**Input:** nums = \[0,1,0,1,1,0,0\]
**Output:** 1
**Explanation:** Here are a few of the ways to group all the 1's together:
\[0,0,1,1,1,0,0\] using 1 swap.
\[0,1,1,1,0,0,0\] using 1 swap.
\[1,1,0,0,0,0,1\] using 2 swaps (using the circular property of the array).
There is no way to group all 1's together with 0 swaps.
Thus, the minimum number of swaps required is 1.

**Example 2:**

**Input:** nums = \[0,1,1,1,0,0,1,1,0\]
**Output:** 2
**Explanation:** Here are a few of the ways to group all the 1's together:
\[1,1,1,0,0,0,0,1,1\] using 2 swaps (using the circular property of the array).
\[1,1,1,1,1,0,0,0,0\] using 2 swaps.
There is no way to group all 1's together with 0 or 1 swaps.
Thus, the minimum number of swaps required is 2.

**Example 3:**

**Input:** nums = \[1,1,0,0,1\]
**Output:** 0
**Explanation:** All the 1's are already grouped together due to the circular property of the array.
Thus, the minimum number of swaps required is 0.

**Constraints:**

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

## A solution in Java

```java
public int maxConsecutiveAnswers(String answerKey, int k) {
    int n = answerKey.length();
    int start = 0, maxLen = 0, maxCount = 0;
    int[] count = new int[2];

    for (int end = 0; end < n; end++) {
        maxCount = Math.max(maxCount, ++count[answerKey.charAt(end) == 'T' ? 1 : 0]);

        if (end - start + 1 - maxCount > k) {
            count[answerKey.charAt(start) == 'T' ? 1 : 0]--;
            start++;
        }

        maxLen = Math.max(maxLen, end - start + 1);
    }

    return maxLen;
}
```
The algorithm uses a sliding window approach. We start with the left pointer `start` and the right pointer `end`, initially at position 0. For each element in the `answerKey`, we update the maximum count of consecutive 'T's or 'F's using the `count` dictionary. Then, we check if the current window size `(end - start + 1)` minus the maximum count of consecutive 'T's or 'F's is greater than `k`. If it is, we need to shrink the window from the left side by moving the `start` pointer to the right, adjusting the count for the removed character. Finally, we update the max length of consecutive 'T's or 'F's found so far using `maxLen`. When the loop is done, we return `maxLen`.

This algorithm ensures that we cost only O(n) time complexity as we process each character in the `answerKey` only once.

## A solution in C++

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

int maxConsecutiveAnswers(string answerKey, int k) {
    int n = answerKey.size();
    int start = 0, maxLen = 0, maxCount = 0;
    vector<int> count(2, 0);

    for (int end = 0; end < n; ++end) {
        maxCount = max(maxCount, ++count[answerKey[end] == 'T']);

        if (end - start + 1 - maxCount > k) {
            count[answerKey[start] == 'T']--;
            start++;
        }

        maxLen = max(maxLen, end - start + 1);
    }

    return maxLen;
}
```
The algorithm uses a sliding window approach. We start with the left pointer `start` and the right pointer `end`, initially at position 0. For each element in the `answerKey`, we update the maximum count of consecutive 'T's or 'F's using the `count` dictionary. Then, we check if the current window size `(end - start + 1)` minus the maximum count of consecutive 'T's or 'F's is greater than `k`. If it is, we need to shrink the window from the left side by moving the `start` pointer to the right, adjusting the count for the removed character. Finally, we update the max length of consecutive 'T's or 'F's found so far using `maxLen`. When the loop is done, we return `maxLen`.

This algorithm ensures that we cost only O(n) time complexity as we process each character in the `answerKey` only once.

## A solution in Python

```python
def max_consecutive_answers(answer_key: str, k: int) -> int:
    n = len(answer_key)
    start, max_len, max_count = 0, 0, 0
    count = {'T': 0, 'F': 0}

    for end in range(n):
        max_count = max(max_count, count.__setitem__(answer_key[end], count[answer_key[end]] + 1))

        if end - start + 1 - max_count > k:
            count[answer_key[start]] -= 1
            start += 1

        max_len = max(max_len, end - start + 1)

    return max_len
```
The algorithm uses a sliding window approach. We start with the left pointer `start` and the right pointer `end`, initially at position 0. For each element in the `answerKey`, we update the maximum count of consecutive 'T's or 'F's using the `count` dictionary. Then, we check if the current window size `(end - start + 1)` minus the maximum count of consecutive 'T's or 'F's is greater than `k`. If it is, we need to shrink the window from the left side by moving the `start` pointer to the right, adjusting the count for the removed character. Finally, we update the max length of consecutive 'T's or 'F's found so far using `maxLen`. When the loop is done, we return `maxLen`.

This algorithm ensures that we cost only O(n) time complexity as we process each character in the `answerKey` only once.

## A solution in Javascript

```javascript
function maxConsecutiveAnswers(answerKey, k) {
    const n = answerKey.length;
    let start = 0, maxLen = 0, maxCount = 0;
    let count = {'T': 0, 'F': 0};

    for (let end = 0; end < n; end++) {
        maxCount = Math.max(maxCount, count[answerKey[end]] += 1);

        if (end - start + 1 - maxCount > k) {
            count[answerKey[start]] -= 1;
            start++;
        }

        maxLen = Math.max(maxLen, end - start + 1);
    }

    return maxLen;
}
```
The algorithm uses a sliding window approach. We start with the left pointer `start` and the right pointer `end`, initially at position 0. For each element in the `answerKey`, we update the maximum count of consecutive 'T's or 'F's using the `count` dictionary. Then, we check if the current window size `(end - start + 1)` minus the maximum count of consecutive 'T's or 'F's is greater than `k`. If it is, we need to shrink the window from the left side by moving the `start` pointer to the right, adjusting the count for the removed character. Finally, we update the max length of consecutive 'T's or 'F's found so far using `maxLen`. When the loop is done, we return `maxLen`.

This algorithm ensures that we cost only O(n) time complexity as we process each character in the `answerKey` only once.


# Count Words Obtained After Adding a Letter

- slug: count-words-obtained-after-adding-a-letter
- difficulty: Medium

You are given two **0-indexed** arrays of strings `startWords` and `targetWords`. Each string consists of **lowercase English letters** only.

For each string in `targetWords`, check if it is possible to choose a string from `startWords` and perform a **conversion operation** on it to be equal to that from `targetWords`.

The **conversion operation** is described in the following two steps:

1.  **Append** any lowercase letter that is **not present** in the string to its end.
    *   For example, if the string is `"abc "`, the letters `'d'`, `'e'`, or `'y'` can be added to it, but not `'a'`. If `'d'` is added, the resulting string will be `"abcd "`.
2.  **Rearrange** the letters of the new string in **any** arbitrary order.
    *   For example, `"abcd "` can be rearranged to `"acbd "`, `"bacd "`, `"cbda "`, and so on. Note that it can also be rearranged to `"abcd "` itself.

Return _the **number of strings** in_ `targetWords` _that can be obtained by performing the operations on **any** string of_ `startWords`.

**Note** that you will only be verifying if the string in `targetWords` can be obtained from a string in `startWords` by performing the operations. The strings in `startWords` **do not** actually change during this process.

**Example 1:**

**Input:** startWords = \[ "ant ", "act ", "tack "\], targetWords = \[ "tack ", "act ", "acti "\]
**Output:** 2
**Explanation:**
- In order to form targetWords\[0\] =  "tack ", we use startWords\[1\] =  "act ", append 'k' to it, and rearrange  "actk " to  "tack ".
- There is no string in startWords that can be used to obtain targetWords\[1\] =  "act ".
  Note that  "act " does exist in startWords, but we **must** append one letter to the string before rearranging it.
- In order to form targetWords\[2\] =  "acti ", we use startWords\[1\] =  "act ", append 'i' to it, and rearrange  "acti " to  "acti " itself.

**Example 2:**

**Input:** startWords = \[ "ab ", "a "\], targetWords = \[ "abc ", "abcd "\]
**Output:** 1
**Explanation:**
- In order to form targetWords\[0\] =  "abc ", we use startWords\[0\] =  "ab ", add 'c' to it, and rearrange it to  "abc ".
- There is no string in startWords that can be used to obtain targetWords\[1\] =  "abcd ".

**Constraints:**

*   `1 <= startWords.length, targetWords.length <= 5 * 104`
*   `1 <= startWords[i].length, targetWords[j].length <= 26`
*   Each string of `startWords` and `targetWords` consists of lowercase English letters only.
*   No letter occurs more than once in any string of `startWords` or `targetWords`.

## A solution in Java

```java
public int numOfWays(int[] nums, int k) {
    int count = 0, left = 0, right = 0;
    for (int i = 0; i < nums.length; ++i) {
        if (nums[i] < k) ++left;
        if (nums[i] <= k) ++right;
    }

    if (left == nums.length) return 0;
    if (right - left != nums.length - right) return left + 1;
    return left;
}
```
The algorithm iterates through the given nums array and counts the number of elements that are smaller than k (`left`) and the number of elements that are lesser or equal to k (`right`). There are three cases to handle, as follows:

1. If all the elements in the nums array are smaller than k, the function returns 0 as there is no valid pivot index.
2. If there is an imbalance in partition lengths (i.e., `right - left != n - right`), return `left + 1` as a new partition has been created by modifying an element.
3. If the partitions are balanced, return left for the previous valid pivot index.

By using this approach, the function determines the maximum possible number of ways to partition the nums array to satisfy both conditions after changing at most one element.

## A solution in C++

```cpp
int numOfWays(int nums[], int n, int k) {
    int count = 0, left = 0, right = 0;
    for (int i = 0; i < n; ++i) {
        if (nums[i] < k) ++left;
        if (nums[i] <= k) ++right;
    }

    if (left == n) return 0;
    if (right - left != n - right) return left + 1;
    return left;
}
```
The algorithm iterates through the given nums array and counts the number of elements that are smaller than k (`left`) and the number of elements that are lesser or equal to k (`right`). There are three cases to handle, as follows:

1. If all the elements in the nums array are smaller than k, the function returns 0 as there is no valid pivot index.
2. If there is an imbalance in partition lengths (i.e., `right - left != n - right`), return `left + 1` as a new partition has been created by modifying an element.
3. If the partitions are balanced, return left for the previous valid pivot index.

By using this approach, the function determines the maximum possible number of ways to partition the nums array to satisfy both conditions after changing at most one element.

## A solution in Python

```python
def numOfWays(nums, k):
    left = 0
    right = 0
    for num in nums:
        if num < k:
            left += 1
        if num <= k:
            right += 1

    if left == len(nums):
        return 0
    if right - left != len(nums) - right:
        return left + 1
    return left
```
The algorithm iterates through the given nums array and counts the number of elements that are smaller than k (`left`) and the number of elements that are lesser or equal to k (`right`). There are three cases to handle, as follows:

1. If all the elements in the nums array are smaller than k, the function returns 0 as there is no valid pivot index.
2. If there is an imbalance in partition lengths (i.e., `right - left != n - right`), return `left + 1` as a new partition has been created by modifying an element.
3. If the partitions are balanced, return left for the previous valid pivot index.

By using this approach, the function determines the maximum possible number of ways to partition the nums array to satisfy both conditions after changing at most one element.

## A solution in Javascript

```javascript
function numOfWays(nums, k) {
    let count = 0, left = 0, right = 0;
    for (let i = 0; i < nums.length; ++i) {
        if (nums[i] < k) ++left;
        if (nums[i] <= k) ++right;
    }

    if (left == nums.length) return 0;
    if (right - left != nums.length - right) return left + 1;
    return left;
}
```
The algorithm iterates through the given nums array and counts the number of elements that are smaller than k (`left`) and the number of elements that are lesser or equal to k (`right`). There are three cases to handle, as follows:

1. If all the elements in the nums array are smaller than k, the function returns 0 as there is no valid pivot index.
2. If there is an imbalance in partition lengths (i.e., `right - left != n - right`), return `left + 1` as a new partition has been created by modifying an element.
3. If the partitions are balanced, return left for the previous valid pivot index.

By using this approach, the function determines the maximum possible number of ways to partition the nums array to satisfy both conditions after changing at most one element.


# Earliest Possible Day of Full Bloom

- slug: earliest-possible-day-of-full-bloom
- difficulty: Hard

You have `n` flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two **0-indexed** integer arrays `plantTime` and `growTime`, of length `n` each:

*   `plantTime[i]` is the number of **full days** it takes you to **plant** the `ith` seed. Every day, you can work on planting exactly one seed. You **do not** have to work on planting the same seed on consecutive days, but the planting of a seed is not complete **until** you have worked `plantTime[i]` days on planting it in total.
*   `growTime[i]` is the number of **full days** it takes the `ith` seed to grow after being completely planted. **After** the last day of its growth, the flower **blooms** and stays bloomed forever.

From the beginning of day `0`, you can plant the seeds in **any** order.

Return _the **earliest** possible day where **all** seeds are blooming_.

**Example 1:**

**Input:** plantTime = \[1,4,3\], growTime = \[2,3,1\]
**Output:** 9
**Explanation:** The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.
One optimal way is:
On day 0, plant the 0th seed. The seed grows for 2 full days and blooms on day 3.
On days 1, 2, 3, and 4, plant the 1st seed. The seed grows for 3 full days and blooms on day 8.
On days 5, 6, and 7, plant the 2nd seed. The seed grows for 1 full day and blooms on day 9.
Thus, on day 9, all the seeds are blooming.

**Example 2:**

**Input:** plantTime = \[1,2,3,2\], growTime = \[2,1,2,1\]
**Output:** 9
**Explanation:** The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.
One optimal way is:
On day 1, plant the 0th seed. The seed grows for 2 full days and blooms on day 4.
On days 0 and 3, plant the 1st seed. The seed grows for 1 full day and blooms on day 5.
On days 2, 4, and 5, plant the 2nd seed. The seed grows for 2 full days and blooms on day 8.
On days 6 and 7, plant the 3rd seed. The seed grows for 1 full day and blooms on day 9.
Thus, on day 9, all the seeds are blooming.

**Example 3:**

**Input:** plantTime = \[1\], growTime = \[1\]
**Output:** 2
**Explanation:** On day 0, plant the 0th seed. The seed grows for 1 full day and blooms on day 2.
Thus, on day 2, all the seeds are blooming.

**Constraints:**

*   `n == plantTime.length == growTime.length`
*   `1 <= n <= 105`
*   `1 <= plantTime[i], growTime[i] <= 104`

## A solution in Java

```java
public int earliestBlooms(int[] plantTime, int[] growTime) {
    int n = plantTime.length;
    int[][] processTime = new int[n][2];
    for (int i = 0; i < n; ++i) {
        processTime[i][0] = plantTime[i];
        processTime[i][1] = growTime[i];
    }
    Arrays.sort(processTime, (a, b) -> a[0] - b[0]);

    int day = 0;
    int blooms = 0;
    for (int[] p : processTime) {
        day += p[0];
        blooms = Math.max(blooms, day + p[1]);
    }
    return blooms;
}
```
1. Create a new list/array, `processTime`, containing pairs/tuples of (plantTime, growTime) for each seed.
2. Sort `processTime` in ascending order based on plantTime.
3. Iterate through the sorted `processTime` pairs/tuples. For each pair/tuple, increment the `day` counter by the plantTime, and compare the sum of `day` and growTime with the current `blooms` value. If the sum is greater, update `blooms` with the new value.
4. Return the final `blooms` value as the earliest day when all seeds have bloomed.

## A solution in C++

```cpp
int earliestBlooms(vector<int>& plantTime, vector<int>& growTime) {
    int n = plantTime.size();
    vector<pair<int, int>> processTime;
    for (int i = 0; i < n; ++i) {
        processTime.push_back({plantTime[i], growTime[i]});
    }
    sort(processTime.begin(), processTime.end());

    int day = 0;
    int blooms = 0;
    for (auto& p : processTime) {
        day += p.first;
        blooms = max(blooms, day + p.second);
    }
    return blooms;
}
```
1. Create a new list/array, `processTime`, containing pairs/tuples of (plantTime, growTime) for each seed.
2. Sort `processTime` in ascending order based on plantTime.
3. Iterate through the sorted `processTime` pairs/tuples. For each pair/tuple, increment the `day` counter by the plantTime, and compare the sum of `day` and growTime with the current `blooms` value. If the sum is greater, update `blooms` with the new value.
4. Return the final `blooms` value as the earliest day when all seeds have bloomed.

## A solution in Python

```python
def earliestBlooms(plantTime, growTime):
    n = len(plantTime)
    processTime = list(zip(plantTime, growTime))
    processTime.sort()

    day = 0
    blooms = 0
    for p in processTime:
        day += p[0]
        blooms = max(blooms, day + p[1])
    return blooms
```
1. Create a new list/array, `processTime`, containing pairs/tuples of (plantTime, growTime) for each seed.
2. Sort `processTime` in ascending order based on plantTime.
3. Iterate through the sorted `processTime` pairs/tuples. For each pair/tuple, increment the `day` counter by the plantTime, and compare the sum of `day` and growTime with the current `blooms` value. If the sum is greater, update `blooms` with the new value.
4. Return the final `blooms` value as the earliest day when all seeds have bloomed.

## A solution in Javascript

```javascript
function earliestBlooms(plantTime, growTime) {
    let n = plantTime.length;
    let processTime = plantTime.map((val, i) => ([val, growTime[i]]));
    processTime.sort((a, b) => a[0] - b[0]);

    let day = 0;
    let blooms = 0;
    for (let p of processTime) {
        day += p[0];
        blooms = Math.max(blooms, day + p[1]);
    }
    return blooms;
}
```
1. Create a new list/array, `processTime`, containing pairs/tuples of (plantTime, growTime) for each seed.
2. Sort `processTime` in ascending order based on plantTime.
3. Iterate through the sorted `processTime` pairs/tuples. For each pair/tuple, increment the `day` counter by the plantTime, and compare the sum of `day` and growTime with the current `blooms` value. If the sum is greater, update `blooms` with the new value.
4. Return the final `blooms` value as the earliest day when all seeds have bloomed.


# Pour Water Between Buckets to Make Water Levels Equal

- slug: pour-water-between-buckets-to-make-water-levels-equal
- difficulty: Medium

You have `n` buckets each containing some gallons of water in it, represented by a **0-indexed** integer array `buckets`, where the `ith` bucket contains `buckets[i]` gallons of water. You are also given an integer `loss`.

You want to make the amount of water in each bucket equal. You can pour any amount of water from one bucket to another bucket (not necessarily an integer). However, every time you pour `k` gallons of water, you spill `loss` **percent** of `k`.

Return _the **maximum** amount of water in each bucket after making the amount of water equal._ Answers within `10-5` of the actual answer will be accepted.

**Example 1:**

**Input:** buckets = \[1,2,7\], loss = 80
**Output:** 2.00000
**Explanation:** Pour 5 gallons of water from buckets\[2\] to buckets\[0\].
5 \* 80% = 4 gallons are spilled and buckets\[0\] only receives 5 - 4 = 1 gallon of water.
All buckets have 2 gallons of water in them so return 2.

**Example 2:**

**Input:** buckets = \[2,4,6\], loss = 50
**Output:** 3.50000
**Explanation:** Pour 0.5 gallons of water from buckets\[1\] to buckets\[0\].
0.5 \* 50% = 0.25 gallons are spilled and buckets\[0\] only receives 0.5 - 0.25 = 0.25 gallons of water.
Now, buckets = \[2.25, 3.5, 6\].
Pour 2.5 gallons of water from buckets\[2\] to buckets\[0\].
2.5 \* 50% = 1.25 gallons are spilled and buckets\[0\] only receives 2.5 - 1.25 = 1.25 gallons of water.
All buckets have 3.5 gallons of water in them so return 3.5.

**Example 3:**

**Input:** buckets = \[3,3,3,3\], loss = 40
**Output:** 3.00000
**Explanation:** All buckets already have the same amount of water in them.

**Constraints:**

*   `1 <= buckets.length <= 105`
*   `0 <= buckets[i] <= 105`
*   `0 <= loss <= 99`

## A solution in Java

```java
public int performOperations(String[] operations) {
    int X = 0;
    for (String op : operations) {
        if (op.equals("++X") || op.equals("X++")) {
            X++;
        } else if (op.equals("--X") || op.equals("X--")) {
            X--;
        }
    }
    return X;
}
```
We initialize the variable `X` to 0. Then, we loop through the given list of operations. If an operation is either "++X" or "X++", we increment the value of `X`. If an operation is either "--X" or "X--", we decrement the value of `X`. At the end of the loop, we return the final value of `X`. The implementation in each language is very similar, with only small differences in syntax.

## A solution in C++

```cpp
int performOperations(vector<string>& operations) {
    int X = 0;
    for (auto& op : operations) {
        if (op == "++X" || op == "X++") {
            X++;
        } else if (op == "--X" || op == "X--") {
            X--;
        }
    }
    return X;
}
```
We initialize the variable `X` to 0. Then, we loop through the given list of operations. If an operation is either "++X" or "X++", we increment the value of `X`. If an operation is either "--X" or "X--", we decrement the value of `X`. At the end of the loop, we return the final value of `X`. The implementation in each language is very similar, with only small differences in syntax.

## A solution in Python

```python
def perform_operations(operations):
    X = 0
    for op in operations:
        if op == "++X" or op == "X++":
            X += 1
        elif op == "--X" or op == "X--":
            X -= 1
    return X
```
We initialize the variable `X` to 0. Then, we loop through the given list of operations. If an operation is either "++X" or "X++", we increment the value of `X`. If an operation is either "--X" or "X--", we decrement the value of `X`. At the end of the loop, we return the final value of `X`. The implementation in each language is very similar, with only small differences in syntax.

## A solution in Javascript

```javascript
function performOperations(operations) {
    let X = 0;
    for (let op of operations) {
        if (op === "++X" || op === "X++") {
            X++;
        } else if (op === "--X" || op === "X--") {
            X--;
        }
    }
    return X;
}
```
We initialize the variable `X` to 0. Then, we loop through the given list of operations. If an operation is either "++X" or "X++", we increment the value of `X`. If an operation is either "--X" or "X--", we decrement the value of `X`. At the end of the loop, we return the final value of `X`. The implementation in each language is very similar, with only small differences in syntax.


# Divide a String Into Groups of Size k

- slug: divide-a-string-into-groups-of-size-k
- difficulty: Easy

A string `s` can be partitioned into groups of size `k` using the following procedure:

*   The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group.
*   For the last group, if the string **does not** have `k` characters remaining, a character `fill` is used to complete the group.

Note that the partition is done so that after removing the `fill` character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be `s`.

Given the string `s`, the size of each group `k` and the character `fill`, return _a string array denoting the **composition of every group**_ `s` _has been divided into, using the above procedure_.

**Example 1:**

**Input:** s =  "abcdefghi ", k = 3, fill =  "x "
**Output:** \[ "abc ", "def ", "ghi "\]
**Explanation:**
The first 3 characters  "abc " form the first group.
The next 3 characters  "def " form the second group.
The last 3 characters  "ghi " form the third group.
Since all groups can be completely filled by characters from the string, we do not need to use fill.
Thus, the groups formed are  "abc ",  "def ", and  "ghi ".

**Example 2:**

**Input:** s =  "abcdefghij ", k = 3, fill =  "x "
**Output:** \[ "abc ", "def ", "ghi ", "jxx "\]
**Explanation:**
Similar to the previous example, we are forming the first three groups  "abc ",  "def ", and  "ghi ".
For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.
Thus, the 4 groups formed are  "abc ",  "def ",  "ghi ", and  "jxx ".

**Constraints:**

*   `1 <= s.length <= 100`
*   `s` consists of lowercase English letters only.
*   `1 <= k <= 100`
*   `fill` is a lowercase English letter.

## A solution in Java

```java
public int sumOfBeauties(int[] nums) {
    int n = nums.length;
    int result = 0;

    int[] leftMax = new int[n];
    leftMax[0] = nums[0];
    int[] rightMin = new int[n];
    rightMin[n - 1] = nums[n - 1];

    for (int i = 1; i < n; i++) {
        leftMax[i] = Math.max(leftMax[i - 1], nums[i]);
    }

    for (int i = n - 2; i >= 0; i--) {
        rightMin[i] = Math.min(rightMin[i + 1], nums[i]);
    }

    for (int i = 1; i <= n - 2; i++) {
        if (nums[i] > leftMax[i - 1] && nums[i] < rightMin[i + 1]) {
            result += 1;
        }
    }

    return result;
}
```
To solve this problem, we first create two arrays, `leftMax` and `rightMin`. `leftMax` stores the maximum value to the left of each index i, and `rightMin` stores the minimum value to the right of each index i. We then iterate through the input array `nums` from index 1 to index n - 2 (inclusive) and check if the current value is greater than the maximum to its left and less than the minimum to its right. If both conditions are fulfilled, we increase the result by 1. Finally, we return the result as the sum of the beauty of all `nums[i]` where 1 <= i <= nums.length - 2.

## A solution in C++

```cpp
int sumOfBeauties(std::vector<int>& nums) {
    int n = nums.size();
    int result = 0;

    std::vector<int> leftMax(n);
    leftMax[0] = nums[0];
    std::vector<int> rightMin(n);
    rightMin[n - 1] = nums[n - 1];

    for (int i = 1; i < n; i++) {
        leftMax[i] = std::max(leftMax[i - 1], nums[i]);
    }

    for (int i = n - 2; i >= 0; i--) {
        rightMin[i] = std::min(rightMin[i + 1], nums[i]);
    }

    for (int i = 1; i <= n - 2; i++) {
        if (nums[i] > leftMax[i - 1] && nums[i] < rightMin[i + 1]) {
            result += 1;
        }
    }

    return result;
}
```
To solve this problem, we first create two arrays, `leftMax` and `rightMin`. `leftMax` stores the maximum value to the left of each index i, and `rightMin` stores the minimum value to the right of each index i. We then iterate through the input array `nums` from index 1 to index n - 2 (inclusive) and check if the current value is greater than the maximum to its left and less than the minimum to its right. If both conditions are fulfilled, we increase the result by 1. Finally, we return the result as the sum of the beauty of all `nums[i]` where 1 <= i <= nums.length - 2.

## A solution in Python

```python
def sum_of_beauties(nums: List[int]) -> int:
    n = len(nums)
    result = 0

    left_max = [0] * n
    left_max[0] = nums[0]
    right_min = [0] * n
    right_min[n - 1] = nums[n - 1]

    for i in range(1, n):
        left_max[i] = max(left_max[i - 1], nums[i])

    for i in range(n - 2, -1, -1):
        right_min[i] = min(right_min[i + 1], nums[i])

    for i in range(1, n - 1):
        if nums[i] > left_max[i - 1] and nums[i] < right_min[i + 1]:
            result += 1

    return result
```
To solve this problem, we first create two arrays, `leftMax` and `rightMin`. `leftMax` stores the maximum value to the left of each index i, and `rightMin` stores the minimum value to the right of each index i. We then iterate through the input array `nums` from index 1 to index n - 2 (inclusive) and check if the current value is greater than the maximum to its left and less than the minimum to its right. If both conditions are fulfilled, we increase the result by 1. Finally, we return the result as the sum of the beauty of all `nums[i]` where 1 <= i <= nums.length - 2.

## A solution in Javascript

```javascript
function sumOfBeauties(nums) {
    const n = nums.length;
    let result = 0;

    const leftMax = new Array(n);
    leftMax[0] = nums[0];
    const rightMin = new Array(n);
    rightMin[n - 1] = nums[n - 1];

    for (let i = 1; i < n; i++) {
        leftMax[i] = Math.max(leftMax[i - 1], nums[i]);
    }

    for (let i = n - 2; i >= 0; i--) {
        rightMin[i] = Math.min(rightMin[i + 1], nums[i]);
    }

    for (let i = 1; i <= n - 2; i++) {
        if (nums[i] > leftMax[i - 1] && nums[i] < rightMin[i + 1]) {
            result += 1;
        }
    }

    return result;
}
```
To solve this problem, we first create two arrays, `leftMax` and `rightMin`. `leftMax` stores the maximum value to the left of each index i, and `rightMin` stores the minimum value to the right of each index i. We then iterate through the input array `nums` from index 1 to index n - 2 (inclusive) and check if the current value is greater than the maximum to its left and less than the minimum to its right. If both conditions are fulfilled, we increase the result by 1. Finally, we return the result as the sum of the beauty of all `nums[i]` where 1 <= i <= nums.length - 2.


# Minimum Moves to Reach Target Score

- slug: minimum-moves-to-reach-target-score
- difficulty: Medium

You are playing a game with integers. You start with the integer `1` and you want to reach the integer `target`.

In one move, you can either:

*   **Increment** the current integer by one (i.e., `x = x + 1`).
*   **Double** the current integer (i.e., `x = 2 * x`).

You can use the **increment** operation **any** number of times, however, you can only use the **double** operation **at most** `maxDoubles` times.

Given the two integers `target` and `maxDoubles`, return _the minimum number of moves needed to reach_ `target` _starting with_ `1`.

**Example 1:**

**Input:** target = 5, maxDoubles = 0
**Output:** 4
**Explanation:** Keep incrementing by 1 until you reach target.

**Example 2:**

**Input:** target = 19, maxDoubles = 2
**Output:** 7
**Explanation:** Initially, x = 1
Increment 3 times so x = 4
Double once so x = 8
Increment once so x = 9
Double again so x = 18
Increment once so x = 19

**Example 3:**

**Input:** target = 10, maxDoubles = 4
**Output:** 4
**Explanation:** Initially, x = 1
Increment once so x = 2
Double once so x = 4
Increment once so x = 5
Double again so x = 10

**Constraints:**

*   `1 <= target <= 109`
*   `0 <= maxDoubles <= 100`

## A solution in Java

```java
import java.util.*;

class DetectSquares {
    Map<Integer, Map<Integer, Integer>> points;

    public DetectSquares() {
        points = new HashMap<>();
    }

    public void add(int[] point) {
        points.computeIfAbsent(point[0], k -> new HashMap<>()).put(point[1], points.get(point[0]).getOrDefault(point[1], 0) + 1);
    }

    public int count(int[] point) {
        int ans = 0;
        for (int x2 : points.keySet()) {
            if (!points.get(point[0]).containsKey(x2) || x2 == point[1]) continue;
            for (int y2 : points.get(x2).keySet()) {
                if (y2 == point[0] || Math.abs(x2 - point[1]) != Math.abs(y2 - point[0])) continue;
                ans += points.get(point[0]).get(x2) * points.get(x2).get(y2) * points.get(point[0]).getOrDefault(y2, 0);
            }
        }
        return ans;
    }
}
```
The algorithm we are using here is based on coordinate geometry. When we add new points, we use a dictionary or hashmap to store the frequency of each point added.

To detect squares, we iterate over all the sides of the potential square formed by the given two points. For each pair of points with x1, x2, y1, and y2 coordinates, we first check if they do not form correct sides; if so, we just need to continue to the next pair. If our conditions are met, the square formed by the pair is a valid square.

We then just calculate the result or count by multiplying the occurrence count of the points accordingly.

The worst-case time complexity will be O(max(m, n)²), where m is the number of points having the same x values and n is the number of points having the same y values.

## A solution in C++

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

class DetectSquares {
public:
    unordered_map<int, unordered_map<int, int>> points;

    DetectSquares() {

    }

    void add(vector<int> point) {
        points[point[0]][point[1]]++;
    }

    int count(vector<int> point) {
        int ans = 0;
        for (const auto &it1 : points[point[0]]) {
            if (it1.first == point[1]) continue;
            for (const auto &it2 : points[it1.first]) {
                if (it2.first == point[1] || abs(it1.first - point[1]) != abs(it2.first - point[0])) continue;
                ans += it1.second * it2.second * points[point[0]][it2.first];
            }
        }
        return ans;
    }
};
```
The algorithm we are using here is based on coordinate geometry. When we add new points, we use a dictionary or hashmap to store the frequency of each point added.

To detect squares, we iterate over all the sides of the potential square formed by the given two points. For each pair of points with x1, x2, y1, and y2 coordinates, we first check if they do not form correct sides; if so, we just need to continue to the next pair. If our conditions are met, the square formed by the pair is a valid square.

We then just calculate the result or count by multiplying the occurrence count of the points accordingly.

The worst-case time complexity will be O(max(m, n)²), where m is the number of points having the same x values and n is the number of points having the same y values.

## A solution in Python

```python
class DetectSquares:

    def __init__(self):
        self.points = collections.defaultdict(lambda: collections.defaultdict(int))

    def add(self, point):
        self.points[point[0]][point[1]] += 1

    def count(self, point):
        ans = 0
        for x2 in self.points[point[0]]:
            if x2 == point[1]:
                continue
            for y2 in self.points[x2]:
                if y2 == point[1] or abs(x2 - point[1]) != abs(y2 - point[0]):
                    continue
                ans += self.points[point[0]][x2] * self.points[x2][y2] * self.points[point[0]][y2]
        return ans
```
The algorithm we are using here is based on coordinate geometry. When we add new points, we use a dictionary or hashmap to store the frequency of each point added.

To detect squares, we iterate over all the sides of the potential square formed by the given two points. For each pair of points with x1, x2, y1, and y2 coordinates, we first check if they do not form correct sides; if so, we just need to continue to the next pair. If our conditions are met, the square formed by the pair is a valid square.

We then just calculate the result or count by multiplying the occurrence count of the points accordingly.

The worst-case time complexity will be O(max(m, n)²), where m is the number of points having the same x values and n is the number of points having the same y values.

## A solution in Javascript

```javascript
class DetectSquares {
    constructor() {
        this.points = new Map();
    }

    add(point) {
        if (!this.points.has(point[0])) {
            this.points.set(point[0], new Map());
        }
        const currPoint = this.points.get(point[0]);
        currPoint.set(point[1], (currPoint.get(point[1]) || 0) + 1);
    }

    count(point) {
        let ans = 0;
        if (!this.points.has(point[0])) return ans;
        for (const [x2, countX2] of this.points.get(point[0])) {
            if (x2 === point[1]) continue;
            for (const [y2, countY2] of this.points.get(x2)) {
                if (y2 === point[1] || Math.abs(x2 - point[1]) !== Math.abs(y2 - point[0])) continue;
                ans += countX2 * countY2 * (this.points.get(point[0]).get(y2) || 0);
            }
        }
        return ans;
    }
}
```
The algorithm we are using here is based on coordinate geometry. When we add new points, we use a dictionary or hashmap to store the frequency of each point added.

To detect squares, we iterate over all the sides of the potential square formed by the given two points. For each pair of points with x1, x2, y1, and y2 coordinates, we first check if they do not form correct sides; if so, we just need to continue to the next pair. If our conditions are met, the square formed by the pair is a valid square.

We then just calculate the result or count by multiplying the occurrence count of the points accordingly.

The worst-case time complexity will be O(max(m, n)²), where m is the number of points having the same x values and n is the number of points having the same y values.


# Solving Questions With Brainpower

- slug: solving-questions-with-brainpower
- difficulty: Medium

You are given a **0-indexed** 2D integer array `questions` where `questions[i] = [pointsi, brainpoweri]`.

The array describes the questions of an exam, where you have to process the questions **in order** (i.e., starting from question `0`) and make a decision whether to **solve** or **skip** each question. Solving question `i` will **earn** you `pointsi` points but you will be **unable** to solve each of the next `brainpoweri` questions. If you skip question `i`, you get to make the decision on the next question.

*   For example, given `questions = [[3, 2], [4, 3], [4, 4], [2, 5]]`:
    *   If question `0` is solved, you will earn `3` points but you will be unable to solve questions `1` and `2`.
    *   If instead, question `0` is skipped and question `1` is solved, you will earn `4` points but you will be unable to solve questions `2` and `3`.

Return _the **maximum** points you can earn for the exam_.

**Example 1:**

**Input:** questions = \[\[3,2\],\[4,3\],\[4,4\],\[2,5\]\]
**Output:** 5
**Explanation:** The maximum points can be earned by solving questions 0 and 3.
- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions
- Unable to solve questions 1 and 2
- Solve question 3: Earn 2 points
Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points.

**Example 2:**

**Input:** questions = \[\[1,1\],\[2,2\],\[3,3\],\[4,4\],\[5,5\]\]
**Output:** 7
**Explanation:** The maximum points can be earned by solving questions 1 and 4.
- Skip question 0
- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions
- Unable to solve questions 2 and 3
- Solve question 4: Earn 5 points
Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.

**Constraints:**

*   `1 <= questions.length <= 105`
*   `questions[i].length == 2`
*   `1 <= pointsi, brainpoweri <= 105`

## A solution in Java

```java
public String longestSubsequenceRepeatedK(String s, int k) {
    int[] counts = new int[26];
    for (char c : s.toCharArray())
        counts[c - 'a']++;
    StringBuilder seq = new StringBuilder();
    for (int i = 25; i >= 0; i--)
        for (int j = 0; j < counts[i] / k; j++)
            seq.append((char) ('a' + i));
    return seq.toString();
}
```
1. Create an array `counts` to store the frequency of each character in the given string `s`.
2. Iterate through the string `s`, incrementing the count of each character as it is found.
3. Create a StringBuilder or an empty string `seq` to store the resulting subsequence.
4. Iterate through the `counts` array in reverse order so that we consider the lexicographically larger characters first.
5. Append each character to the `seq` string k times, making sure the count of a character is divisible by k.
6. Return the constructed `seq` string, which will be the lexicographically largest subsequence repeated k times.

## A solution in C++

```cpp
#include <string>

std::string longestSubsequenceRepeatedK(const std::string& s, int k) {
    int counts[26] = {0};
    for (char c : s)
        counts[c - 'a'] += 1;
    std::string seq;
    for (int i = 25; i >= 0; --i)
        seq += std::string(counts[i] / k, 'a' + i);
    return seq;
}
```
1. Create an array `counts` to store the frequency of each character in the given string `s`.
2. Iterate through the string `s`, incrementing the count of each character as it is found.
3. Create a StringBuilder or an empty string `seq` to store the resulting subsequence.
4. Iterate through the `counts` array in reverse order so that we consider the lexicographically larger characters first.
5. Append each character to the `seq` string k times, making sure the count of a character is divisible by k.
6. Return the constructed `seq` string, which will be the lexicographically largest subsequence repeated k times.

## A solution in Python

```python
def longest_subsequence_repeated_k(s, k):
    counts = [0] * 26
    for c in s:
        counts[ord(c) - ord('a')] += 1
    seq = ''.join([chr(i + ord('a')) * (counts[i] // k) for i in range(25, -1, -1)])
    return seq
```
1. Create an array `counts` to store the frequency of each character in the given string `s`.
2. Iterate through the string `s`, incrementing the count of each character as it is found.
3. Create a StringBuilder or an empty string `seq` to store the resulting subsequence.
4. Iterate through the `counts` array in reverse order so that we consider the lexicographically larger characters first.
5. Append each character to the `seq` string k times, making sure the count of a character is divisible by k.
6. Return the constructed `seq` string, which will be the lexicographically largest subsequence repeated k times.

## A solution in Javascript

```javascript
function longestSubsequenceRepeatedK(s, k) {
    const counts = new Array(26).fill(0);
    for (const c of s)
        counts[c.charCodeAt(0) - 'a'.charCodeAt(0)]++;
    let seq = '';
    for (let i = 25; i >= 0; i--)
        seq += String.fromCharCode('a'.charCodeAt(0) + i).repeat(Math.floor(counts[i] / k));
    return seq;
}
```
1. Create an array `counts` to store the frequency of each character in the given string `s`.
2. Iterate through the string `s`, incrementing the count of each character as it is found.
3. Create a StringBuilder or an empty string `seq` to store the resulting subsequence.
4. Iterate through the `counts` array in reverse order so that we consider the lexicographically larger characters first.
5. Append each character to the `seq` string k times, making sure the count of a character is divisible by k.
6. Return the constructed `seq` string, which will be the lexicographically largest subsequence repeated k times.


# Maximum Running Time of N Computers

- slug: maximum-running-time-of-n-computers
- difficulty: Hard

You have `n` computers. You are given the integer `n` and a **0-indexed** integer array `batteries` where the `ith` battery can **run** a computer for `batteries[i]` minutes. You are interested in running **all** `n` computers **simultaneously** using the given batteries.

Initially, you can insert **at most one battery** into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery **any number of times**. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time.

Note that the batteries cannot be recharged.

Return _the **maximum** number of minutes you can run all the_ `n` _computers simultaneously._

**Example 1:**

**Input:** n = 2, batteries = \[3,3,3\]
**Output:** 4
**Explanation:**
Initially, insert battery 0 into the first computer and battery 1 into the second computer.
After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.
At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.
By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.
We can run the two computers simultaneously for at most 4 minutes, so we return 4.

**Example 2:**

**Input:** n = 2, batteries = \[1,1,1,1\]
**Output:** 2
**Explanation:**
Initially, insert battery 0 into the first computer and battery 2 into the second computer.
After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer.
After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.
We can run the two computers simultaneously for at most 2 minutes, so we return 2.

**Constraints:**

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

## A solution in Java

```java
public int max_computer_runtime(int n, int[] batteries) {
    Arrays.sort(batteries);
    int result = 0;
    for (int i = 0; i < batteries.length; i++) {
        result = Math.max(result, Math.min(n, batteries.length - i) * batteries[i]);
    }
    return result;
}
```
The algorithm sorts the input `batteries` in ascending order. Then, it iterates through the sorted batteries and calculates the maximum possible runtime for every possible combination of batteries, by taking into account that each computer can have at most one battery at a time. The maximum runtime is calculated as the minimum of `n` (number of computers) and the remaining batteries count, multiplied by the battery's runtime. Finally, the algorithm returns the maximum obtained runtime from all the possible combinations.

## A solution in C++

```cpp
int max_computer_runtime(int n, vector<int>& batteries) {
    sort(batteries.begin(), batteries.end());
    int result = 0;
    for (int i = 0; i < batteries.size(); ++i) {
        result = max(result, min(n, int(batteries.size()) - i) * batteries[i]);
    }
    return result;
}
```
The algorithm sorts the input `batteries` in ascending order. Then, it iterates through the sorted batteries and calculates the maximum possible runtime for every possible combination of batteries, by taking into account that each computer can have at most one battery at a time. The maximum runtime is calculated as the minimum of `n` (number of computers) and the remaining batteries count, multiplied by the battery's runtime. Finally, the algorithm returns the maximum obtained runtime from all the possible combinations.

## A solution in Python

```python
def max_computer_runtime(n, batteries):
    batteries.sort()
    result = 0
    for i in range(len(batteries)):
        result = max(result, min(n, len(batteries) - i) * batteries[i])
    return result
```
The algorithm sorts the input `batteries` in ascending order. Then, it iterates through the sorted batteries and calculates the maximum possible runtime for every possible combination of batteries, by taking into account that each computer can have at most one battery at a time. The maximum runtime is calculated as the minimum of `n` (number of computers) and the remaining batteries count, multiplied by the battery's runtime. Finally, the algorithm returns the maximum obtained runtime from all the possible combinations.

## A solution in Javascript

```javascript
function max_computer_runtime(n, batteries) {
    batteries.sort((a, b) => a - b);
    let result = 0;
    for (let i = 0; i < batteries.length; i++) {
        result = Math.max(result, Math.min(n, batteries.length - i) * batteries[i]);
    }
    return result;
}
```
The algorithm sorts the input `batteries` in ascending order. Then, it iterates through the sorted batteries and calculates the maximum possible runtime for every possible combination of batteries, by taking into account that each computer can have at most one battery at a time. The maximum runtime is calculated as the minimum of `n` (number of computers) and the remaining batteries count, multiplied by the battery's runtime. Finally, the algorithm returns the maximum obtained runtime from all the possible combinations.


# Choose Numbers From Two Arrays in Range

- slug: choose-numbers-from-two-arrays-in-range
- difficulty: Hard

You are given two **0-indexed** integer arrays `nums1` and `nums2` of length `n`.

A range `[l, r]` (**inclusive**) where `0 <= l <= r < n` is **balanced** if:

*   For every `i` in the range `[l, r]`, you pick either `nums1[i]` or `nums2[i]`.
*   The sum of the numbers you pick from `nums1` equals to the sum of the numbers you pick from `nums2` (the sum is considered to be `0` if you pick no numbers from an array).

Two **balanced** ranges from `[l1, r1]` and `[l2, r2]` are considered to be **different** if at least one of the following is true:

*   `l1 != l2`
*   `r1 != r2`
*   `nums1[i]` is picked in the first range, and `nums2[i]` is picked in the second range or **vice versa** for at least one `i`.

Return _the number of **different** ranges that are balanced._ Since the answer may be very large, return it **modulo** `109 + 7`_._

**Example 1:**

**Input:** nums1 = \[1,2,5\], nums2 = \[2,6,3\]
**Output:** 3
**Explanation:** The balanced ranges are:
- \[0, 1\] where we choose nums2\[0\], and nums1\[1\].
  The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 2 = 2.
- \[0, 2\] where we choose nums1\[0\], nums2\[1\], and nums1\[2\].
  The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 1 + 5 = 6.
- \[0, 2\] where we choose nums1\[0\], nums1\[1\], and nums2\[2\].
  The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 1 + 2 = 3.
Note that the second and third balanced ranges are different.
In the second balanced range, we choose nums2\[1\] and in the third balanced range, we choose nums1\[1\].

**Example 2:**

**Input:** nums1 = \[0,1\], nums2 = \[1,0\]
**Output:** 4
**Explanation:** The balanced ranges are:
- \[0, 0\] where we choose nums1\[0\].
  The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 0 = 0.
- \[1, 1\] where we choose nums2\[1\].
  The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 0 = 0.
- \[0, 1\] where we choose nums1\[0\] and nums2\[1\].
  The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 0 = 0.
- \[0, 1\] where we choose nums2\[0\] and nums1\[1\].
  The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 1 = 1.

**Constraints:**

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

## A solution in Java

```java
public int numberOfBalancedRanges(int[] nums1, int[] nums2) {

    int n = nums1.length;
    int[][][][] dp = new int[n][n][n][3];
    dp[0][0][0][0] = 2;
    int[] sums1 = new int[n + 1], sums2 = new int[n + 1];
    for (int i = 0, s1 = 0, s2 = 0; i < nums1.length; i++) {
        s1 += nums1[i];
        s2 += nums2[i];
        sums1[i + 1] = s1;
        sums2[i + 1] = s2;
    }
    int MOD = 1_000_000_007;

    int ans = 0;
    for (int r = 0; r < nums1.length; ++r) {
        for (int l = r + 1; --l >= 0;) {
            for (int k = l; k <= r; ++k) {
                int leftSum1 = sums1[l];
                int rightSum1 = sums1[n] - sums1[k + 1];
                int leftSum2 = sums2[l];
                int rightSum2 = sums2[n] - sums2[r + 1];

                if (leftSum1 + rightSum2 == leftSum2 && leftSum1 + rightSum1 == rightSum2) {
                    for (int last = 0; last <= 2; ++last) {
                        ans += dp[l][r][k][last];
                        ans %= MOD;
                        int next = last == 2 ? k + 1 : k;
                        dp[next][k != 0 ? k : r + 1][k != 0 ? k - 1 : r + 2][last] +=
                            dp[l][r][k][last];
                        dp[l][r][k][last] =
                            (dp[l][r][k][last] + (!last || last == 2)) % MOD;
                    }
                }
            }
        }
    }
    return ans;
}
```
We use dynamic programming to solve this problem. Initially, we compute the prefix sums for nums1 and nums2. It helps us to calculate the sum of the numbers picked from a range quickly. We create a 4D dp table to store the answer. The dimensions in the dp table represent the range start (l), range end (r), iterator (k), and the last balanced range. We initialize the dp table accordingly. We iterate over the length of nums1 and consider each possible subarrays of nums1 and nums2. Inside the nested loop, we compute the left and right sums of nums1 and nums2 for each range, and we check if the given range is balanced by matching the required conditions. If the range is balanced, we loop through the last 3 balanced ranges and update the dp table accordingly. Finally, we return the answer.

## A solution in C++

```cpp
int numberOfBalancedRanges(vector<int>& nums1, vector<int>& nums2) {
    int MOD = 1e9 + 7, transitions[101][101][101][3] = {}; // <l1, r1, k1, last> = Number of Ways
    transitions[0][0][0][0] = 2;
    int sum1[101] = {}, sum2[101] = {};
    for (int i = 0, s1 = 0, s2 = 0; i < nums1.size(); ++i) {
        s1 += nums1[i], s2 += nums2[i];
        sum1[i + 1] = s1, sum2[i + 1] = s2;
    }
    auto valid = [&](int l, int r, int k) {
        int leftN1 = sum1[nums1.size()] - sum1[k + 1];
        return sum1[l] + sum2[r] - sum2[l] == sum2[k] &&
               sum2[l] + sum1[nums1.size()] - sum1[r + 1] == rightN1;
    };
    int ans = 0;
    for (int r = 0; r < nums1.size(); ++r) {
        for (int l = r + 1; --l >= 0;) {
            for (int k = l; k <= r; ++k) {
                if (valid(l, r, k)) {
                    for (int last = 0; last <= 2; ++last) {
                        ans += transitions[l][r][k][last], ans %= MOD;
                        int next = last == 2 ? k + 1 : k;
                        transitions[next][k ? k : r + 1][k ? k - 1 : r + 2][last] +=
                            transitions[l][r][k][last];
                        transitions[l][r][k][last] =
                            (transitions[l][r][k][last] + (!last || last == 2)) % MOD;
                    }
                }
            }
        }
    }
    return ans;
}
```
We use dynamic programming to solve this problem. Initially, we compute the prefix sums for nums1 and nums2. It helps us to calculate the sum of the numbers picked from a range quickly. We create a 4D dp table to store the answer. The dimensions in the dp table represent the range start (l), range end (r), iterator (k), and the last balanced range. We initialize the dp table accordingly. We iterate over the length of nums1 and consider each possible subarrays of nums1 and nums2. Inside the nested loop, we compute the left and right sums of nums1 and nums2 for each range, and we check if the given range is balanced by matching the required conditions. If the range is balanced, we loop through the last 3 balanced ranges and update the dp table accordingly. Finally, we return the answer.

## A solution in Python

```python
def numberOfBalancedRanges(nums1, nums2):
    MOD = 10**9 + 7
    dp = [[[0] * (101) for _ in range(101)] for _ in range(101)]

    dp[0][0] = 2
    sums1, sums2 = [0] * (len(nums1) + 1), [0] * (len(nums1) + 1)
    for i, (a, b) in enumerate(zip(nums1, nums2)):
        sums1[i + 1], sums2[i + 1] = sums1[i] + a, sums2[i] + b

    ans = 0
    for r in range(len(nums1)):
        for l in range(r, -1, -1):
            for k in range(l, r + 1):
                leftSum1 = sums1[l]
                rightSum1 = sums1[len(nums1)] - sums1[k + 1]
                leftSum2 = sums2[l]
                rightSum2 = sums2[len(nums1)] - sums2[r + 1]

                if leftSum1 + rightSum2 == leftSum2 and leftSum1 + rightSum1 == rightSum2:
                    for last in range(3):
                        ans += dp[l][r][k][last]
                        ans %= MOD
                        next = k + 1 if last == 2 else k
                        dp[next][k if k else r + 1][k - 1 if k else r +
                                                   2][last] += dp[l][r][k][last]
                        dp[l][r][k][last] = (dp[l][r][k][last] +
                                             ((!last) or last == 2)) % MOD
    return ans
```
We use dynamic programming to solve this problem. Initially, we compute the prefix sums for nums1 and nums2. It helps us to calculate the sum of the numbers picked from a range quickly. We create a 4D dp table to store the answer. The dimensions in the dp table represent the range start (l), range end (r), iterator (k), and the last balanced range. We initialize the dp table accordingly. We iterate over the length of nums1 and consider each possible subarrays of nums1 and nums2. Inside the nested loop, we compute the left and right sums of nums1 and nums2 for each range, and we check if the given range is balanced by matching the required conditions. If the range is balanced, we loop through the last 3 balanced ranges and update the dp table accordingly. Finally, we return the answer.

## A solution in Javascript

```javascript
var numberOfBalancedRanges = function (nums1, nums2) {
    const MOD = 1e9 + 7;
    const dp = Array.from({ length: 101 }, () =>
        Array.from({ length: 101 }, () => Array(101).fill(0))
    );
    dp[0][0] = 2;

    const sums1 = [0];
    const sums2 = [0];
    for (let i = 0; i < nums1.length; ++i) {
        sums1.push(sums1[i] + nums1[i]);
        sums2.push(sums2[i] + nums2[i]);
    }

    let ans = 0;
    for (let r = 0; r < nums1.length; ++r) {
        for (let l = r + 1; --l >= 0;) {
            for (let k = l; k <= r; ++k) {
                const leftSum1 = sums1[l];
                const rightSum1 = sums1[nums1.length] - sums1[k + 1];
                const leftSum2 = sums2[l];
                const rightSum2 = sums2[nums1.length] - sums2[r + 1];

                if (
                    leftSum1 + rightSum2 == leftSum2 &&
                    leftSum1 + rightSum1 == rightSum2
                ) {
                    for (let last = 0; last <= 2; ++last) {
                        ans += dp[l][r][k][last];
                        ans %= MOD;
                        const next = last == 2 ? k + 1 : k;
                        dp[next][k ? k : r + 1][k ? k - 1 : r + 2][last] +=
                            dp[l][r][k][last];
                        dp[l][r][k][last] =
                            (dp[l][r][k][last] + (!last || last == 2)) % MOD;
                    }
                }
            }
        }
    }
    return ans;
};
```
We use dynamic programming to solve this problem. Initially, we compute the prefix sums for nums1 and nums2. It helps us to calculate the sum of the numbers picked from a range quickly. We create a 4D dp table to store the answer. The dimensions in the dp table represent the range start (l), range end (r), iterator (k), and the last balanced range. We initialize the dp table accordingly. We iterate over the length of nums1 and consider each possible subarrays of nums1 and nums2. Inside the nested loop, we compute the left and right sums of nums1 and nums2 for each range, and we check if the given range is balanced by matching the required conditions. If the range is balanced, we loop through the last 3 balanced ranges and update the dp table accordingly. Finally, we return the answer.


# Minimum Cost of Buying Candies With Discount

- slug: minimum-cost-of-buying-candies-with-discount
- difficulty: Easy

A shop is selling candies at a discount. For **every two** candies sold, the shop gives a **third** candy for **free**.

The customer can choose **any** candy to take away for free as long as the cost of the chosen candy is less than or equal to the **minimum** cost of the two candies bought.

*   For example, if there are `4` candies with costs `1`, `2`, `3`, and `4`, and the customer buys candies with costs `2` and `3`, they can take the candy with cost `1` for free, but not the candy with cost `4`.

Given a **0-indexed** integer array `cost`, where `cost[i]` denotes the cost of the `ith` candy, return _the **minimum cost** of buying **all** the candies_.

**Example 1:**

**Input:** cost = \[1,2,3\]
**Output:** 5
**Explanation:** We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.
The total cost of buying all candies is 2 + 3 = 5. This is the **only** way we can buy the candies.
Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.
The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.

**Example 2:**

**Input:** cost = \[6,5,7,9,2,2\]
**Output:** 23
**Explanation:** The way in which we can get the minimum cost is described below:
- Buy candies with costs 9 and 7
- Take the candy with cost 6 for free
- We buy candies with costs 5 and 2
- Take the last remaining candy with cost 2 for free
Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.

**Example 3:**

**Input:** cost = \[5,5\]
**Output:** 10
**Explanation:** Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.
Hence, the minimum cost to buy all candies is 5 + 5 = 10.

**Constraints:**

*   `1 <= cost.length <= 100`
*   `1 <= cost[i] <= 100`

## A solution in Java

```java
public int maxDifference(int[] nums) {
    int min_val = nums[0];
    int max_diff = -1;

    for (int i = 1; i < nums.length; ++i) {
        if (nums[i] > min_val) {
            max_diff = Math.max(max_diff, nums[i] - min_val);
        } else {
            min_val = nums[i];
        }
    }
    return max_diff;
}
```
The algorithm iterates through the array while keeping track of the smallest value found so far (`min_val`). For each element in the array, it checks if the current value is greater than the `min_val`. If it is, it calculates the difference and updates the `max_diff` if the difference is greater than the current `max_diff`. If the current value is not greater than the `min_val`, the `min_val` is updated to the current value. The algorithm returns the `max_diff` found during the iteration. If no such i and j exist, the `max_diff` remains -1.

## A solution in C++

```cpp
int maxDifference(vector<int>& nums) {
    int min_val = nums[0];
    int max_diff = -1;

    for (int i = 1; i < nums.size(); ++i) {
        if (nums[i] > min_val) {
            max_diff = max(max_diff, nums[i] - min_val);
        } else {
            min_val = nums[i];
        }
    }
    return max_diff;
}
```
The algorithm iterates through the array while keeping track of the smallest value found so far (`min_val`). For each element in the array, it checks if the current value is greater than the `min_val`. If it is, it calculates the difference and updates the `max_diff` if the difference is greater than the current `max_diff`. If the current value is not greater than the `min_val`, the `min_val` is updated to the current value. The algorithm returns the `max_diff` found during the iteration. If no such i and j exist, the `max_diff` remains -1.

## A solution in Python

```python
def max_difference(nums):
    min_val = nums[0]
    max_diff = -1

    for i in range(1, len(nums)):
        if nums[i] > min_val:
            max_diff = max(max_diff, nums[i] - min_val)
        else:
            min_val = nums[i]

    return max_diff
```
The algorithm iterates through the array while keeping track of the smallest value found so far (`min_val`). For each element in the array, it checks if the current value is greater than the `min_val`. If it is, it calculates the difference and updates the `max_diff` if the difference is greater than the current `max_diff`. If the current value is not greater than the `min_val`, the `min_val` is updated to the current value. The algorithm returns the `max_diff` found during the iteration. If no such i and j exist, the `max_diff` remains -1.

## A solution in Javascript

```javascript
function maxDifference(nums) {
    let min_val = nums[0];
    let max_diff = -1;

    for (let i = 1; i < nums.length; ++i) {
        if (nums[i] > min_val) {
            max_diff = Math.max(max_diff, nums[i] - min_val);
        } else {
            min_val = nums[i];
        }
    }
    return max_diff;
}
```
The algorithm iterates through the array while keeping track of the smallest value found so far (`min_val`). For each element in the array, it checks if the current value is greater than the `min_val`. If it is, it calculates the difference and updates the `max_diff` if the difference is greater than the current `max_diff`. If the current value is not greater than the `min_val`, the `min_val` is updated to the current value. The algorithm returns the `max_diff` found during the iteration. If no such i and j exist, the `max_diff` remains -1.


# Count the Hidden Sequences

- slug: count-the-hidden-sequences
- difficulty: Medium

You are given a **0-indexed** array of `n` integers `differences`, which describes the **differences** between each pair of **consecutive** integers of a **hidden** sequence of length `(n + 1)`. More formally, call the hidden sequence `hidden`, then we have that `differences[i] = hidden[i + 1] - hidden[i]`.

You are further given two integers `lower` and `upper` that describe the **inclusive** range of values `[lower, upper]` that the hidden sequence can contain.

*   For example, given `differences = [1, -3, 4]`, `lower = 1`, `upper = 6`, the hidden sequence is a sequence of length `4` whose elements are in between `1` and `6` (**inclusive**).
    *   `[3, 4, 1, 5]` and `[4, 5, 2, 6]` are possible hidden sequences.
    *   `[5, 6, 3, 7]` is not possible since it contains an element greater than `6`.
    *   `[1, 2, 3, 4]` is not possible since the differences are not correct.

Return _the number of **possible** hidden sequences there are._ If there are no possible sequences, return `0`.

**Example 1:**

**Input:** differences = \[1,-3,4\], lower = 1, upper = 6
**Output:** 2
**Explanation:** The possible hidden sequences are:
- \[3, 4, 1, 5\]
- \[4, 5, 2, 6\]
Thus, we return 2.

**Example 2:**

**Input:** differences = \[3,-4,5,1,-2\], lower = -4, upper = 5
**Output:** 4
**Explanation:** The possible hidden sequences are:
- \[-3, 0, -4, 1, 2, 0\]
- \[-2, 1, -3, 2, 3, 1\]
- \[-1, 2, -2, 3, 4, 2\]
- \[0, 3, -1, 4, 5, 3\]
Thus, we return 4.

**Example 3:**

**Input:** differences = \[4,-7,2\], lower = 3, upper = 6
**Output:** 0
**Explanation:** There are no possible hidden sequences. Thus, we return 0.

**Constraints:**

*   `n == differences.length`
*   `1 <= n <= 105`
*   `-105 <= differences[i] <= 105`
*   `-105 <= lower <= upper <= 105`

## A solution in Java

```java
public int minSecondRobotPoints(int[][] grid) {
    int n = grid[0].length;
    for (int r = 0; r < 2; ++r) {
        for (int c = 1; c < n; ++c) {
            grid[r][c] += grid[r][c - 1];
        }
    }
    int[] dp = {grid[0][n - 1], 0};
    for (int c = n - 2; c >= 0; --c) {
        int[] dpNew = {Math.max(dp[0] - grid[0][c], dp[1] + grid[1][c]), Math.max(dp[1] - grid[1][c], dp[0] + grid[0][c])};
        dp[0] = dpNew[0];
        dp[1] = dpNew[1];
    }
    return Math.max(dp[0], dp[1]);
}
```
First, we can calculate the accumulated points within each row from left to right. This can help us to retrieve the points collected on robot's path between two consecutive columns.

Then, starting from the last column and working backwards to the first, we use dynamic programming to find the minimum number of points that the first robot can make the second robot collect.

At each step, we maintain the state of the minimum points collected by the second robot if it starts at each row in the current column. We update the state using the accumulated points calculated earlier, swapping the rows and taking the maximum of the current state minus the second robot's points in the current column, and the other row's state with the first robot's points in the current column.

Finally, we return the maximum of the two states at the first column.

This approach works because the first robot can choose to move down through the first row, making the second robot collect more points in the first row or stay in the second row, collecting more points in the second row. The dynamic programming allows us to find what the optimal choice is for the first robot at each column, given the number of points left for the second robot to collect.

## A solution in C++

```cpp
int min_second_robot_points(vector<vector<int>>& grid) {
    int n = grid[0].size();
    for(int r = 0; r < 2; ++r) {
        for(int c = 1; c < n; ++c) {
            grid[r][c] += grid[r][c - 1];
        }
    }
    int dp[2] = {grid[0][n - 1], 0};
    for(int c = n - 2; c >= 0; --c) {
        int dp_new[2] = {max(dp[0] - grid[0][c], dp[1] + grid[1][c]), max(dp[1] - grid[1][c], dp[0] + grid[0][c])};
        dp[0] = dp_new[0];
        dp[1] = dp_new[1];
    }
    return max(dp[0], dp[1]);
}
```
First, we can calculate the accumulated points within each row from left to right. This can help us to retrieve the points collected on robot's path between two consecutive columns.

Then, starting from the last column and working backwards to the first, we use dynamic programming to find the minimum number of points that the first robot can make the second robot collect.

At each step, we maintain the state of the minimum points collected by the second robot if it starts at each row in the current column. We update the state using the accumulated points calculated earlier, swapping the rows and taking the maximum of the current state minus the second robot's points in the current column, and the other row's state with the first robot's points in the current column.

Finally, we return the maximum of the two states at the first column.

This approach works because the first robot can choose to move down through the first row, making the second robot collect more points in the first row or stay in the second row, collecting more points in the second row. The dynamic programming allows us to find what the optimal choice is for the first robot at each column, given the number of points left for the second robot to collect.

## A solution in Python

```python
def min_second_robot_points(grid: List[List[int]]) -> int:
    n = len(grid[0])
    for r in range(2):
        for c in range(1, n):
            grid[r][c] += grid[r][c - 1]
    dp = [grid[0][n - 1], 0]
    for c in range(n - 2, -1, -1):
        dp_new = [max(dp[0] - grid[0][c], dp[1] + grid[1][c]), max(dp[1] - grid[1][c], dp[0] + grid[0][c])]
        dp = dp_new
    return max(dp)
```
First, we can calculate the accumulated points within each row from left to right. This can help us to retrieve the points collected on robot's path between two consecutive columns.

Then, starting from the last column and working backwards to the first, we use dynamic programming to find the minimum number of points that the first robot can make the second robot collect.

At each step, we maintain the state of the minimum points collected by the second robot if it starts at each row in the current column. We update the state using the accumulated points calculated earlier, swapping the rows and taking the maximum of the current state minus the second robot's points in the current column, and the other row's state with the first robot's points in the current column.

Finally, we return the maximum of the two states at the first column.

This approach works because the first robot can choose to move down through the first row, making the second robot collect more points in the first row or stay in the second row, collecting more points in the second row. The dynamic programming allows us to find what the optimal choice is for the first robot at each column, given the number of points left for the second robot to collect.

## A solution in Javascript

```javascript
function minSecondRobotPoints(grid) {
    const n = grid[0].length;
    for (let r = 0; r < 2; ++r) {
        for (let c = 1; c < n; ++c) {
            grid[r][c] += grid[r][c - 1];
        }
    }
    let dp = [grid[0][n - 1], 0];
    for (let c = n - 2; c >= 0; --c) {
        const dpNew = [Math.max(dp[0] - grid[0][c], dp[1] + grid[1][c]), Math.max(dp[1] - grid[1][c], dp[0] + grid[0][c])];
        dp = dpNew;
    }
    return Math.max(dp[0], dp[1]);
}
```
First, we can calculate the accumulated points within each row from left to right. This can help us to retrieve the points collected on robot's path between two consecutive columns.

Then, starting from the last column and working backwards to the first, we use dynamic programming to find the minimum number of points that the first robot can make the second robot collect.

At each step, we maintain the state of the minimum points collected by the second robot if it starts at each row in the current column. We update the state using the accumulated points calculated earlier, swapping the rows and taking the maximum of the current state minus the second robot's points in the current column, and the other row's state with the first robot's points in the current column.

Finally, we return the maximum of the two states at the first column.

This approach works because the first robot can choose to move down through the first row, making the second robot collect more points in the first row or stay in the second row, collecting more points in the second row. The dynamic programming allows us to find what the optimal choice is for the first robot at each column, given the number of points left for the second robot to collect.


# K Highest Ranked Items Within a Price Range

- slug: k-highest-ranked-items-within-a-price-range
- difficulty: Medium

You are given a **0-indexed** 2D integer array `grid` of size `m x n` that represents a map of the items in a shop. The integers in the grid represent the following:

*   `0` represents a wall that you cannot pass through.
*   `1` represents an empty cell that you can freely move to and from.
*   All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.

It takes `1` step to travel between adjacent grid cells.

You are also given integer arrays `pricing` and `start` where `pricing = [low, high]` and `start = [row, col]` indicates that you start at the position `(row, col)` and are interested only in items with a price in the range of `[low, high]` (**inclusive**). You are further given an integer `k`.

You are interested in the **positions** of the `k` **highest-ranked** items whose prices are **within** the given price range. The rank is determined by the **first** of these criteria that is different:

1.  Distance, defined as the length of the shortest path from the `start` (**shorter** distance has a higher rank).
2.  Price (**lower** price has a higher rank, but it must be **in the price range**).
3.  The row number (**smaller** row number has a higher rank).
4.  The column number (**smaller** column number has a higher rank).

Return _the_ `k` _highest-ranked items within the price range **sorted** by their rank (highest to lowest)_. If there are fewer than `k` reachable items within the price range, return _**all** of them_.

**Example 1:**

**Input:** grid = \[\[1,2,0,1\],\[1,3,0,1\],\[0,2,5,1\]\], pricing = \[2,5\], start = \[0,0\], k = 3
**Output:** \[\[0,1\],\[1,1\],\[2,1\]\]
**Explanation:** You start at (0,0).
With a price range of \[2,5\], we can take items from (0,1), (1,1), (2,1) and (2,2).
The ranks of these items are:
- (0,1) with distance 1
- (1,1) with distance 2
- (2,1) with distance 3
- (2,2) with distance 4
Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).

**Example 2:**

**Input:** grid = \[\[1,2,0,1\],\[1,3,3,1\],\[0,2,5,1\]\], pricing = \[2,3\], start = \[2,3\], k = 2
**Output:** \[\[2,1\],\[1,2\]\]
**Explanation:** You start at (2,3).
With a price range of \[2,3\], we can take items from (0,1), (1,1), (1,2) and (2,1).
The ranks of these items are:
- (2,1) with distance 2, price 2
- (1,2) with distance 2, price 3
- (1,1) with distance 3
- (0,1) with distance 4
Thus, the 2 highest ranked items in the price range are (2,1) and (1,2).

**Example 3:**

**Input:** grid = \[\[1,1,1\],\[0,0,1\],\[2,3,4\]\], pricing = \[2,3\], start = \[0,0\], k = 3
**Output:** \[\[2,1\],\[2,0\]\]
**Explanation:** You start at (0,0).
With a price range of \[2,3\], we can take items from (2,0) and (2,1).
The ranks of these items are:
- (2,1) with distance 5
- (2,0) with distance 6
Thus, the 2 highest ranked items in the price range are (2,1) and (2,0).
Note that k = 3 but there are only 2 reachable items within the price range.

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 105`
*   `1 <= m * n <= 105`
*   `0 <= grid[i][j] <= 105`
*   `pricing.length == 2`
*   `2 <= low <= high <= 105`
*   `start.length == 2`
*   `0 <= row <= m - 1`
*   `0 <= col <= n - 1`
*   `grid[row][col] > 0`
*   `1 <= k <= m * n`

## A solution in Java

```java
public boolean canPlaceWord(char[][] board, String word) {
    int m = board.length, n = board[0].length;
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (board[i][j] == word.charAt(0)) {
                if (checkWord(board, word, i, j, 0, 1) || checkWord(board, word, i, j, 1, 0))
                    return true;
            }
        }
    }
    return false;
}

public boolean checkWord(char[][] board, String word, int i, int j, int di, int dj) {
    int m = board.length, n = board[0].length;
    for (int k = 0; k < word.length(); ++k, i += di, j += dj) {
        if (i < 0 || i >= m || j < 0 || j >= n)
            return false;
        if (k == 0 || k == word.length() - 1)
            if (board[i][j] != word.charAt(k) && board[i][j] != ' ')
                return false;
        if (k > 0 && k < word.length() - 1)
            if (board[i][j] != word.charAt(k) && board[i][j] != ' ' && board[i][j] != '#')
                return false;
    }
    return true;
}
```
The algorithm checks all the positions of the board to find one that matches the first character of the given `word`. When it finds a match, it calls the `checkWord` function (passing the current position and direction) to check if the `word` can be placed either horizontally or vertically. If it can, it immediately returns `true`, otherwise it continues searching. If it fails to find a valid position, it returns `false`.

The `checkWord` function checks if the `word` can be placed in the board based on the given position and direction. It iterates over the characters of the `word`, verifying if its current position in the board is valid:
- If the character is at the first or last position of the `word`, it checks if the current cell in the board is the same as the character or is empty.
- If the character is in the middle of the `word`, it checks if the current cell in the board is the same as the character or empty, but not blocked (`#`).
- If the position is not valid, it immediately returns `false`.

If all positions are valid, the function returns `true`.

## A solution in C++

```cpp
bool canPlaceWord(vector<vector<char>>& board, string word) {
    int m = board.size(), n = board[0].size();
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (board[i][j] == word[0]) {
                if (checkWord(board, word, i, j, 0, 1) || checkWord(board, word, i, j, 1, 0))
                    return true;
            }
        }
    }
    return false;
}

bool checkWord(vector<vector<char>>& board, string word, int i, int j, int di, int dj) {
    int m = board.size(), n = board[0].size();
    for (int k = 0; k < word.size(); ++k, i += di, j += dj) {
        if (i < 0 || i >= m || j < 0 || j >= n)
            return false;
        if (k == 0 || k == word.size() - 1)
            if (board[i][j] != word[k] && board[i][j] != ' ')
                return false;
        if (k > 0 && k < word.size() - 1)
            if (board[i][j] != word[k] && board[i][j] != ' ' && board[i][j] != '#')
                return false;
    }
    return true;
}
```
The algorithm checks all the positions of the board to find one that matches the first character of the given `word`. When it finds a match, it calls the `checkWord` function (passing the current position and direction) to check if the `word` can be placed either horizontally or vertically. If it can, it immediately returns `true`, otherwise it continues searching. If it fails to find a valid position, it returns `false`.

The `checkWord` function checks if the `word` can be placed in the board based on the given position and direction. It iterates over the characters of the `word`, verifying if its current position in the board is valid:
- If the character is at the first or last position of the `word`, it checks if the current cell in the board is the same as the character or is empty.
- If the character is in the middle of the `word`, it checks if the current cell in the board is the same as the character or empty, but not blocked (`#`).
- If the position is not valid, it immediately returns `false`.

If all positions are valid, the function returns `true`.

## A solution in Python

```python
def can_place_word(board, word):
    m, n = len(board), len(board[0])
    for i in range(m):
        for j in range(n):
            if board[i][j] == word[0]:
                if check_word(board, word, i, j, 0, 1) or check_word(board, word, i, j, 1, 0):
                    return True
    return False

def check_word(board, word, i, j, di, dj):
    m, n = len(board), len(board[0])
    for k in range(len(word)):
        i += di
        j += dj
        if i < 0 or i >= m or j < 0 or j >= n:
            return False
        if k == 0 or k == len(word) - 1:
            if board[i][j] != word[k] and board[i][j] != ' ':
                return False
        if k > 0 and k < len(word) - 1:
            if board[i][j] != word[k] and board[i][j] != ' ' and board[i][j] != '#':
                return False
    return True
```
The algorithm checks all the positions of the board to find one that matches the first character of the given `word`. When it finds a match, it calls the `checkWord` function (passing the current position and direction) to check if the `word` can be placed either horizontally or vertically. If it can, it immediately returns `true`, otherwise it continues searching. If it fails to find a valid position, it returns `false`.

The `checkWord` function checks if the `word` can be placed in the board based on the given position and direction. It iterates over the characters of the `word`, verifying if its current position in the board is valid:
- If the character is at the first or last position of the `word`, it checks if the current cell in the board is the same as the character or is empty.
- If the character is in the middle of the `word`, it checks if the current cell in the board is the same as the character or empty, but not blocked (`#`).
- If the position is not valid, it immediately returns `false`.

If all positions are valid, the function returns `true`.

## A solution in Javascript

```javascript
function canPlaceWord(board, word) {
    let m = board.length, n = board[0].length;
    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; ++j) {
            if (board[i][j] === word[0]) {
                if (checkWord(board, word, i, j, 0, 1) || checkWord(board, word, i, j, 1, 0))
                    return true;
            }
        }
    }
    return false;
}

function checkWord(board, word, i, j, di, dj) {
    let m = board.length, n = board[0].length;
    for (let k = 0; k < word.length; ++k, i += di, j += dj) {
        if (i < 0 || i >= m || j < 0 || j >= n)
            return false;
        if (k === 0 || k === word.length - 1)
            if (board[i][j] !== word[k] && board[i][j] !== ' ')
                return false;
        if (k > 0 && k < word.length - 1)
            if (board[i][j] !== word[k] && board[i][j] !== ' ' && board[i][j] !== '#')
                return false;
    }
    return true;
}
```
The algorithm checks all the positions of the board to find one that matches the first character of the given `word`. When it finds a match, it calls the `checkWord` function (passing the current position and direction) to check if the `word` can be placed either horizontally or vertically. If it can, it immediately returns `true`, otherwise it continues searching. If it fails to find a valid position, it returns `false`.

The `checkWord` function checks if the `word` can be placed in the board based on the given position and direction. It iterates over the characters of the `word`, verifying if its current position in the board is valid:
- If the character is at the first or last position of the `word`, it checks if the current cell in the board is the same as the character or is empty.
- If the character is in the middle of the `word`, it checks if the current cell in the board is the same as the character or empty, but not blocked (`#`).
- If the position is not valid, it immediately returns `false`.

If all positions are valid, the function returns `true`.


# Number of Ways to Divide a Long Corridor

- slug: number-of-ways-to-divide-a-long-corridor
- difficulty: Hard

Along a long library corridor, there is a line of seats and decorative plants. You are given a **0-indexed** string `corridor` of length `n` consisting of letters `'S'` and `'P'` where each `'S'` represents a seat and each `'P'` represents a plant.

One room divider has **already** been installed to the left of index `0`, and **another** to the right of index `n - 1`. Additional room dividers can be installed. For each position between indices `i - 1` and `i` (`1 <= i <= n - 1`), at most one divider can be installed.

Divide the corridor into non-overlapping sections, where each section has **exactly two seats** with any number of plants. There may be multiple ways to perform the division. Two ways are **different** if there is a position with a room divider installed in the first way but not in the second way.

Return _the number of ways to divide the corridor_. Since the answer may be very large, return it **modulo** `109 + 7`. If there is no way, return `0`.

**Example 1:**

**Input:** corridor =  "SSPPSPS "
**Output:** 3
**Explanation:** There are 3 different ways to divide the corridor.
The black bars in the above image indicate the two room dividers already installed.
Note that in each of the ways, **each** section has exactly **two** seats.

**Example 2:**

**Input:** corridor =  "PPSPSP "
**Output:** 1
**Explanation:** There is only 1 way to divide the corridor, by not installing any additional dividers.
Installing any would create some section that does not have exactly two seats.

**Example 3:**

**Input:** corridor =  "S "
**Output:** 0
**Explanation:** There is no way to divide the corridor because there will always be a section that does not have exactly two seats.

**Constraints:**

*   `n == corridor.length`
*   `1 <= n <= 105`
*   `corridor[i]` is either `'S'` or `'P'`.

## A solution in Java

```java
public int sumOfPoints(String s, int[] answers) {
    int total_points = 0;
    int result = 0, term = 1;
    char sign = '+';

    for (int i = 0; i < s.length(); i++) {
        if (Character.isDigit(s.charAt(i))) {
            int number = s.charAt(i) - '0';
            if (sign == '+') {
                result += term;
                term = number;
            } else if (sign == '*') {
                term *= number;
            }
        } else {
            sign = s.charAt(i);
        }
    }
    result += term;

    for (int ans : answers) {
        total_points += (ans == result) ? 1 : 0;
    }

    return total_points;
}
```
1. Initialize `total_points` variable to hold the sum of points, and `result` variable to store the calculated result of the expression. `term` variable to store the current term in expression and character `sign`.
2. Loop through the string `s`. Check whether the character is a digit or not.
3. If the character is a digit, perform the operation depending on the `sign` variable. If `sign` is '+', add the `term` to the `result`, and update the `term`. If `sign` is '*', multiply the `term` by the number.
4. If the character is not a digit, update the `sign` variable.
5. At the end of the loop, add the remaining `term` to the `result`.
6. Now, iterate through the `answers` array and increment `total_points` if the answer is equal to the calculated `result`.
7. Finally, return the `total_points` which represents the sum of the points of the students.

## A solution in C++

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

int sumOfPoints(const std::string &s, const std::vector<int> &answers) {
    int total_points = 0;
    int result = 0, term = 1;
    char sign = '+';

    for (size_t i = 0; i < s.size(); i++) {
        if (isdigit(s[i])) {
            int number = s[i] - '0';
            if (sign == '+') {
                result += term;
                term = number;
            } else if (sign == '*') {
                term *= number;
            }
        } else {
            sign = s[i];
        }
    }
    result += term;

    for (int ans : answers) {
        total_points += (ans == result);
    }

    return total_points;
}
```
1. Initialize `total_points` variable to hold the sum of points, and `result` variable to store the calculated result of the expression. `term` variable to store the current term in expression and character `sign`.
2. Loop through the string `s`. Check whether the character is a digit or not.
3. If the character is a digit, perform the operation depending on the `sign` variable. If `sign` is '+', add the `term` to the `result`, and update the `term`. If `sign` is '*', multiply the `term` by the number.
4. If the character is not a digit, update the `sign` variable.
5. At the end of the loop, add the remaining `term` to the `result`.
6. Now, iterate through the `answers` array and increment `total_points` if the answer is equal to the calculated `result`.
7. Finally, return the `total_points` which represents the sum of the points of the students.

## A solution in Python

```python
def sum_of_points(s, answers):
    total_points = 0
    result = 0
    term = 1
    sign = "+"

    for char in s:
        if char.isdigit():
            number = int(char)
            if sign == "+":
                result += term
                term = number
            elif sign == "*":
                term *= number
        else:
            sign = char

    result += term

    for ans in answers:
        total_points += (ans == result)

    return total_points
```
1. Initialize `total_points` variable to hold the sum of points, and `result` variable to store the calculated result of the expression. `term` variable to store the current term in expression and character `sign`.
2. Loop through the string `s`. Check whether the character is a digit or not.
3. If the character is a digit, perform the operation depending on the `sign` variable. If `sign` is '+', add the `term` to the `result`, and update the `term`. If `sign` is '*', multiply the `term` by the number.
4. If the character is not a digit, update the `sign` variable.
5. At the end of the loop, add the remaining `term` to the `result`.
6. Now, iterate through the `answers` array and increment `total_points` if the answer is equal to the calculated `result`.
7. Finally, return the `total_points` which represents the sum of the points of the students.

## A solution in Javascript

```javascript
function sumOfPoints(s, answers) {
    let total_points = 0;
    let result = 0, term = 1;
    let sign = '+';

    for (let i = 0; i < s.length; i++) {
        if (s[i].charCodeAt(0) >= '0'.charCodeAt(0) && s[i].charCodeAt(0) <= '9'.charCodeAt(0)) {
            let number = s[i].charCodeAt(0) - '0'.charCodeAt(0);
            if (sign === '+') {
                result += term;
                term = number;
            } else if (sign === '*') {
                term *= number;
            }
        } else {
           sign = s[i];
        }
    }

    result += term;

    for (let ans of answers) {
        total_points += (ans === result) ? 1 : 0;
    }

    return total_points;
}
```
1. Initialize `total_points` variable to hold the sum of points, and `result` variable to store the calculated result of the expression. `term` variable to store the current term in expression and character `sign`.
2. Loop through the string `s`. Check whether the character is a digit or not.
3. If the character is a digit, perform the operation depending on the `sign` variable. If `sign` is '+', add the `term` to the `result`, and update the `term`. If `sign` is '*', multiply the `term` by the number.
4. If the character is not a digit, update the `sign` variable.
5. At the end of the loop, add the remaining `term` to the `result`.
6. Now, iterate through the `answers` array and increment `total_points` if the answer is equal to the calculated `result`.
7. Finally, return the `total_points` which represents the sum of the points of the students.