# Successful Pairs of Spells and Potions

- slug: successful-pairs-of-spells-and-potions
- difficulty: Medium

You are given two positive integer arrays `spells` and `potions`, of length `n` and `m` respectively, where `spells[i]` represents the strength of the `ith` spell and `potions[j]` represents the strength of the `jth` potion.

You are also given an integer `success`. A spell and potion pair is considered **successful** if the **product** of their strengths is **at least** `success`.

Return _an integer array_ `pairs` _of length_ `n` _where_ `pairs[i]` _is the number of **potions** that will form a successful pair with the_ `ith` _spell._

**Example 1:**

**Input:** spells = \[5,1,3\], potions = \[1,2,3,4,5\], success = 7
**Output:** \[4,0,3\]
**Explanation:**
- 0th spell: 5 \* \[1,2,3,4,5\] = \[5,**10**,**15**,**20**,**25**\]. 4 pairs are successful.
- 1st spell: 1 \* \[1,2,3,4,5\] = \[1,2,3,4,5\]. 0 pairs are successful.
- 2nd spell: 3 \* \[1,2,3,4,5\] = \[3,6,**9**,**12**,**15**\]. 3 pairs are successful.
Thus, \[4,0,3\] is returned.

**Example 2:**

**Input:** spells = \[3,1,2\], potions = \[8,5,8\], success = 16
**Output:** \[2,0,2\]
**Explanation:**
- 0th spell: 3 \* \[8,5,8\] = \[**24**,15,**24**\]. 2 pairs are successful.
- 1st spell: 1 \* \[8,5,8\] = \[8,5,8\]. 0 pairs are successful.
- 2nd spell: 2 \* \[8,5,8\] = \[**16**,10,**16**\]. 2 pairs are successful.
Thus, \[2,0,2\] is returned.

**Constraints:**

*   `n == spells.length`
*   `m == potions.length`
*   `1 <= n, m <= 105`
*   `1 <= spells[i], potions[i] <= 105`
*   `1 <= success <= 1010`

## A solution in Java

```java
import java.util.Arrays;

public String repeatLimitedString(String s, int repeatLimit) {
    char[] chars = s.toCharArray();
    Arrays.sort(chars);
    StringBuilder result = new StringBuilder();

    for (int i = chars.length - 1; i >= 0; i--) {
        char c = chars[i];
        int pos = result.indexOf(Character.toString(c));

        if (pos == -1) {
            result.append(c);
        } else {
            int count = 1;

            while (pos + count < result.length() && result.charAt(pos + count) == c) {
                count++;
            }

            if (count < repeatLimit) {
                result.insert(pos + count, c);
            }
        }
    }

    return result.toString();
}
```
1. Sort the given string s in descending order by converting it into an array, sorting, and reversing (in Python, sorting in reverse directly). This helps us process the characters in lexicographically largest order.
2. Iterate through the sorted characters.
3. For each character, find its position in the result string. If it is not present, add it; if it is present and the count of consecutive occurrences is less than repeatLimit, insert the character after the last occurrence of the same character.
4. Finally, convert the result back to a string, if applicable, and return it.

## A solution in C++

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

std::string repeatLimitedString(std::string s, int repeatLimit) {
    std::string result = "";
    std::sort(s.begin(), s.end(), std::greater<char>());

    for (char c : s) {
        size_t pos = result.find(c);

        if (pos == std::string::npos) {
            result.push_back(c);
        } else {
            int count = 1;

            while (pos + count < result.size() && result[pos + count] == c) {
                count++;
            }

            if (count < repeatLimit) {
                result.insert(pos + count, 1, c);
            }
        }
    }

    return result;
}
```
1. Sort the given string s in descending order by converting it into an array, sorting, and reversing (in Python, sorting in reverse directly). This helps us process the characters in lexicographically largest order.
2. Iterate through the sorted characters.
3. For each character, find its position in the result string. If it is not present, add it; if it is present and the count of consecutive occurrences is less than repeatLimit, insert the character after the last occurrence of the same character.
4. Finally, convert the result back to a string, if applicable, and return it.

## A solution in Python

```python
def repeat_limited_string(s, repeat_limit):
    result = []
    sorted_s = sorted(s, reverse=True)

    for c in sorted_s:
        pos = result.count(c)

        if pos < repeat_limit:
            result.insert(pos, c)

    return "".join(result)
```
1. Sort the given string s in descending order by converting it into an array, sorting, and reversing (in Python, sorting in reverse directly). This helps us process the characters in lexicographically largest order.
2. Iterate through the sorted characters.
3. For each character, find its position in the result string. If it is not present, add it; if it is present and the count of consecutive occurrences is less than repeatLimit, insert the character after the last occurrence of the same character.
4. Finally, convert the result back to a string, if applicable, and return it.

## A solution in Javascript

```javascript
function repeatLimitedString(s, repeatLimit) {
    let result = "";
    let sortedS = Array.from(s).sort().reverse().join("");

    for (const c of sortedS) {
        let pos = result.indexOf(c);

        if (pos === -1) {
            result += c;
        } else {
            let count = 1;

            while (pos + count < result.length && result.charAt(pos + count) === c) {
                count++;
            }

            if (count < repeatLimit) {
                result = result.substring(0, pos + count) + c + result.substring(pos + count);
            }
        }
    }

    return result;
}
```
1. Sort the given string s in descending order by converting it into an array, sorting, and reversing (in Python, sorting in reverse directly). This helps us process the characters in lexicographically largest order.
2. Iterate through the sorted characters.
3. For each character, find its position in the result string. If it is not present, add it; if it is present and the count of consecutive occurrences is less than repeatLimit, insert the character after the last occurrence of the same character.
4. Finally, convert the result back to a string, if applicable, and return it.


# Match Substring After Replacement

- slug: match-substring-after-replacement
- difficulty: Hard

You are given two strings `s` and `sub`. You are also given a 2D character array `mappings` where `mappings[i] = [oldi, newi]` indicates that you may perform the following operation **any** number of times:

*   **Replace** a character `oldi` of `sub` with `newi`.

Each character in `sub` **cannot** be replaced more than once.

Return `true` _if it is possible to make_ `sub` _a substring of_ `s` _by replacing zero or more characters according to_ `mappings`. Otherwise, return `false`.

A **substring** is a contiguous non-empty sequence of characters within a string.

**Example 1:**

**Input:** s =  "fool3e7bar ", sub =  "leet ", mappings = \[\[ "e ", "3 "\],\[ "t ", "7 "\],\[ "t ", "8 "\]\]
**Output:** true
**Explanation:** Replace the first 'e' in sub with '3' and 't' in sub with '7'.
Now sub =  "l3e7 " is a substring of s, so we return true.

**Example 2:**

**Input:** s =  "fooleetbar ", sub =  "f00l ", mappings = \[\[ "o ", "0 "\]\]
**Output:** false
**Explanation:** The string  "f00l " is not a substring of s and no replacements can be made.
Note that we cannot replace '0' with 'o'.

**Example 3:**

**Input:** s =  "Fool33tbaR ", sub =  "leetd ", mappings = \[\[ "e ", "3 "\],\[ "t ", "7 "\],\[ "t ", "8 "\],\[ "d ", "b "\],\[ "p ", "b "\]\]
**Output:** true
**Explanation:** Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.
Now sub =  "l33tb " is a substring of s, so we return true.

**Constraints:**

*   `1 <= sub.length <= s.length <= 5000`
*   `0 <= mappings.length <= 1000`
*   `mappings[i].length == 2`
*   `oldi != newi`
*   `s` and `sub` consist of uppercase and lowercase English letters and digits.
*   `oldi` and `newi` are either uppercase or lowercase English letters or digits.

0 <= i < j < n and nums\[i\] % k + nums\[j\] % k == k.

## A solution in Java

```java
public int countPairs(int[] nums, int k) {
    int[] mod_count = new int[k];
    int count = 0;

    for(int num : nums) {
        mod_count[num % k]++;
    }

    count += mod_count[0] * (mod_count[0] - 1) / 2;

    for(int i = 1; i <= k/2; i++) {
        if (i != k - i) {
            count += mod_count[i] * mod_count[k-i];
        } else {
            count += mod_count[i] * (mod_count[i] - 1) / 2;
        }
    }
    return count;
}
```
1. Create an array `mod_count` of size k and initialize it with zeros. This array will store the frequency of each remainder when dividing the array elements by k.
2. Iterate through the input array `nums`, calculate the remainder when dividing each element by k, and increment the corresponding element in the `mod_count` array.
3. Calculate the pairs that have k as sum of the reminders. For this purpose:
   a. Calculate the pairs with both elements having 0 as reminder and add it to the count.
   b. Iterate through the possible divisors `i` of k (1 to k/2). If i is not equal to k-i, then add the product of both mod_counts to the final count. Otherwise, add the count of the valid pairs for the same reminder to the final count.
4. Return the final count of the pairs.

## A solution in C++

```cpp
int countPairs(vector<int>& nums, int k) {
    vector<int> mod_count(k, 0);
    int count = 0;

    for(int num : nums) {
        mod_count[num % k]++;
    }

    count += mod_count[0] * (mod_count[0] - 1) / 2;

    for(int i = 1; i <= k/2; i++) {
        if(i != k - i){
            count += mod_count[i] * mod_count[k-i];
        } else {
            count += mod_count[i] * (mod_count[i] - 1) / 2;
        }
    }
    return count;
}
```
1. Create an array `mod_count` of size k and initialize it with zeros. This array will store the frequency of each remainder when dividing the array elements by k.
2. Iterate through the input array `nums`, calculate the remainder when dividing each element by k, and increment the corresponding element in the `mod_count` array.
3. Calculate the pairs that have k as sum of the reminders. For this purpose:
   a. Calculate the pairs with both elements having 0 as reminder and add it to the count.
   b. Iterate through the possible divisors `i` of k (1 to k/2). If i is not equal to k-i, then add the product of both mod_counts to the final count. Otherwise, add the count of the valid pairs for the same reminder to the final count.
4. Return the final count of the pairs.

## A solution in Python

```python
def count_pairs(nums, k):
    mod_count = [0] * k
    count = 0

    for num in nums:
        mod_count[num % k] += 1

    count += mod_count[0] * (mod_count[0] - 1) // 2

    for i in range(1, k // 2 + 1):
        if i != k - i:
            count += mod_count[i] * mod_count[k-i]
        else:
            count += mod_count[i] * (mod_count[i] - 1) // 2

    return count
```
1. Create an array `mod_count` of size k and initialize it with zeros. This array will store the frequency of each remainder when dividing the array elements by k.
2. Iterate through the input array `nums`, calculate the remainder when dividing each element by k, and increment the corresponding element in the `mod_count` array.
3. Calculate the pairs that have k as sum of the reminders. For this purpose:
   a. Calculate the pairs with both elements having 0 as reminder and add it to the count.
   b. Iterate through the possible divisors `i` of k (1 to k/2). If i is not equal to k-i, then add the product of both mod_counts to the final count. Otherwise, add the count of the valid pairs for the same reminder to the final count.
4. Return the final count of the pairs.

## A solution in Javascript

```javascript
function countPairs(nums, k) {
    const mod_count = new Array(k).fill(0);
    let count = 0;

    for (const num of nums) {
        mod_count[num % k]++;
    }

    count += mod_count[0] * (mod_count[0] - 1) / 2;

    for (let i = 1; i <= Math.floor(k / 2); i++) {
        if (i != k - i) {
            count += mod_count[i] * mod_count[k-i];
        } else {
            count += mod_count[i] * (mod_count[i] - 1) / 2;
        }
    }

    return count;
}
```
1. Create an array `mod_count` of size k and initialize it with zeros. This array will store the frequency of each remainder when dividing the array elements by k.
2. Iterate through the input array `nums`, calculate the remainder when dividing each element by k, and increment the corresponding element in the `mod_count` array.
3. Calculate the pairs that have k as sum of the reminders. For this purpose:
   a. Calculate the pairs with both elements having 0 as reminder and add it to the count.
   b. Iterate through the possible divisors `i` of k (1 to k/2). If i is not equal to k-i, then add the product of both mod_counts to the final count. Otherwise, add the count of the valid pairs for the same reminder to the final count.
4. Return the final count of the pairs.


# Count Subarrays With Score Less Than K

- slug: count-subarrays-with-score-less-than-k
- difficulty: Hard

The **score** of an array is defined as the **product** of its sum and its length.

*   For example, the score of `[1, 2, 3, 4, 5]` is `(1 + 2 + 3 + 4 + 5) * 5 = 75`.

Given a positive integer array `nums` and an integer `k`, return _the **number of non-empty subarrays** of_ `nums` _whose score is **strictly less** than_ `k`.

A **subarray** is a contiguous sequence of elements within an array.

**Example 1:**

**Input:** nums = \[2,1,4,3,5\], k = 10
**Output:** 6
**Explanation:**
The 6 subarrays having scores less than 10 are:
- \[2\] with score 2 \* 1 = 2.
- \[1\] with score 1 \* 1 = 1.
- \[4\] with score 4 \* 1 = 4.
- \[3\] with score 3 \* 1 = 3.
- \[5\] with score 5 \* 1 = 5.
- \[2,1\] with score (2 + 1) \* 2 = 6.
Note that subarrays such as \[1,4\] and \[4,3,5\] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.

**Example 2:**

**Input:** nums = \[1,1,1\], k = 5
**Output:** 5
**Explanation:**
Every subarray except \[1,1,1\] has a score less than 5.
\[1,1,1\] has a score (1 + 1 + 1) \* 3 = 9, which is greater than 5.
Thus, there are 5 subarrays having scores less than 5.

**Constraints:**

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

## A solution in Java

```java
public int countSubarrays(int[] nums, long k) {
    int n = nums.length;
    int left = 0, right = 0;
    long sum = 0, count = 0;

    while (right < n) {
        sum += nums[right];
        while (sum * (right - left + 1) >= k) {
            sum -= nums[left];
            left++;
        }
        count += right - left + 1;
        right++;
    }

    return (int)count;
}
```
We use the sliding window technique to solve this problem as it ensures that we only check relevant subarrays.

1. Initialize two pointers `left` and `right` to 0 and variables `sum` and `count` to 0.

2. Iterate through the array using the `right` pointer.

3. Inside the loop, add the current value of `nums[right]` to the current sum.

4. Inside the loop, use the inner `while` loop to check if the score `sum * (right - left + 1)` is equal to or greater than `k`. If true, subtract the value at `nums[left]` from the sum and increment `left`.

5. Add the number of subarrays calculated at this step to the count: `count += right - left + 1`.

6. Increment the right pointer.

7. Continue iterating until the entire array is traversed.

8. Return the count of subarrays with scores less than `k`.

## A solution in C++

```cpp
int countSubarrays(vector<int>& nums, long long k) {
    int n = nums.size();
    int left = 0, right = 0;
    long long sum = 0, count = 0;

    while (right < n) {
        sum += nums[right];
        while (sum * (right - left + 1) >= k) {
            sum -= nums[left];
            left++;
        }
        count += right - left + 1;
        right++;
    }

    return count;
}
```
We use the sliding window technique to solve this problem as it ensures that we only check relevant subarrays.

1. Initialize two pointers `left` and `right` to 0 and variables `sum` and `count` to 0.

2. Iterate through the array using the `right` pointer.

3. Inside the loop, add the current value of `nums[right]` to the current sum.

4. Inside the loop, use the inner `while` loop to check if the score `sum * (right - left + 1)` is equal to or greater than `k`. If true, subtract the value at `nums[left]` from the sum and increment `left`.

5. Add the number of subarrays calculated at this step to the count: `count += right - left + 1`.

6. Increment the right pointer.

7. Continue iterating until the entire array is traversed.

8. Return the count of subarrays with scores less than `k`.

## A solution in Python

```python
def countSubarrays(nums: List[int], k: int) -> int:
    n = len(nums)
    left, right = 0, 0
    sum_, count = 0, 0

    while right < n:
        sum_ += nums[right]
        while sum_ * (right - left + 1) >= k:
            sum_ -= nums[left]
            left += 1
        count += right - left + 1
        right += 1

    return count
```
We use the sliding window technique to solve this problem as it ensures that we only check relevant subarrays.

1. Initialize two pointers `left` and `right` to 0 and variables `sum` and `count` to 0.

2. Iterate through the array using the `right` pointer.

3. Inside the loop, add the current value of `nums[right]` to the current sum.

4. Inside the loop, use the inner `while` loop to check if the score `sum * (right - left + 1)` is equal to or greater than `k`. If true, subtract the value at `nums[left]` from the sum and increment `left`.

5. Add the number of subarrays calculated at this step to the count: `count += right - left + 1`.

6. Increment the right pointer.

7. Continue iterating until the entire array is traversed.

8. Return the count of subarrays with scores less than `k`.

## A solution in Javascript

```javascript
function countSubarrays(nums, k) {
    let n = nums.length;
    let left = 0, right = 0;
    let sum = 0, count = 0;

    while (right < n) {
        sum += nums[right];
        while (sum * (right - left + 1) >= k) {
            sum -= nums[left];
            left++;
        }
        count += right - left + 1;
        right++;
    }

    return count;
}
```
We use the sliding window technique to solve this problem as it ensures that we only check relevant subarrays.

1. Initialize two pointers `left` and `right` to 0 and variables `sum` and `count` to 0.

2. Iterate through the array using the `right` pointer.

3. Inside the loop, add the current value of `nums[right]` to the current sum.

4. Inside the loop, use the inner `while` loop to check if the score `sum * (right - left + 1)` is equal to or greater than `k`. If true, subtract the value at `nums[left]` from the sum and increment `left`.

5. Add the number of subarrays calculated at this step to the count: `count += right - left + 1`.

6. Increment the right pointer.

7. Continue iterating until the entire array is traversed.

8. Return the count of subarrays with scores less than `k`.


# Calculate Amount Paid in Taxes

- slug: calculate-amount-paid-in-taxes
- difficulty: Easy

You are given a **0-indexed** 2D integer array `brackets` where `brackets[i] = [upperi, percenti]` means that the `ith` tax bracket has an upper bound of `upperi` and is taxed at a rate of `percenti`. The brackets are **sorted** by upper bound (i.e. `upperi-1 < upperi` for `0 < i < brackets.length`).

Tax is calculated as follows:

*   The first `upper0` dollars earned are taxed at a rate of `percent0`.
*   The next `upper1 - upper0` dollars earned are taxed at a rate of `percent1`.
*   The next `upper2 - upper1` dollars earned are taxed at a rate of `percent2`.
*   And so on.

You are given an integer `income` representing the amount of money you earned. Return _the amount of money that you have to pay in taxes._ Answers within `10-5` of the actual answer will be accepted.

**Example 1:**

**Input:** brackets = \[\[3,50\],\[7,10\],\[12,25\]\], income = 10
**Output:** 2.65000
**Explanation:**
Based on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket.
The tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.
In total, you pay $3 \* 50% + $4 \* 10% + $3 \* 25% = $2.65 in taxes.

**Example 2:**

**Input:** brackets = \[\[1,0\],\[4,25\],\[5,50\]\], income = 2
**Output:** 0.25000
**Explanation:**
Based on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket.
The tax rate for the two tax brackets is 0% and 25%, respectively.
In total, you pay $1 \* 0% + $1 \* 25% = $0.25 in taxes.

**Example 3:**

**Input:** brackets = \[\[2,50\]\], income = 0
**Output:** 0.00000
**Explanation:**
You have no income to tax, so you have to pay a total of $0 in taxes.

**Constraints:**

*   `1 <= brackets.length <= 100`
*   `1 <= upperi <= 1000`
*   `0 <= percenti <= 100`
*   `0 <= income <= 1000`
*   `upperi` is sorted in ascending order.
*   All the values of `upperi` are **unique**.
*   The upper bound of the last tax bracket is greater than or equal to `income`.

## A solution in Java

```java
double taxAmount(int[][] brackets, int income) {
    double tax = 0;
    int prev_upper = 0;
    for (int[] bracket : brackets) {
        int upper = bracket[0];
        double percent = bracket[1] / 100.0;
        tax += (Math.min(upper, income) - prev_upper) * percent;
        prev_upper = upper;
        if (income <= upper) break;
    }
    return tax;
}
```
The algorithm loops through the tax brackets and calculates the tax for each segment. The tax amount for each segment is calculated as `(min(upper, income) - prev_upper) * percent`. We also need to keep track of the previous upper bound, which is why `prev_upper` is initialized to 0 and updated in each iteration. If the income is less than or equal to the current upper bound, we can break out of the loop as the remaining tax segments don't matter.

The time complexity of this algorithm is O(n), where n is the number of tax brackets.

## A solution in C++

```cpp
double taxAmount(vector<vector<int>>& brackets, int income) {
    double tax = 0;
    int prev_upper = 0;
    for (vector<int>& bracket : brackets) {
        int upper = bracket[0];
        double percent = bracket[1] / 100.0;
        tax += (min(upper, income) - prev_upper) * percent;
        prev_upper = upper;
        if (income <= upper) break;
    }
    return tax;
}
```
The algorithm loops through the tax brackets and calculates the tax for each segment. The tax amount for each segment is calculated as `(min(upper, income) - prev_upper) * percent`. We also need to keep track of the previous upper bound, which is why `prev_upper` is initialized to 0 and updated in each iteration. If the income is less than or equal to the current upper bound, we can break out of the loop as the remaining tax segments don't matter.

The time complexity of this algorithm is O(n), where n is the number of tax brackets.

## A solution in Python

```python
def tax_amount(brackets, income):
    tax = 0
    prev_upper = 0
    for upper, percent in brackets:
        tax += (min(upper, income) - prev_upper) * (percent / 100)
        prev_upper = upper
        if income <= upper:
            break
    return tax
```
The algorithm loops through the tax brackets and calculates the tax for each segment. The tax amount for each segment is calculated as `(min(upper, income) - prev_upper) * percent`. We also need to keep track of the previous upper bound, which is why `prev_upper` is initialized to 0 and updated in each iteration. If the income is less than or equal to the current upper bound, we can break out of the loop as the remaining tax segments don't matter.

The time complexity of this algorithm is O(n), where n is the number of tax brackets.

## A solution in Javascript

```javascript
function taxAmount(brackets, income) {
    let tax = 0;
    let prev_upper = 0;
    for (let bracket of brackets) {
        let upper = bracket[0];
        let percent = bracket[1] / 100;
        tax += (Math.min(upper, income) - prev_upper) * percent;
        prev_upper = upper;
        if (income <= upper) break;
    }
    return tax;
}
```
The algorithm loops through the tax brackets and calculates the tax for each segment. The tax amount for each segment is calculated as `(min(upper, income) - prev_upper) * percent`. We also need to keep track of the previous upper bound, which is why `prev_upper` is initialized to 0 and updated in each iteration. If the income is less than or equal to the current upper bound, we can break out of the loop as the remaining tax segments don't matter.

The time complexity of this algorithm is O(n), where n is the number of tax brackets.


# Minimum Path Cost in a Grid

- slug: minimum-path-cost-in-a-grid
- difficulty: Medium

You are given a **0-indexed** `m x n` integer matrix `grid` consisting of **distinct** integers from `0` to `m * n - 1`. You can move in this matrix from a cell to any other cell in the **next** row. That is, if you are in cell `(x, y)` such that `x < m - 1`, you can move to any of the cells `(x + 1, 0)`, `(x + 1, 1)`, ..., `(x + 1, n - 1)`. **Note** that it is not possible to move from cells in the last row.

Each possible move has a cost given by a **0-indexed** 2D array `moveCost` of size `(m * n) x n`, where `moveCost[i][j]` is the cost of moving from a cell with value `i` to a cell in column `j` of the next row. The cost of moving from cells in the last row of `grid` can be ignored.

The cost of a path in `grid` is the **sum** of all values of cells visited plus the **sum** of costs of all the moves made. Return _the **minimum** cost of a path that starts from any cell in the **first** row and ends at any cell in the **last** row._

**Example 1:**

**Input:** grid = \[\[5,3\],\[4,0\],\[2,1\]\], moveCost = \[\[9,8\],\[1,5\],\[10,12\],\[18,6\],\[2,4\],\[14,3\]\]
**Output:** 17
**Explanation:** The path with the minimum possible cost is the path 5 -> 0 -> 1.
- The sum of the values of cells visited is 5 + 0 + 1 = 6.
- The cost of moving from 5 to 0 is 3.
- The cost of moving from 0 to 1 is 8.
So the total cost of the path is 6 + 3 + 8 = 17.

**Example 2:**

**Input:** grid = \[\[5,1,2\],\[4,0,3\]\], moveCost = \[\[12,10,15\],\[20,23,8\],\[21,7,1\],\[8,1,13\],\[9,10,25\],\[5,3,2\]\]
**Output:** 6
**Explanation:** The path with the minimum possible cost is the path 2 -> 3.
- The sum of the values of cells visited is 2 + 3 = 5.
- The cost of moving from 2 to 3 is 1.
So the total cost of this path is 5 + 1 = 6.

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `2 <= m, n <= 50`
*   `grid` consists of distinct integers from `0` to `m * n - 1`.
*   `moveCost.length == m * n`
*   `moveCost[i].length == n`
*   `1 <= moveCost[i][j] <= 100`

## A solution in Java

```java
import java.util.*;

public List<String> excelSheetCells(String s) {
    int r1, r2;
    char c1, c2;

    String[] parts = s.split("[:]");
    c1 = parts[0].charAt(0);
    r1 = Integer.parseInt(parts[0].substring(1));
    c2 = parts[1].charAt(0);
    r2 = Integer.parseInt(parts[1].substring(1));

    List<String> result = new ArrayList<>();

    for (char c = c1; c <= c2; c++) {
        for (int r = r1; r <= r2; r++) {
            result.add(String.valueOf(c) + r);
        }
    }
    return result;
}
```
1. First, parse the input string `s` to extract the column and row values for c1, r1, c2, and r2.
2. Initialize an empty result list to store the cells.
3. Loop through the columns from c1 to c2.
  a. Loop through the rows from r1 to r2.
    i. Append the cell string formed by concatenating the current column and row to the result list.
4. Return the result list with all the created cells.

## A solution in C++

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

std::vector<std::string> excelSheetCells(std::string s) {
    int r1, r2, c1, c2;
    sscanf(s.c_str(), "%c%d:%c%d", &c1, &r1, &c2, &r2);
    std::vector<std::string> result;

    for (int c = c1; c <= c2; ++c) {
        for (int r = r1; r <= r2; ++r) {
            result.emplace_back(std::string(1, char(c)) + std::to_string(r));
        }
    }
    return result;
}
```
1. First, parse the input string `s` to extract the column and row values for c1, r1, c2, and r2.
2. Initialize an empty result list to store the cells.
3. Loop through the columns from c1 to c2.
  a. Loop through the rows from r1 to r2.
    i. Append the cell string formed by concatenating the current column and row to the result list.
4. Return the result list with all the created cells.

## A solution in Python

```python
def excel_sheet_cells(s: str):
    c1, r1, c2, r2 = s.split(':')
    r1, r2 = int(r1[1:]), int(r2[1:])
    c1, c2 = ord(c1[0]), ord(c2[0])
    result = []

    for c in range(c1, c2 + 1):
        for r in range(r1, r2 + 1):
            result.append(chr(c) + str(r))

    return result
```
1. First, parse the input string `s` to extract the column and row values for c1, r1, c2, and r2.
2. Initialize an empty result list to store the cells.
3. Loop through the columns from c1 to c2.
  a. Loop through the rows from r1 to r2.
    i. Append the cell string formed by concatenating the current column and row to the result list.
4. Return the result list with all the created cells.

## A solution in Javascript

```javascript
function excelSheetCells(s) {
    const [part1, part2] = s.split(':');
    const [c1, r1] = [part1.charCodeAt(0), parseInt(part1.slice(1))];
    const [c2, r2] = [part2.charCodeAt(0), parseInt(part2.slice(1))];

    const result = [];

    for (let c = c1; c <= c2; c++) {
        for (let r = r1; r <= r2; r++) {
            result.push(String.fromCharCode(c) + r);
        }
    }
    return result;
}
```
1. First, parse the input string `s` to extract the column and row values for c1, r1, c2, and r2.
2. Initialize an empty result list to store the cells.
3. Loop through the columns from c1 to c2.
  a. Loop through the rows from r1 to r2.
    i. Append the cell string formed by concatenating the current column and row to the result list.
4. Return the result list with all the created cells.


# Fair Distribution of Cookies

- slug: fair-distribution-of-cookies
- difficulty: Medium

You are given an integer array `cookies`, where `cookies[i]` denotes the number of cookies in the `ith` bag. You are also given an integer `k` that denotes the number of children to distribute **all** the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.

The **unfairness** of a distribution is defined as the **maximum** **total** cookies obtained by a single child in the distribution.

Return _the **minimum** unfairness of all distributions_.

**Example 1:**

**Input:** cookies = \[8,15,10,20,8\], k = 2
**Output:** 31
**Explanation:** One optimal distribution is \[8,15,8\] and \[10,20\]
- The 1st child receives \[8,15,8\] which has a total of 8 + 15 + 8 = 31 cookies.
- The 2nd child receives \[10,20\] which has a total of 10 + 20 = 30 cookies.
The unfairness of the distribution is max(31,30) = 31.
It can be shown that there is no distribution with an unfairness less than 31.

**Example 2:**

**Input:** cookies = \[6,1,3,2,2,4,1,2\], k = 3
**Output:** 7
**Explanation:** One optimal distribution is \[6,1\], \[3,2,2\], and \[4,1,2\]
- The 1st child receives \[6,1\] which has a total of 6 + 1 = 7 cookies.
- The 2nd child receives \[3,2,2\] which has a total of 3 + 2 + 2 = 7 cookies.
- The 3rd child receives \[4,1,2\] which has a total of 4 + 1 + 2 = 7 cookies.
The unfairness of the distribution is max(7,7,7) = 7.
It can be shown that there is no distribution with an unfairness less than 7.

**Constraints:**

*   `2 <= cookies.length <= 8`
*   `1 <= cookies[i] <= 105`
*   `2 <= k <= cookies.length`

## A solution in Java

```java
public int minAppendKSum(int[] nums, int k) {
    int max_elem = Arrays.stream(nums).max().getAsInt();
    int sum = 0;
    for (int i = max_elem + 1; i <= max_elem + k; i++) {
        sum += i;
    }
    return sum;
}
```
The algorithm simply finds the maximum element in the given array `nums` and calculates the sum of the next `k` unique positive integers after that maximum element to ensure the resulting total sum is minimum.

1. Find the maximum element in the array, denoted as `max_elem`.
2. Calculate the sum of the `k` unique positive integers that come after `max_elem` by iterating from `max_elem + 1` to `max_elem + k` and adding each number to the sum.
3. Return the sum calculated in step 2.

## A solution in C++

```cpp
int minAppendKSum(vector<int>& nums, int k) {
    int max_elem = *max_element(nums.begin(), nums.end());
    int sum = 0;
    for (int i = max_elem + 1; i <= max_elem + k; ++i) {
        sum += i;
    }
    return sum;
}
```
The algorithm simply finds the maximum element in the given array `nums` and calculates the sum of the next `k` unique positive integers after that maximum element to ensure the resulting total sum is minimum.

1. Find the maximum element in the array, denoted as `max_elem`.
2. Calculate the sum of the `k` unique positive integers that come after `max_elem` by iterating from `max_elem + 1` to `max_elem + k` and adding each number to the sum.
3. Return the sum calculated in step 2.

## A solution in Python

```python
def min_append_k_sum(nums, k):
    max_elem = max(nums)
    return sum(range(max_elem + 1, max_elem + k + 1))
```
The algorithm simply finds the maximum element in the given array `nums` and calculates the sum of the next `k` unique positive integers after that maximum element to ensure the resulting total sum is minimum.

1. Find the maximum element in the array, denoted as `max_elem`.
2. Calculate the sum of the `k` unique positive integers that come after `max_elem` by iterating from `max_elem + 1` to `max_elem + k` and adding each number to the sum.
3. Return the sum calculated in step 2.

## A solution in Javascript

```javascript
function minAppendKSum(nums, k) {
    const max_elem = Math.max(...nums);
    let sum = 0;
    for (let i = max_elem + 1; i <= max_elem + k; i++) {
        sum += i;
    }
    return sum;
}
```
The algorithm simply finds the maximum element in the given array `nums` and calculates the sum of the next `k` unique positive integers after that maximum element to ensure the resulting total sum is minimum.

1. Find the maximum element in the array, denoted as `max_elem`.
2. Calculate the sum of the `k` unique positive integers that come after `max_elem` by iterating from `max_elem + 1` to `max_elem + k` and adding each number to the sum.
3. Return the sum calculated in step 2.


# Naming a Company

- slug: naming-a-company
- difficulty: Hard

You are given an array of strings `ideas` that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:

1.  Choose 2 **distinct** names from `ideas`, call them `ideaA` and `ideaB`.
2.  Swap the first letters of `ideaA` and `ideaB` with each other.
3.  If **both** of the new names are not found in the original `ideas`, then the name `ideaA ideaB` (the **concatenation** of `ideaA` and `ideaB`, separated by a space) is a valid company name.
4.  Otherwise, it is not a valid name.

Return _the number of **distinct** valid names for the company_.

**Example 1:**

**Input:** ideas = \[ "coffee ", "donuts ", "time ", "toffee "\]
**Output:** 6
**Explanation:** The following selections are valid:
- ( "coffee ",  "donuts "): The company name created is  "doffee conuts ".
- ( "donuts ",  "coffee "): The company name created is  "conuts doffee ".
- ( "donuts ",  "time "): The company name created is  "tonuts dime ".
- ( "donuts ",  "toffee "): The company name created is  "tonuts doffee ".
- ( "time ",  "donuts "): The company name created is  "dime tonuts ".
- ( "toffee ",  "donuts "): The company name created is  "doffee tonuts ".
Therefore, there are a total of 6 distinct company names.

The following are some examples of invalid selections:
- ( "coffee ",  "time "): The name  "toffee " formed after swapping already exists in the original array.
- ( "time ",  "toffee "): Both names are still the same after swapping and exist in the original array.
- ( "coffee ",  "toffee "): Both names formed after swapping already exist in the original array.

**Example 2:**

**Input:** ideas = \[ "lack ", "back "\]
**Output:** 0
**Explanation:** There are no valid selections. Therefore, 0 is returned.

**Constraints:**

*   `2 <= ideas.length <= 5 * 104`
*   `1 <= ideas[i].length <= 10`
*   `ideas[i]` consists of lowercase English letters.
*   All the strings in `ideas` are **unique**.

## A solution in Java

```java
import java.util.HashMap;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public TreeNode constructTree(int[][] descriptions) {
    HashMap<Integer, TreeNode> nodes = new HashMap<>();
    for (int[] d : descriptions) {
        nodes.put(d[0], new TreeNode(d[0]));
        nodes.put(d[1], new TreeNode(d[1]));
    }

    for (int[] d : descriptions) {
        if (d[2] == 1)
            nodes.get(d[0]).left = nodes.get(d[1]);
        else
            nodes.get(d[0]).right = nodes.get(d[1]);
    }

    return nodes.get(descriptions[0][0]);
}
```
The algorithm first initializes an empty binary tree structure and steps through the input descriptions. For each description, it creates the TreeNode instances for each parent and child. Then, it links the parent with the child according to the 'isLefti' value in each description.

1. Create a TreeNode class with `val`, `left`, and `right`, which represents our binary tree structure.
2. Create a function `constructTree` that accepts the descriptions input and initializes an empty hash_map (or dictionary in Python, Map in JavaScript) called `nodes` to store the parent and children node references.
3. For each description in the input, create TreeNode instances for the parent and child nodes (if not already created) and store them in our `nodes` hash table using their respective values as keys.
4. Iterate through the input descriptions again to connect each parent with its child(ren) based on the 'isLefti' value.
5. Return the root of the tree, which is the first parent in the given descriptions.

## A solution in C++

```cpp
#include <unordered_map>

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

TreeNode* constructTree(std::vector<std::vector<int>>& descriptions) {
    std::unordered_map<int, TreeNode*> nodes;
    for (const auto& d : descriptions) {
        nodes[d[0]] = new TreeNode(d[0]);
        nodes[d[1]] = new TreeNode(d[1]);
    }

    for (const auto& d : descriptions) {
        if (d[2])
            nodes[d[0]]->left = nodes[d[1]];
        else
            nodes[d[0]]->right = nodes[d[1]];
    }

    return nodes[descriptions.front()[0]];
}
```
The algorithm first initializes an empty binary tree structure and steps through the input descriptions. For each description, it creates the TreeNode instances for each parent and child. Then, it links the parent with the child according to the 'isLefti' value in each description.

1. Create a TreeNode class with `val`, `left`, and `right`, which represents our binary tree structure.
2. Create a function `constructTree` that accepts the descriptions input and initializes an empty hash_map (or dictionary in Python, Map in JavaScript) called `nodes` to store the parent and children node references.
3. For each description in the input, create TreeNode instances for the parent and child nodes (if not already created) and store them in our `nodes` hash table using their respective values as keys.
4. Iterate through the input descriptions again to connect each parent with its child(ren) based on the 'isLefti' value.
5. Return the root of the tree, which is the first parent in the given descriptions.

## A solution in Python

```python
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def construct_tree(descriptions):
    nodes = {}

    for d in descriptions:
        nodes[d[0]] = TreeNode(d[0])
        nodes[d[1]] = TreeNode(d[1])

    for d in descriptions:
        if d[2]:
            nodes[d[0]].left = nodes[d[1]]
        else:
            nodes[d[0]].right = nodes[d[1]]

    return nodes[descriptions[0][0]]
```
The algorithm first initializes an empty binary tree structure and steps through the input descriptions. For each description, it creates the TreeNode instances for each parent and child. Then, it links the parent with the child according to the 'isLefti' value in each description.

1. Create a TreeNode class with `val`, `left`, and `right`, which represents our binary tree structure.
2. Create a function `constructTree` that accepts the descriptions input and initializes an empty hash_map (or dictionary in Python, Map in JavaScript) called `nodes` to store the parent and children node references.
3. For each description in the input, create TreeNode instances for the parent and child nodes (if not already created) and store them in our `nodes` hash table using their respective values as keys.
4. Iterate through the input descriptions again to connect each parent with its child(ren) based on the 'isLefti' value.
5. Return the root of the tree, which is the first parent in the given descriptions.

## A solution in Javascript

```javascript
class TreeNode {
    constructor(val, left = null, right = null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

function constructTree(descriptions) {
    const nodes = new Map();

    for (const d of descriptions) {
        nodes.set(d[0], new TreeNode(d[0]));
        nodes.set(d[1], new TreeNode(d[1]));
    }

    for (const d of descriptions) {
        if (d[2] === 1)
            nodes.get(d[0]).left = nodes.get(d[1]);
        else
            nodes.get(d[0]).right = nodes.get(d[1]);
    }

    return nodes.get(descriptions[0][0]);
}
```
The algorithm first initializes an empty binary tree structure and steps through the input descriptions. For each description, it creates the TreeNode instances for each parent and child. Then, it links the parent with the child according to the 'isLefti' value in each description.

1. Create a TreeNode class with `val`, `left`, and `right`, which represents our binary tree structure.
2. Create a function `constructTree` that accepts the descriptions input and initializes an empty hash_map (or dictionary in Python, Map in JavaScript) called `nodes` to store the parent and children node references.
3. For each description in the input, create TreeNode instances for the parent and child nodes (if not already created) and store them in our `nodes` hash table using their respective values as keys.
4. Iterate through the input descriptions again to connect each parent with its child(ren) based on the 'isLefti' value.
5. Return the root of the tree, which is the first parent in the given descriptions.


# Check for Contradictions in Equations

- slug: check-for-contradictions-in-equations
- difficulty: Hard

You are given a 2D array of strings `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` means that `Ai / Bi = values[i]`.

Determine if there exists a contradiction in the equations. Return `true` _if there is a contradiction, or_ `false` _otherwise_.

**Note**:

*   When checking if two numbers are equal, check that their **absolute difference** is less than `10-5`.
*   The testcases are generated such that there are no cases targeting precision, i.e. using `double` is enough to solve the problem.

**Example 1:**

**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "a ", "c "\]\], values = \[3,0.5,1.5\]
**Output:** false
**Explanation:**
The given equations are: a / b = 3, b / c = 0.5, a / c = 1.5
There are no contradictions in the equations. One possible assignment to satisfy all equations is:
a = 3, b = 1 and c = 2.

**Example 2:**

**Input:** equations = \[\[ "le ", "et "\],\[ "le ", "code "\],\[ "code ", "et "\]\], values = \[2,5,0.5\]
**Output:** true
**Explanation:**
The given equations are: le / et = 2, le / code = 5, code / et = 0.5
Based on the first two equations, we get code / et = 0.4.
Since the third equation is code / et = 0.5, we get a contradiction.

**Constraints:**

*   `1 <= equations.length <= 100`
*   `equations[i].length == 2`
*   `1 <= Ai.length, Bi.length <= 5`
*   `Ai`, `Bi` consist of lowercase English letters.
*   `equations.length == values.length`
*   `0.0 < values[i] <= 10.0`
*   `values[i]` has a maximum of 2 decimal places.

## A solution in Java

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

public List<Integer> modifyArray(List<Integer> nums) {
    int n = nums.size();
    for (int i = 1; i < n; ++i) {
        if (gcd(nums.get(i - 1), nums.get(i)) > 1) {
            nums.add(i, 1);
            ++n;
            ++i;
        }
    }
    return nums;
}

private int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}
```
1. Loop through the input array starting from the second element.
2. For each element, check if it has a GCD greater than 1 with the previous element.
3. If they have a GCD greater than 1, insert the value 1 into the array between these two elements.
4. Move to the next element.
5. Repeat steps 2-4 until the end of the array is reached.
6. Return the modified array.

Both Python and JavaScript use 0-based indexing, so the index value is incremented when a new element is inserted. In C++ and Java, the element is inserted in the beginning of the vector and the index values are adjusted accordingly. This ensures that the algorithm works correctly for all languages. The `gcd` function is implemented using the Euclidean algorithm for calculating the greatest common divisor of two numbers.

## A solution in C++

```cpp
#include <algorithm>

int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}

std::vector<int> modifyArray(std::vector<int>& nums) {
    int n = nums.size();
    for (int i = 1; i < n; ++i) {
        if (gcd(nums[i - 1], nums[i]) > 1) {
            nums.insert(nums.begin() + i, 1);
            ++n;
            ++i;
        }
    }
    return nums;
}
```
1. Loop through the input array starting from the second element.
2. For each element, check if it has a GCD greater than 1 with the previous element.
3. If they have a GCD greater than 1, insert the value 1 into the array between these two elements.
4. Move to the next element.
5. Repeat steps 2-4 until the end of the array is reached.
6. Return the modified array.

Both Python and JavaScript use 0-based indexing, so the index value is incremented when a new element is inserted. In C++ and Java, the element is inserted in the beginning of the vector and the index values are adjusted accordingly. This ensures that the algorithm works correctly for all languages. The `gcd` function is implemented using the Euclidean algorithm for calculating the greatest common divisor of two numbers.

## A solution in Python

```python
from math import gcd

def modify_array(nums):
    i = 1
    while i < len(nums):
        if gcd(nums[i-1], nums[i]) > 1:
            nums.insert(i, 1)
            i += 1
        i += 1
    return nums
```
1. Loop through the input array starting from the second element.
2. For each element, check if it has a GCD greater than 1 with the previous element.
3. If they have a GCD greater than 1, insert the value 1 into the array between these two elements.
4. Move to the next element.
5. Repeat steps 2-4 until the end of the array is reached.
6. Return the modified array.

Both Python and JavaScript use 0-based indexing, so the index value is incremented when a new element is inserted. In C++ and Java, the element is inserted in the beginning of the vector and the index values are adjusted accordingly. This ensures that the algorithm works correctly for all languages. The `gcd` function is implemented using the Euclidean algorithm for calculating the greatest common divisor of two numbers.

## A solution in Javascript

```javascript
function gcd(a, b) {
    if (b === 0) return a;
    return gcd(b, a % b);
}

function modifyArray(nums) {
    let n = nums.length;
    for (let i = 1; i < n; ++i) {
        if (gcd(nums[i - 1], nums[i]) > 1) {
            nums.splice(i, 0, 1);
            ++n;
            ++i;
        }
    }
    return nums;
}
```
1. Loop through the input array starting from the second element.
2. For each element, check if it has a GCD greater than 1 with the previous element.
3. If they have a GCD greater than 1, insert the value 1 into the array between these two elements.
4. Move to the next element.
5. Repeat steps 2-4 until the end of the array is reached.
6. Return the modified array.

Both Python and JavaScript use 0-based indexing, so the index value is incremented when a new element is inserted. In C++ and Java, the element is inserted in the beginning of the vector and the index values are adjusted accordingly. This ensures that the algorithm works correctly for all languages. The `gcd` function is implemented using the Euclidean algorithm for calculating the greatest common divisor of two numbers.


# Greatest English Letter in Upper and Lower Case

- slug: greatest-english-letter-in-upper-and-lower-case
- difficulty: Easy

Given a string of English letters `s`, return _the **greatest** English letter which occurs as **both** a lowercase and uppercase letter in_ `s`. The returned letter should be in **uppercase**. If no such letter exists, return _an empty string_.

An English letter `b` is **greater** than another letter `a` if `b` appears **after** `a` in the English alphabet.

**Example 1:**

**Input:** s =  "l**Ee**TcOd**E** "
**Output:**  "E "
**Explanation:**
The letter 'E' is the only letter to appear in both lower and upper case.

**Example 2:**

**Input:** s =  "a**rR**AzFif "
**Output:**  "R "
**Explanation:**
The letter 'R' is the greatest letter to appear in both lower and upper case.
Note that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.

**Example 3:**

**Input:** s =  "AbCdEfGhIjK "
**Output:**  " "
**Explanation:**
There is no letter that appears in both lower and upper case.

**Constraints:**

*   `1 <= s.length <= 1000`
*   `s` consists of lowercase and uppercase English letters.

## A solution in Java

```java
public int getMaxOccurrences(String text, String pattern) {
    int[] count = new int[2];
    for (char c : text.toCharArray()) {
        if (c == pattern.charAt(1)) {
            count[1] += count[0];
        }
        else if (c == pattern.charAt(0)) {
            count[0] += 1;
        }
    }
    return count[1];
}
```
The algorithm iterates through the text string character by character. Two counters, count[0] and count[1], are used to keep track of the occurrences of pattern[0] and pattern[1], respectively. For each character encountered in the text, we check whether it is equal to pattern[0] or pattern[1]. If the character matches pattern[0], we increment counter count[0]. If the character matches pattern[1], we increment the counter count[1] by count[0], because we want to count the number of subsequences formed with the previously found matches of pattern[0]. Finally, after the iteration, the count of pattern[1] returns the maximum number of occurrences of the given pattern.

## A solution in C++

```cpp
int getMaxOccurrences(const std::string& text, const std::string& pattern) {
    int count[2] = {0, 0};
    for (char c : text) {
        if (c == pattern[1]) {
            count[1] += count[0];
        }
        else if (c == pattern[0]) {
            count[0] += 1;
        }
    }
    return count[1];
}
```
The algorithm iterates through the text string character by character. Two counters, count[0] and count[1], are used to keep track of the occurrences of pattern[0] and pattern[1], respectively. For each character encountered in the text, we check whether it is equal to pattern[0] or pattern[1]. If the character matches pattern[0], we increment counter count[0]. If the character matches pattern[1], we increment the counter count[1] by count[0], because we want to count the number of subsequences formed with the previously found matches of pattern[0]. Finally, after the iteration, the count of pattern[1] returns the maximum number of occurrences of the given pattern.

## A solution in Python

```python
def get_max_occurrences(text: str, pattern: str) -> int:
    count = [0, 0]
    for c in text:
        if c == pattern[1]:
            count[1] += count[0]
        elif c == pattern[0]:
            count[0] += 1
    return count[1]
```
The algorithm iterates through the text string character by character. Two counters, count[0] and count[1], are used to keep track of the occurrences of pattern[0] and pattern[1], respectively. For each character encountered in the text, we check whether it is equal to pattern[0] or pattern[1]. If the character matches pattern[0], we increment counter count[0]. If the character matches pattern[1], we increment the counter count[1] by count[0], because we want to count the number of subsequences formed with the previously found matches of pattern[0]. Finally, after the iteration, the count of pattern[1] returns the maximum number of occurrences of the given pattern.

## A solution in Javascript

```javascript
function getMaxOccurrences(text, pattern) {
    let count = [0, 0];
    for (let c of text) {
        if (c === pattern[1]) {
            count[1] += count[0];
        }
        else if (c === pattern[0]) {
            count[0] += 1;
        }
    }
    return count[1];
}
```
The algorithm iterates through the text string character by character. Two counters, count[0] and count[1], are used to keep track of the occurrences of pattern[0] and pattern[1], respectively. For each character encountered in the text, we check whether it is equal to pattern[0] or pattern[1]. If the character matches pattern[0], we increment counter count[0]. If the character matches pattern[1], we increment the counter count[1] by count[0], because we want to count the number of subsequences formed with the previously found matches of pattern[0]. Finally, after the iteration, the count of pattern[1] returns the maximum number of occurrences of the given pattern.


# Sum of Numbers With Units Digit K

- slug: sum-of-numbers-with-units-digit-k
- difficulty: Medium

Given two integers `num` and `k`, consider a set of positive integers with the following properties:

*   The units digit of each integer is `k`.
*   The sum of the integers is `num`.

Return _the **minimum** possible size of such a set, or_ `-1` _if no such set exists._

Note:

*   The set can contain multiple instances of the same integer, and the sum of an empty set is considered `0`.
*   The **units digit** of a number is the rightmost digit of the number.

**Example 1:**

**Input:** num = 58, k = 9
**Output:** 2
**Explanation:**
One valid set is \[9,49\], as the sum is 58 and each integer has a units digit of 9.
Another valid set is \[19,39\].
It can be shown that 2 is the minimum possible size of a valid set.

**Example 2:**

**Input:** num = 37, k = 2
**Output:** -1
**Explanation:** It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.

**Example 3:**

**Input:** num = 0, k = 7
**Output:** 0
**Explanation:** The sum of an empty set is considered 0.

**Constraints:**

*   `0 <= num <= 3000`
*   `0 <= k <= 9`

## A solution in Java

```java
import java.util.Arrays;
import java.util.Collections;

public int minOperations(Integer[] nums) {
    Arrays.sort(nums, Collections.reverseOrder());
    int sum = 0, half_sum = 0, operations = 0;
    for (int num : nums) sum += num;
    for (int num : nums) {
        half_sum += num;
        operations++;
        if (half_sum >= (sum + 1) / 2) break;
    }
    return operations;
}
```
The algorithm first sorts the input array nums in decreasing order. Then, it calculates the total sum of elements in the array. It initializes two variables, half_sum, and operations, to 0.

The algorithm iterates through the sorted array, adding each element to the half_sum, and incrementing the operations count. It checks whether half_sum is greater than or equal to half of the total sum at each step, and if true, it breaks out of the loop.

Finally, the algorithm returns the value of operations, which is the minimum number of operations required to reduce the sum of nums by at least half.

## A solution in C++

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

int minOperations(std::vector<int>& nums) {
    std::sort(nums.begin(), nums.end(), std::greater<int>());
    int sum = 0, half_sum = 0, operations = 0;
    for (int num : nums) sum += num;
    for (int num : nums) {
        half_sum += num;
        operations++;
        if (half_sum >= (sum + 1) / 2) break;
    }
    return operations;
}
```
The algorithm first sorts the input array nums in decreasing order. Then, it calculates the total sum of elements in the array. It initializes two variables, half_sum, and operations, to 0.

The algorithm iterates through the sorted array, adding each element to the half_sum, and incrementing the operations count. It checks whether half_sum is greater than or equal to half of the total sum at each step, and if true, it breaks out of the loop.

Finally, the algorithm returns the value of operations, which is the minimum number of operations required to reduce the sum of nums by at least half.

## A solution in Python

```python
def min_operations(nums):
    nums.sort(reverse=True)
    total_sum = sum(nums)
    half_sum, operations = 0, 0
    for num in nums:
        half_sum += num
        operations += 1
        if half_sum >= (total_sum + 1) // 2:
            break
    return operations
```
The algorithm first sorts the input array nums in decreasing order. Then, it calculates the total sum of elements in the array. It initializes two variables, half_sum, and operations, to 0.

The algorithm iterates through the sorted array, adding each element to the half_sum, and incrementing the operations count. It checks whether half_sum is greater than or equal to half of the total sum at each step, and if true, it breaks out of the loop.

Finally, the algorithm returns the value of operations, which is the minimum number of operations required to reduce the sum of nums by at least half.

## A solution in Javascript

```javascript
function minOperations(nums) {
    nums.sort((a, b) => b - a);
    const sum = nums.reduce((a, b) => a + b, 0);
    let halfSum = 0, operations = 0;
    for (const num of nums) {
        halfSum += num;
        operations++;
        if (halfSum >= Math.floor((sum + 1) / 2)) break;
    }
    return operations;
}
```
The algorithm first sorts the input array nums in decreasing order. Then, it calculates the total sum of elements in the array. It initializes two variables, half_sum, and operations, to 0.

The algorithm iterates through the sorted array, adding each element to the half_sum, and incrementing the operations count. It checks whether half_sum is greater than or equal to half of the total sum at each step, and if true, it breaks out of the loop.

Finally, the algorithm returns the value of operations, which is the minimum number of operations required to reduce the sum of nums by at least half.


# Longest Binary Subsequence Less Than or Equal to K

- slug: longest-binary-subsequence-less-than-or-equal-to-k
- difficulty: Medium

You are given a binary string `s` and a positive integer `k`.

Return _the length of the **longest** subsequence of_ `s` _that makes up a **binary** number less than or equal to_ `k`.

Note:

*   The subsequence can contain **leading zeroes**.
*   The empty string is considered to be equal to `0`.
*   A **subsequence** is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.

**Example 1:**

**Input:** s =  "1001010 ", k = 5
**Output:** 5
**Explanation:** The longest subsequence of s that makes up a binary number less than or equal to 5 is  "00010 ", as this number is equal to 2 in decimal.
Note that  "00100 " and  "00101 " are also possible, which are equal to 4 and 5 in decimal, respectively.
The length of this subsequence is 5, so 5 is returned.

**Example 2:**

**Input:** s =  "00101001 ", k = 1
**Output:** 6
**Explanation:**  "000001 " is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
The length of this subsequence is 6, so 6 is returned.

**Constraints:**

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

## A solution in Java

```java
public int minVisibleWhiteTiles(String floor, int numCarpets, int carpetLen) {
    int n = floor.length();
    int visibleWhiteCount = 0;
    for (int i = 0; i < n; i++) visibleWhiteCount += (floor.charAt(i) == '1') ? 1 : 0;

    int coveredTiles = 0;
    for (int i = 0; i < n; i++) {
        if (floor.charAt(i) == '1') {
            int start = Math.max(0, i - carpetLen + 1);
            int end = Math.min(n - carpetLen, i);
            int maxCover = 0;
            for (int firstTile = start; firstTile <= end; firstTile++) {
                int cover = 0;
                for (int j = firstTile; j < firstTile + carpetLen; j++) {
                    cover += (floor.charAt(j) == '1') ? 1 : 0;
                }
                maxCover = Math.max(maxCover, cover);
            }

            coveredTiles += maxCover;
            --numCarpets;
            if (numCarpets == 0) break;
        }
    }

    return visibleWhiteCount - coveredTiles;
}
```
This function works as follows:

1. Loops through the floor once to count the number of white tiles (visible_white_count).
2. Begins a second loop through the floor to check possible locations for the carpets for maximum overlapping of white tiles.
3. Loops through subarrays with a length of carpetLen to find a position having the maximum number of white tiles (max_cover).
4. Adds max_cover to the covered_tiles.
5. Decreases the number of available carpets (numCarpets) by 1.
6. Checks whether every carpet is used.
7. Returns the difference between the visible_white_count and covered_tiles.

## A solution in C++

```cpp
int min_visible_white_tiles(const std::string& floor, int numCarpets, int carpetLen) {
    int n = floor.size();
    int visible_white_count = 0;
    for (int i = 0; i < n; i++) visible_white_count += (floor[i] == '1');

    int covered_tiles = 0;
    for (int i = 0; i < n; i++) {
        if (floor[i] == '1') {
            int start = std::max(0, i - carpetLen + 1);
            int end = std::min(n - carpetLen, i);
            int max_cover = 0;
            for (int first_tile = start; first_tile <= end; first_tile++) {
                int cover = std::count(floor.begin() + first_tile, floor.begin() + first_tile + carpetLen, '1');
                max_cover = std::max(max_cover, cover);
            }

            covered_tiles += max_cover;
            --numCarpets;
            if (numCarpets == 0) break;
        }
    }

    return visible_white_count - covered_tiles;
}
```
This function works as follows:

1. Loops through the floor once to count the number of white tiles (visible_white_count).
2. Begins a second loop through the floor to check possible locations for the carpets for maximum overlapping of white tiles.
3. Loops through subarrays with a length of carpetLen to find a position having the maximum number of white tiles (max_cover).
4. Adds max_cover to the covered_tiles.
5. Decreases the number of available carpets (numCarpets) by 1.
6. Checks whether every carpet is used.
7. Returns the difference between the visible_white_count and covered_tiles.

## A solution in Python

```python
def min_visible_white_tiles(floor, num_carpets, carpet_len):
    n = len(floor)
    visible_white_count = floor.count('1')

    covered_tiles = 0
    for i in range(n):
        if floor[i] == '1':
            start = max(0, i - carpet_len + 1)
            end = min(n - carpet_len, i)
            max_cover = 0
            for first_tile in range(start, end + 1):
                cover = floor[first_tile:first_tile + carpet_len].count('1')
                max_cover = max(max_cover, cover)

            covered_tiles += max_cover
            num_carpets -= 1
            if num_carpets == 0:
                break

    return visible_white_count - covered_tiles
```
This function works as follows:

1. Loops through the floor once to count the number of white tiles (visible_white_count).
2. Begins a second loop through the floor to check possible locations for the carpets for maximum overlapping of white tiles.
3. Loops through subarrays with a length of carpetLen to find a position having the maximum number of white tiles (max_cover).
4. Adds max_cover to the covered_tiles.
5. Decreases the number of available carpets (numCarpets) by 1.
6. Checks whether every carpet is used.
7. Returns the difference between the visible_white_count and covered_tiles.

## A solution in Javascript

```javascript
function minVisibleWhiteTiles(floor, numCarpets, carpetLen) {
    const n = floor.length;
    let visibleWhiteCount = 0;
    for (let i = 0; i < n; i++) {
        if (floor[i] === '1') visibleWhiteCount++;
    }

    let coveredTiles = 0;
    for (let i = 0; i < n; i++) {
        if (floor[i] === '1') {
            let start = Math.max(0, i - carpetLen + 1);
            let end = Math.min(n - carpetLen, i);
            let maxCover = 0;
            for (let firstTile = start; firstTile <= end; firstTile++) {
                let cover = 0;
                for (let j = firstTile; j < firstTile + carpetLen; j++) {
                    if (floor[j] === '1') cover ++;
                }
                maxCover = Math.max(maxCover, cover);
            }

            coveredTiles += maxCover;
            --numCarpets;
            if (numCarpets === 0) break;
        }
    }

    return visibleWhiteCount - coveredTiles;
}
```
This function works as follows:

1. Loops through the floor once to count the number of white tiles (visible_white_count).
2. Begins a second loop through the floor to check possible locations for the carpets for maximum overlapping of white tiles.
3. Loops through subarrays with a length of carpetLen to find a position having the maximum number of white tiles (max_cover).
4. Adds max_cover to the covered_tiles.
5. Decreases the number of available carpets (numCarpets) by 1.
6. Checks whether every carpet is used.
7. Returns the difference between the visible_white_count and covered_tiles.


# Selling Pieces of Wood

- slug: selling-pieces-of-wood
- difficulty: Hard

You are given two integers `m` and `n` that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array `prices`, where `prices[i] = [hi, wi, pricei]` indicates you can sell a rectangular piece of wood of height `hi` and width `wi` for `pricei` dollars.

To cut a piece of wood, you must make a vertical or horizontal cut across the **entire** height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to `prices`. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you **cannot** rotate a piece to swap its height and width.

Return _the **maximum** money you can earn after cutting an_ `m x n` _piece of wood_.

Note that you can cut the piece of wood as many times as you want.

**Example 1:**

**Input:** m = 3, n = 5, prices = \[\[1,4,2\],\[2,2,7\],\[2,1,3\]\]
**Output:** 19
**Explanation:** The diagram above shows a possible scenario. It consists of:
- 2 pieces of wood shaped 2 x 2, selling for a price of 2 \* 7 = 14.
- 1 piece of wood shaped 2 x 1, selling for a price of 1 \* 3 = 3.
- 1 piece of wood shaped 1 x 4, selling for a price of 1 \* 2 = 2.
This obtains a total of 14 + 3 + 2 = 19 money earned.
It can be shown that 19 is the maximum amount of money that can be earned.

**Example 2:**

**Input:** m = 4, n = 6, prices = \[\[3,2,10\],\[1,4,2\],\[4,1,3\]\]
**Output:** 32
**Explanation:** The diagram above shows a possible scenario. It consists of:
- 3 pieces of wood shaped 3 x 2, selling for a price of 3 \* 10 = 30.
- 1 piece of wood shaped 1 x 4, selling for a price of 1 \* 2 = 2.
This obtains a total of 30 + 2 = 32 money earned.
It can be shown that 32 is the maximum amount of money that can be earned.
Notice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.

**Constraints:**

*   `1 <= m, n <= 200`
*   `1 <= prices.length <= 2 * 104`
*   `prices[i].length == 3`
*   `1 <= hi <= m`
*   `1 <= wi <= n`
*   `1 <= pricei <= 106`
*   All the shapes of wood `(hi, wi)` are pairwise **distinct**.

## A solution in Java

```java
import java.util.HashMap;

public int maxCountTarget(int[] nums, int key) {
    HashMap<Integer, Integer> count = new HashMap<>();
    int max_count = 0;
    int max_target = -1;
    for (int i = 1; i < nums.length; ++i) {
        if (nums[i - 1] == key) {
            count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);
            if (count.get(nums[i]) > max_count) {
                max_count = count.get(nums[i]);
                max_target = nums[i];
            }
        }
    }
    return max_target;
}
```
1. Create a hash map (called `count`) to store the count of unique integers following the key.
2. Initialize `max_count` to 0 and `max_target` to -1.
3. Iterate through the array from index 1 to the end.
4. In each iteration, check if the element at the previous index is equal to the key.
5. If the previous element is equal to the key, increment the count of the current element in the hash map.
6. If the incremented count is greater than the current `max_count`, update `max_count` to the incremented count and `max_target` to the current element.
7. Return `max_target`.

## A solution in C++

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

int maxCountTarget(const std::vector<int>& nums, int key) {
    std::unordered_map<int, int> count;
    int max_count = 0;
    int max_target = -1;
    for (size_t i = 1; i < nums.size(); ++i) {
        if (nums[i - 1] == key) {
            count[nums[i]]++;
            if (count[nums[i]] > max_count) {
                max_count = count[nums[i]];
                max_target = nums[i];
            }
        }
    }
    return max_target;
}
```
1. Create a hash map (called `count`) to store the count of unique integers following the key.
2. Initialize `max_count` to 0 and `max_target` to -1.
3. Iterate through the array from index 1 to the end.
4. In each iteration, check if the element at the previous index is equal to the key.
5. If the previous element is equal to the key, increment the count of the current element in the hash map.
6. If the incremented count is greater than the current `max_count`, update `max_count` to the incremented count and `max_target` to the current element.
7. Return `max_target`.

## A solution in Python

```python
def max_count_target(nums, key):
    count = {}
    max_count = 0
    max_target = -1
    for i in range(1, len(nums)):
        if nums[i - 1] == key:
            count[nums[i]] = count.get(nums[i], 0) + 1
            if count[nums[i]] > max_count:
                max_count = count[nums[i]]
                max_target = nums[i]
    return max_target
```
1. Create a hash map (called `count`) to store the count of unique integers following the key.
2. Initialize `max_count` to 0 and `max_target` to -1.
3. Iterate through the array from index 1 to the end.
4. In each iteration, check if the element at the previous index is equal to the key.
5. If the previous element is equal to the key, increment the count of the current element in the hash map.
6. If the incremented count is greater than the current `max_count`, update `max_count` to the incremented count and `max_target` to the current element.
7. Return `max_target`.

## A solution in Javascript

```javascript
function maxCountTarget(nums, key) {
    let count = new Map();
    let maxCount = 0;
    let maxTarget = -1;
    for (let i = 1; i < nums.length; ++i) {
        if (nums[i - 1] === key) {
            count.set(nums[i], (count.get(nums[i]) || 0) + 1);
            if (count.get(nums[i]) > maxCount) {
                maxCount = count.get(nums[i]);
                maxTarget = nums[i];
            }
        }
    }
    return maxTarget;
}
```
1. Create a hash map (called `count`) to store the count of unique integers following the key.
2. Initialize `max_count` to 0 and `max_target` to -1.
3. Iterate through the array from index 1 to the end.
4. In each iteration, check if the element at the previous index is equal to the key.
5. If the previous element is equal to the key, increment the count of the current element in the hash map.
6. If the incremented count is greater than the current `max_count`, update `max_count` to the incremented count and `max_target` to the current element.
7. Return `max_target`.


# Minimum Flips in Binary Tree to Get Result

- slug: minimum-flips-in-binary-tree-to-get-result
- difficulty: Hard

You are given the `root` of a **binary tree** with the following properties:

*   **Leaf nodes** have either the value `0` or `1`, representing `false` and `true` respectively.
*   **Non-leaf nodes** have either the value `2`, `3`, `4`, or `5`, representing the boolean operations `OR`, `AND`, `XOR`, and `NOT`, respectively.

You are also given a boolean `result`, which is the desired result of the **evaluation** of the `root` node.

The evaluation of a node is as follows:

*   If the node is a leaf node, the evaluation is the **value** of the node, i.e. `true` or `false`.
*   Otherwise, **evaluate** the node's children and **apply** the boolean operation of its value with the children's evaluations.

In one operation, you can **flip** a leaf node, which causes a `false` node to become `true`, and a `true` node to become `false`.

Return _the minimum number of operations that need to be performed such that the evaluation of_ `root` _yields_ `result`. It can be shown that there is always a way to achieve `result`.

A **leaf node** is a node that has zero children.

Note: `NOT` nodes have either a left child or a right child, but other non-leaf nodes have both a left child and a right child.

**Example 1:**

**Input:** root = \[3,5,4,2,null,1,1,1,0\], result = true
**Output:** 2
**Explanation:**
It can be shown that a minimum of 2 nodes have to be flipped to make the root of the tree
evaluate to true. One way to achieve this is shown in the diagram above.

**Example 2:**

**Input:** root = \[0\], result = false
**Output:** 0
**Explanation:**
The root of the tree already evaluates to false, so 0 nodes have to be flipped.

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 105]`.
*   `0 <= Node.val <= 5`
*   `OR`, `AND`, and `XOR` nodes have `2` children.
*   `NOT` nodes have `1` child.
*   Leaf nodes have a value of `0` or `1`.
*   Non-leaf nodes have a value of `2`, `3`, `4`, or `5`.

## A solution in Java

```java
public class Node {
    int val;
    Node left;
    Node right;
}

public int minOperations(Node root, int result) {
    if (root == null) {
        return 0;
    }
    if (root.val <= 1) {
        return (root.val == result) ? 0 : 1;
    } else {
        int leftOperations = minOperations(root.left, root.val == 4 ? result ^ 1 : result);
        int rightOperations = minOperations(root.right, root.val == 4 ? result ^ 1 : result);
        if (root.val == 3) {
            return Math.min(leftOperations, rightOperations);
        } else if (root.val == 2) {
            return Math.max(leftOperations, rightOperations);
        } else {
            return leftOperations + rightOperations;
        }
    }
}
```
For each node, we check its value.
- If the node is a leaf node, return 0 if its value matches `result`, else return 1 (which means one flip operation is needed).
- If the node is a non-leaf node, recursively calculate the minimum operations needed to make its left and right children evaluate to the desired result based on the given boolean operation, and return the total minimum operations needed. For AND operation, return the minimum of left and right operations. For OR operation, return the maximum of left and right operations. For XOR operation, return the summation of left and right operations with exclusive OR applied on the result.

## A solution in C++

```cpp
class Node {
public:
    int val;
    Node* left;
    Node* right;
};

int minOperations(Node* root, int result) {
    if (root == nullptr) {
        return 0;
    }
    if (root->val <= 1) {
        return (root->val == result) ? 0 : 1;
    } else {
        int leftOperations = minOperations(root->left, root->val == 4 ? result ^ 1 : result);
        int rightOperations = minOperations(root->right, root->val == 4 ? result ^ 1 : result);
        if (root->val == 3) {
            return min(leftOperations, rightOperations);
        } else if (root->val == 2) {
            return max(leftOperations, rightOperations);
        } else {
            return leftOperations + rightOperations;
        }
    }
}
```
For each node, we check its value.
- If the node is a leaf node, return 0 if its value matches `result`, else return 1 (which means one flip operation is needed).
- If the node is a non-leaf node, recursively calculate the minimum operations needed to make its left and right children evaluate to the desired result based on the given boolean operation, and return the total minimum operations needed. For AND operation, return the minimum of left and right operations. For OR operation, return the maximum of left and right operations. For XOR operation, return the summation of left and right operations with exclusive OR applied on the result.

## A solution in Python

```python
class Node:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def min_operations(root, result):
    if root is None:
        return 0
    if root.val <= 1:
        return 0 if root.val == result else 1
    else:
        left_operations = min_operations(root.left, result ^ 1 if root.val == 4 else result)
        right_operations = min_operations(root.right, result ^ 1 if root.val == 4 else result)
        if root.val == 3:
            return min(left_operations, right_operations)
        elif root.val == 2:
            return max(left_operations, right_operations)
        else:
            return left_operations + right_operations
```
For each node, we check its value.
- If the node is a leaf node, return 0 if its value matches `result`, else return 1 (which means one flip operation is needed).
- If the node is a non-leaf node, recursively calculate the minimum operations needed to make its left and right children evaluate to the desired result based on the given boolean operation, and return the total minimum operations needed. For AND operation, return the minimum of left and right operations. For OR operation, return the maximum of left and right operations. For XOR operation, return the summation of left and right operations with exclusive OR applied on the result.

## A solution in Javascript

```javascript
class Node {
    constructor(val = 0, left = null, right = null) {
        this.val = val
        this.left = left
        this.right = right
    }
}

function minOperations(root, result) {
    if (!root) {
        return 0;
    }
    if (root.val <= 1) {
        return (root.val === result) ? 0 : 1;
    } else {
        let leftOperations = minOperations(root.left, root.val === 4 ? result ^ 1 : result);
        let rightOperations = minOperations(root.right, root.val === 4 ? result ^ 1 : result);
        if (root.val === 3) {
            return Math.min(leftOperations, rightOperations);
        } else if (root.val === 2) {
            return Math.max(leftOperations, rightOperations);
        } else {
            return leftOperations + rightOperations;
        }
    }
}
```
For each node, we check its value.
- If the node is a leaf node, return 0 if its value matches `result`, else return 1 (which means one flip operation is needed).
- If the node is a non-leaf node, recursively calculate the minimum operations needed to make its left and right children evaluate to the desired result based on the given boolean operation, and return the total minimum operations needed. For AND operation, return the minimum of left and right operations. For OR operation, return the maximum of left and right operations. For XOR operation, return the summation of left and right operations with exclusive OR applied on the result.


# Count Asterisks

- slug: count-asterisks
- difficulty: Easy

You are given a string `s`, where every **two** consecutive vertical bars `'|'` are grouped into a **pair**. In other words, the 1st and 2nd `'|'` make a pair, the 3rd and 4th `'|'` make a pair, and so forth.

Return _the number of_ `'*'` _in_ `s`_, **excluding** the_ `'*'` _between each pair of_ `'|'`.

**Note** that each `'|'` will belong to **exactly** one pair.

**Example 1:**

**Input:** s =  "l|\*e\*et|c\*\*o|\*de| "
**Output:** 2
**Explanation:** The considered characters are underlined:  "l|\*e\*et|c\*\*o|\*de| ".
The characters between the first and second '|' are excluded from the answer.
Also, the characters between the third and fourth '|' are excluded from the answer.
There are 2 asterisks considered. Therefore, we return 2.

**Example 2:**

**Input:** s =  "iamprogrammer "
**Output:** 0
**Explanation:** In this example, there are no asterisks in s. Therefore, we return 0.

**Example 3:**

**Input:** s =  "yo|uar|e\*\*|b|e\*\*\*au|tifu|l "
**Output:** 5
**Explanation:** The considered characters are underlined:  "yo|uar|e\*\*|b|e\*\*\*au|tifu|l ". There are 5 asterisks considered. Therefore, we return 5.

**Constraints:**

*   `1 <= s.length <= 1000`
*   `s` consists of lowercase English letters, vertical bars `'|'`, and asterisks `'*'`.
*   `s` contains an **even** number of vertical bars `'|'`.

## A solution in Java

```java
public int countStarsExceptBetweenPair(String s) {
    int count = 0;
    int pipeCount = 0;

    for (char c : s.toCharArray()) {
        if (c == '|') {
            pipeCount++;
        } else if (c == '*' && pipeCount % 2 == 0) {
            count++;
        }
    }

    return count;
}
```
The algorithm loops through the string with a simple for loop iterating on characters. It keeps track of the number of pipes encountered (pipeCount) and the total count of stars. If a pipe is encountered, increment pipeCount. If a star is encountered and pipeCount is even, increment the count. This condition (pipeCount % 2 == 0) ensures we are not considering stars between a pair of vertical bars. Finally, return the count of stars after processing the entire string.

## A solution in C++

```cpp
int countStarsExceptBetweenPair(const std::string& s) {
    int count = 0;
    int pipeCount = 0;

    for (char c : s) {
        if (c == '|') {
            pipeCount++;
        } else if (c == '*' && pipeCount % 2 == 0) {
            count++;
        }
    }

    return count;
}
```
The algorithm loops through the string with a simple for loop iterating on characters. It keeps track of the number of pipes encountered (pipeCount) and the total count of stars. If a pipe is encountered, increment pipeCount. If a star is encountered and pipeCount is even, increment the count. This condition (pipeCount % 2 == 0) ensures we are not considering stars between a pair of vertical bars. Finally, return the count of stars after processing the entire string.

## A solution in Python

```python
def count_stars_except_between_pair(s: str) -> int:
    count = 0
    pipe_count = 0

    for c in s:
        if c == '|':
            pipe_count += 1
        elif c == '*' and pipe_count % 2 == 0:
            count += 1

    return count
```
The algorithm loops through the string with a simple for loop iterating on characters. It keeps track of the number of pipes encountered (pipeCount) and the total count of stars. If a pipe is encountered, increment pipeCount. If a star is encountered and pipeCount is even, increment the count. This condition (pipeCount % 2 == 0) ensures we are not considering stars between a pair of vertical bars. Finally, return the count of stars after processing the entire string.

## A solution in Javascript

```javascript
function countStarsExceptBetweenPair(s) {
    let count = 0;
    let pipeCount = 0;

    for (let c of s) {
        if (c === '|') {
            pipeCount++;
        } else if (c === '*' && pipeCount % 2 === 0) {
            count++;
        }
    }

    return count;
}
```
The algorithm loops through the string with a simple for loop iterating on characters. It keeps track of the number of pipes encountered (pipeCount) and the total count of stars. If a pipe is encountered, increment pipeCount. If a star is encountered and pipeCount is even, increment the count. This condition (pipeCount % 2 == 0) ensures we are not considering stars between a pair of vertical bars. Finally, return the count of stars after processing the entire string.


# Count Unreachable Pairs of Nodes in an Undirected Graph

- slug: count-unreachable-pairs-of-nodes-in-an-undirected-graph
- difficulty: Medium

You are given an integer `n`. There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi`.

Return _the **number of pairs** of different nodes that are **unreachable** from each other_.

**Example 1:**

**Input:** n = 3, edges = \[\[0,1\],\[0,2\],\[1,2\]\]
**Output:** 0
**Explanation:** There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.

**Example 2:**

**Input:** n = 7, edges = \[\[0,2\],\[0,5\],\[2,4\],\[1,6\],\[5,4\]\]
**Output:** 14
**Explanation:** There are 14 pairs of nodes that are unreachable from each other:
\[\[0,1\],\[0,3\],\[0,6\],\[1,2\],\[1,3\],\[1,4\],\[1,5\],\[2,3\],\[2,6\],\[3,4\],\[3,5\],\[3,6\],\[4,6\],\[5,6\]\].
Therefore, we return 14.

**Constraints:**

*   `1 <= n <= 105`
*   `0 <= edges.length <= 2 * 105`
*   `edges[i].length == 2`
*   `0 <= ai, bi < n`
*   `ai != bi`
*   There are no repeated edges.

## A solution in Java

```java
public int countHillsValleys(int[] nums) {
    int count = 0;
    for (int i = 1; i < nums.length - 1; i++) {
        if ((nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) || (nums[i] < nums[i - 1] && nums[i] < nums[i + 1])) {
            count++;
        }
    }
    return count;
}
```
The algorithm iterates through the array from the second element to the second-last element. For each element, it checks whether it is part of a hill or a valley. This is done by comparing the current element with its left and right neighbors. If the element is larger than both neighbors, it is part of a hill; if it is smaller than both neighbors, it is part of a valley. The count is incremented when the element is part of a hill or a valley. This process is repeated for all elements in the specified range. Finally, the count of hills and valleys is returned.

## A solution in C++

```cpp
int count_hills_valleys(vector<int>& nums) {
    int count = 0;
    for (int i = 1; i < nums.size() - 1; ++i) {
        if ((nums[i] > nums[i-1] && nums[i] > nums[i+1]) || (nums[i] < nums[i-1] && nums[i] < nums[i+1])) {
            count++;
        }
    }
    return count;
}
```
The algorithm iterates through the array from the second element to the second-last element. For each element, it checks whether it is part of a hill or a valley. This is done by comparing the current element with its left and right neighbors. If the element is larger than both neighbors, it is part of a hill; if it is smaller than both neighbors, it is part of a valley. The count is incremented when the element is part of a hill or a valley. This process is repeated for all elements in the specified range. Finally, the count of hills and valleys is returned.

## A solution in Python

```python
def count_hills_valleys(nums):
    count = 0
    for i in range(1, len(nums) - 1):
        if (nums[i] > nums[i - 1] and nums[i] > nums[i + 1]) or (nums[i] < nums[i - 1] and nums[i] < nums[i + 1]):
            count += 1
    return count
```
The algorithm iterates through the array from the second element to the second-last element. For each element, it checks whether it is part of a hill or a valley. This is done by comparing the current element with its left and right neighbors. If the element is larger than both neighbors, it is part of a hill; if it is smaller than both neighbors, it is part of a valley. The count is incremented when the element is part of a hill or a valley. This process is repeated for all elements in the specified range. Finally, the count of hills and valleys is returned.

## A solution in Javascript

```javascript
function countHillsValleys(nums) {
    let count = 0;
    for (let i = 1; i < nums.length - 1; i++) {
        if ((nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) || (nums[i] < nums[i - 1] && nums[i] < nums[i + 1])) {
            count++;
        }
    }
    return count;
}
```
The algorithm iterates through the array from the second element to the second-last element. For each element, it checks whether it is part of a hill or a valley. This is done by comparing the current element with its left and right neighbors. If the element is larger than both neighbors, it is part of a hill; if it is smaller than both neighbors, it is part of a valley. The count is incremented when the element is part of a hill or a valley. This process is repeated for all elements in the specified range. Finally, the count of hills and valleys is returned.


# Maximum XOR After Operations

- slug: maximum-xor-after-operations
- difficulty: Medium

You are given a **0-indexed** integer array `nums`. In one operation, select **any** non-negative integer `x` and an index `i`, then **update** `nums[i]` to be equal to `nums[i] AND (nums[i] XOR x)`.

Note that `AND` is the bitwise AND operation and `XOR` is the bitwise XOR operation.

Return _the **maximum** possible bitwise XOR of all elements of_ `nums` _after applying the operation **any number** of times_.

**Example 1:**

**Input:** nums = \[3,2,4,6\]
**Output:** 7
**Explanation:** Apply the operation with x = 4 and i = 3, num\[3\] = 6 AND (6 XOR 4) = 6 AND 2 = 2.
Now, nums = \[3, 2, 4, 2\] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.
It can be shown that 7 is the maximum possible bitwise XOR.
Note that other operations may be used to achieve a bitwise XOR of 7.

**Example 2:**

**Input:** nums = \[1,2,3,9,2\]
**Output:** 11
**Explanation:** Apply the operation zero times.
The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.
It can be shown that 11 is the maximum possible bitwise XOR.

**Constraints:**

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

## A solution in Java

```java
int countCollisions(String directions) {
    int collisionCount = 0, leftCount = 0;

    for (char direction : directions.toCharArray()) {
        if (direction == 'L') {
            leftCount++;
        } else if (direction == 'R') {
            collisionCount += leftCount;
        }
    }

    return collisionCount;
}
```
The algorithm iterates through the `directions` string, counting the number of 'L' characters (left moving cars) as `leftCount`. When a 'R' character (right moving car) is encountered, the number of collisions for that right moving car is equal to the current value of `leftCount` (as all those left moving cars will collide with the current right moving car). This value is added to `collisionCount`. The final value of `collisionCount` after iterating through the string is the total number of collisions that will happen on the road.

## A solution in C++

```cpp
int countCollisions(string directions) {
    int collisionCount = 0, leftCount = 0;

    for (char direction : directions) {
        if (direction == 'L') {
            leftCount++;
        } else if (direction == 'R') {
            collisionCount += leftCount;
        }
    }

    return collisionCount;
}
```
The algorithm iterates through the `directions` string, counting the number of 'L' characters (left moving cars) as `leftCount`. When a 'R' character (right moving car) is encountered, the number of collisions for that right moving car is equal to the current value of `leftCount` (as all those left moving cars will collide with the current right moving car). This value is added to `collisionCount`. The final value of `collisionCount` after iterating through the string is the total number of collisions that will happen on the road.

## A solution in Python

```python
def count_collisions(directions: str) -> int:
    collision_count = 0
    left_count = 0

    for direction in directions:
        if direction == 'L':
            left_count += 1
        elif direction == 'R':
            collision_count += left_count

    return collision_count
```
The algorithm iterates through the `directions` string, counting the number of 'L' characters (left moving cars) as `leftCount`. When a 'R' character (right moving car) is encountered, the number of collisions for that right moving car is equal to the current value of `leftCount` (as all those left moving cars will collide with the current right moving car). This value is added to `collisionCount`. The final value of `collisionCount` after iterating through the string is the total number of collisions that will happen on the road.

## A solution in Javascript

```javascript
function countCollisions(directions) {
    let collisionCount = 0;
    let leftCount = 0;

    for (let direction of directions) {
        if (direction === 'L') {
            leftCount++;
        } else if (direction === 'R') {
            collisionCount += leftCount;
        }
    }

    return collisionCount;
}
```
The algorithm iterates through the `directions` string, counting the number of 'L' characters (left moving cars) as `leftCount`. When a 'R' character (right moving car) is encountered, the number of collisions for that right moving car is equal to the current value of `leftCount` (as all those left moving cars will collide with the current right moving car). This value is added to `collisionCount`. The final value of `collisionCount` after iterating through the string is the total number of collisions that will happen on the road.