# Pseudo-Palindromic Paths in a Binary Tree

- slug: pseudo-palindromic-paths-in-a-binary-tree
- difficulty: Medium

Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be **pseudo-palindromic** if at least one permutation of the node values in the path is a palindrome.

_Return the number of **pseudo-palindromic** paths going from the root node to leaf nodes._

**Example 1:**

**Input:** root = \[2,3,1,3,1,null,1\]
**Output:** 2
**Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path \[2,3,3\], the green path \[2,1,1\], and the path \[2,3,1\]. Among these paths only red path and green path are pseudo-palindromic paths since the red path \[2,3,3\] can be rearranged in \[3,2,3\] (palindrome) and the green path \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome).

**Example 2:**

**Input:** root = \[2,1,1,1,3,null,null,null,null,null,1\]
**Output:** 1
**Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path \[2,1,1\], the path \[2,1,3,1\], and the path \[2,1\]. Among these paths only the green path is pseudo-palindromic since \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome).

**Example 3:**

**Input:** root = \[9\]
**Output:** 1

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 105]`.
*   `1 <= Node.val <= 9`

## A solution in Java

```java
public int minDifficulty(int[] jobDifficulty, int d) {
    int n = jobDifficulty.length;
    if (n < d) return -1;
    int[][] dp = new int[d][n];

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

    for (int i = 1; i < d; ++i) {
        for (int j = i; j < n; ++j) {
            int maxD = jobDifficulty[j];
            for (int k = j; k >= i; --k) {
                maxD = Math.max(maxD, jobDifficulty[k]);
                dp[i][j] = Math.min(dp[i][j], dp[i-1][k-1] + maxD);
            }
        }
    }
    return dp[d-1][n-1];
}
```
We use a dynamic programming approach to solve this problem. The `dp[i][j]` represents the minimum difficulty of a job schedule for the first `j+1` jobs in `i+1` days. We first initialize the difficulty for the first day. Then, for each day from 1 to `d - 1`, we loop through each job `j` starting from the current day index `i`. We find the maximum difficulty for each day by iterating through the jobs in reverse order (from the last job to the start of the day) and maintain a temporary maximum difficulty during this iteration. Finally, we find the minimum of the current difficulty at `dp[i][j]` and the previous day's difficulty plus the temporary maximum difficulty.

After the nested loops, the result can be retrieved from `dp[d-1][n-1]`.

## A solution in C++

```cpp
#include <vector>
#include <algorithm>
#include <limits.h>

int minDifficulty(std::vector<int>& jobDifficulty, int d) {
    int n = jobDifficulty.size();
    if (n < d) return -1;
    std::vector<std::vector<int>> dp(d, std::vector<int>(n, INT_MAX));

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

    for (int i = 1; i < d; ++i) {
        for (int j = i; j < n; ++j) {
            int maxD = jobDifficulty[j];
            for (int k = j; k >= i; --k) {
                maxD = std::max(maxD, jobDifficulty[k]);
                dp[i][j] = std::min(dp[i][j], dp[i-1][k-1] + maxD);
            }
        }
    }
    return dp[d-1][n-1];
}
```
We use a dynamic programming approach to solve this problem. The `dp[i][j]` represents the minimum difficulty of a job schedule for the first `j+1` jobs in `i+1` days. We first initialize the difficulty for the first day. Then, for each day from 1 to `d - 1`, we loop through each job `j` starting from the current day index `i`. We find the maximum difficulty for each day by iterating through the jobs in reverse order (from the last job to the start of the day) and maintain a temporary maximum difficulty during this iteration. Finally, we find the minimum of the current difficulty at `dp[i][j]` and the previous day's difficulty plus the temporary maximum difficulty.

After the nested loops, the result can be retrieved from `dp[d-1][n-1]`.

## A solution in Python

```python
def minDifficulty(jobDifficulty, d):
    n = len(jobDifficulty)
    if n < d: return -1
    dp = [[float("inf")] * n for _ in range(d)]

    dp[0][0] = jobDifficulty[0]
    for i in range(1, n):
        dp[0][i] = max(dp[0][i-1], jobDifficulty[i])

    for i in range(1, d):
        for j in range(i, n):
            maxD = jobDifficulty[j]
            for k in range(j, i - 1, -1):
                maxD = max(maxD, jobDifficulty[k])
                dp[i][j] = min(dp[i][j], dp[i-1][k-1] + maxD)

    return dp[d-1][n-1]
```
We use a dynamic programming approach to solve this problem. The `dp[i][j]` represents the minimum difficulty of a job schedule for the first `j+1` jobs in `i+1` days. We first initialize the difficulty for the first day. Then, for each day from 1 to `d - 1`, we loop through each job `j` starting from the current day index `i`. We find the maximum difficulty for each day by iterating through the jobs in reverse order (from the last job to the start of the day) and maintain a temporary maximum difficulty during this iteration. Finally, we find the minimum of the current difficulty at `dp[i][j]` and the previous day's difficulty plus the temporary maximum difficulty.

After the nested loops, the result can be retrieved from `dp[d-1][n-1]`.

## A solution in Javascript

```javascript
function minDifficulty(jobDifficulty, d) {
    let n = jobDifficulty.length;
    if (n < d) return -1;
    let dp = Array.from({ length: d }, () => new Array(n).fill(Infinity));

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

    for (let i = 1; i < d; ++i) {
        for (let j = i; j < n; ++j) {
            let maxD = jobDifficulty[j];
            for (let k = j; k >= i; --k) {
                maxD = Math.max(maxD, jobDifficulty[k]);
                dp[i][j] = Math.min(dp[i][j], dp[i-1][k-1] + maxD);
            }
        }
    }
    return dp[d-1][n-1];
}
```
We use a dynamic programming approach to solve this problem. The `dp[i][j]` represents the minimum difficulty of a job schedule for the first `j+1` jobs in `i+1` days. We first initialize the difficulty for the first day. Then, for each day from 1 to `d - 1`, we loop through each job `j` starting from the current day index `i`. We find the maximum difficulty for each day by iterating through the jobs in reverse order (from the last job to the start of the day) and maintain a temporary maximum difficulty during this iteration. Finally, we find the minimum of the current difficulty at `dp[i][j]` and the previous day's difficulty plus the temporary maximum difficulty.

After the nested loops, the result can be retrieved from `dp[d-1][n-1]`.


# Max Dot Product of Two Subsequences

- slug: max-dot-product-of-two-subsequences
- difficulty: Hard

Given two arrays `nums1` and `nums2`.

Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length.

A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, `[2,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,5,3]` is not).

**Example 1:**

**Input:** nums1 = \[2,1,-2,5\], nums2 = \[3,0,-6\]
**Output:** 18
**Explanation:** Take subsequence \[2,-2\] from nums1 and subsequence \[3,-6\] from nums2.
Their dot product is (2\*3 + (-2)\*(-6)) = 18.

**Example 2:**

**Input:** nums1 = \[3,-2\], nums2 = \[2,-6,7\]
**Output:** 21
**Explanation:** Take subsequence \[3\] from nums1 and subsequence \[7\] from nums2.
Their dot product is (3\*7) = 21.

**Example 3:**

**Input:** nums1 = \[-1,-1\], nums2 = \[1,1\]
**Output:** -1
**Explanation:** Take subsequence \[-1\] from nums1 and subsequence \[1\] from nums2.
Their dot product is -1.

**Constraints:**

*   `1 <= nums1.length, nums2.length <= 500`
*   `-1000 <= nums1[i], nums2[i] <= 1000`

## A solution in Java

```java
import java.util.Arrays;
import java.util.Comparator;

public int[] sortByBits(int[] arr) {
    Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);
    Arrays.sort(boxedArr, new Comparator<Integer>() {
        @Override
        public int compare(Integer a, Integer b) {
            int count_a = Integer.bitCount(a);
            int count_b = Integer.bitCount(b);

            if (count_a == count_b) {
                return a - b;
            }
            return count_a - count_b;
        }
    });

    return Arrays.stream(boxedArr).mapToInt(Integer::intValue).toArray();
}
```
The basic algorithm for solving this problem is to use a sorting algorithm that takes a custom comparator function. This custom comparator function is responsible for sorting the integers based on the number of 1's in their binary representation.

For C++, the `sort()` function and `__builtin_popcount()` function from the `<algorithm>` header are used. The comparator function `compare()` sorts the elements based on the number of 1's and if equal, by ascending value.

For Java, the boxed Integer array is created and the `Arrays.sort()` method is used with a custom anonymous Comparator. The `Integer.bitCount()` method is used to get the number of 1's.

For Python, a lambda function is passed as the `key` argument for the `sorted()` function, where it returns a tuple that contains the number of 1's (calculated using the `bin()` function and `count()` method) and the value itself for sorting purposes.

For JavaScript, a custom function `countOnes()` is implemented to count the number of 1's in each number. The `arr.sort()` method is used with an anonymous comparator function that calculates the difference in 1's and the difference in value if the number of 1's is the same.

## A solution in C++

```cpp
#include <algorithm>

bool compare(int a, int b) {
    int count_a = __builtin_popcount(a);
    int count_b = __builtin_popcount(b);

    if (count_a == count_b) {
        return a < b;
    }
    return count_a < count_b;
}

vector<int> sortByBits(vector<int>& arr) {
    sort(arr.begin(), arr.end(), compare);
    return arr;
}
```
The basic algorithm for solving this problem is to use a sorting algorithm that takes a custom comparator function. This custom comparator function is responsible for sorting the integers based on the number of 1's in their binary representation.

For C++, the `sort()` function and `__builtin_popcount()` function from the `<algorithm>` header are used. The comparator function `compare()` sorts the elements based on the number of 1's and if equal, by ascending value.

For Java, the boxed Integer array is created and the `Arrays.sort()` method is used with a custom anonymous Comparator. The `Integer.bitCount()` method is used to get the number of 1's.

For Python, a lambda function is passed as the `key` argument for the `sorted()` function, where it returns a tuple that contains the number of 1's (calculated using the `bin()` function and `count()` method) and the value itself for sorting purposes.

For JavaScript, a custom function `countOnes()` is implemented to count the number of 1's in each number. The `arr.sort()` method is used with an anonymous comparator function that calculates the difference in 1's and the difference in value if the number of 1's is the same.

## A solution in Python

```python
def sortByBits(arr):
    return sorted(arr, key=lambda x: (bin(x).count('1'), x))
```
The basic algorithm for solving this problem is to use a sorting algorithm that takes a custom comparator function. This custom comparator function is responsible for sorting the integers based on the number of 1's in their binary representation.

For C++, the `sort()` function and `__builtin_popcount()` function from the `<algorithm>` header are used. The comparator function `compare()` sorts the elements based on the number of 1's and if equal, by ascending value.

For Java, the boxed Integer array is created and the `Arrays.sort()` method is used with a custom anonymous Comparator. The `Integer.bitCount()` method is used to get the number of 1's.

For Python, a lambda function is passed as the `key` argument for the `sorted()` function, where it returns a tuple that contains the number of 1's (calculated using the `bin()` function and `count()` method) and the value itself for sorting purposes.

For JavaScript, a custom function `countOnes()` is implemented to count the number of 1's in each number. The `arr.sort()` method is used with an anonymous comparator function that calculates the difference in 1's and the difference in value if the number of 1's is the same.

## A solution in Javascript

```javascript
function sortByBits(arr) {
    function countOnes(n) {
        let count = 0;
        while (n > 0) {
            count += n & 1;
            n >>= 1;
        }
        return count;
    }

    return arr.sort((a, b) => {
        let diff = countOnes(a) - countOnes(b);
        return diff !== 0 ? diff : a - b;
    });
}
```
The basic algorithm for solving this problem is to use a sorting algorithm that takes a custom comparator function. This custom comparator function is responsible for sorting the integers based on the number of 1's in their binary representation.

For C++, the `sort()` function and `__builtin_popcount()` function from the `<algorithm>` header are used. The comparator function `compare()` sorts the elements based on the number of 1's and if equal, by ascending value.

For Java, the boxed Integer array is created and the `Arrays.sort()` method is used with a custom anonymous Comparator. The `Integer.bitCount()` method is used to get the number of 1's.

For Python, a lambda function is passed as the `key` argument for the `sorted()` function, where it returns a tuple that contains the number of 1's (calculated using the `bin()` function and `count()` method) and the value itself for sorting purposes.

For JavaScript, a custom function `countOnes()` is implemented to count the number of 1's in each number. The `arr.sort()` method is used with an anonymous comparator function that calculates the difference in 1's and the difference in value if the number of 1's is the same.


# Make Two Arrays Equal by Reversing Subarrays

- slug: make-two-arrays-equal-by-reversing-subarrays
- difficulty: Easy

You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.

Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.

**Example 1:**

**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.

**Example 2:**

**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.

**Example 3:**

**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.

**Constraints:**

*   `target.length == arr.length`
*   `1 <= target.length <= 1000`
*   `1 <= target[i] <= 1000`
*   `1 <= arr[i] <= 1000`

## A solution in Java

```java
public int numberOfSubstrings(String s) {
    int res = 0, left = 0;
    int[] count = new int[3];

    for (int right = 0; right < s.length(); right++) {
        count[s.charAt(right) - 'a']++;

        while (count[0] > 0 && count[1] > 0 && count[2] > 0) {
            count[s.charAt(left++) - 'a']--;
        }

        res += left;
    }

    return res;
}
```
1. Initialize three pointers `res`, `i` (or `left`), and a count list, where `res` is the result of total numbers of substrings containing a, b, and c.
2. Iterate through the string `s`, increment the count of the current character.
3. Use a while loop inside the iteration to check if all characters' count values are greater than 0.
4. If all are greater than 0, continuously decrease the count of the character at the current index `i` while incrementing the `i`.
5. For each iteration, increase the result `res` by `i` (or `left`).
6. Return the result `res`.

The algorithm uses a sliding window method to keep track of the substrings. The complexity is O(N), where N is the length of the string s.

## A solution in C++

```cpp
int numberOfSubstrings(string s) {
    int res = 0, i = 0;
    vector<int> count(3, 0);

    for (int j = 0; j < s.length(); j++) {
        count[s[j] - 'a']++;

        while(count[0] > 0 && count[1] > 0 && count[2] > 0) {
            count[s[i++] - 'a']--;
        }

        res += i;
    }

    return res;
}
```
1. Initialize three pointers `res`, `i` (or `left`), and a count list, where `res` is the result of total numbers of substrings containing a, b, and c.
2. Iterate through the string `s`, increment the count of the current character.
3. Use a while loop inside the iteration to check if all characters' count values are greater than 0.
4. If all are greater than 0, continuously decrease the count of the character at the current index `i` while incrementing the `i`.
5. For each iteration, increase the result `res` by `i` (or `left`).
6. Return the result `res`.

The algorithm uses a sliding window method to keep track of the substrings. The complexity is O(N), where N is the length of the string s.

## A solution in Python

```python
def numberOfSubstrings(s: str) -> int:
    res, i, count = 0, 0, [0, 0, 0]

    for j, ch in enumerate(s):
        count[ord(ch) - ord('a')] += 1

        while count[0] > 0 and count[1] > 0 and count[2] > 0:
            count[ord(s[i]) - ord('a')] -= 1
            i += 1

        res += i

    return res
```
1. Initialize three pointers `res`, `i` (or `left`), and a count list, where `res` is the result of total numbers of substrings containing a, b, and c.
2. Iterate through the string `s`, increment the count of the current character.
3. Use a while loop inside the iteration to check if all characters' count values are greater than 0.
4. If all are greater than 0, continuously decrease the count of the character at the current index `i` while incrementing the `i`.
5. For each iteration, increase the result `res` by `i` (or `left`).
6. Return the result `res`.

The algorithm uses a sliding window method to keep track of the substrings. The complexity is O(N), where N is the length of the string s.

## A solution in Javascript

```javascript
function numberOfSubstrings(s) {
    let res = 0, left = 0;
    let count = [0, 0, 0];

    for (let right = 0; right < s.length; right++) {
        count[s.charCodeAt(right) - 'a'.charCodeAt(0)]++;

        while (count[0] > 0 && count[1] > 0 && count[2] > 0) {
            count[s.charCodeAt(left) - 'a'.charCodeAt(0)]--;
            left++;
        }

        res += left;
    }

    return res;
}
```
1. Initialize three pointers `res`, `i` (or `left`), and a count list, where `res` is the result of total numbers of substrings containing a, b, and c.
2. Iterate through the string `s`, increment the count of the current character.
3. Use a while loop inside the iteration to check if all characters' count values are greater than 0.
4. If all are greater than 0, continuously decrease the count of the character at the current index `i` while incrementing the `i`.
5. For each iteration, increase the result `res` by `i` (or `left`).
6. Return the result `res`.

The algorithm uses a sliding window method to keep track of the substrings. The complexity is O(N), where N is the length of the string s.


# Check If a String Contains All Binary Codes of Size K

- slug: check-if-a-string-contains-all-binary-codes-of-size-k
- difficulty: Medium

Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.

**Example 1:**

**Input:** s =  "00110110 ", k = 2
**Output:** true
**Explanation:** The binary codes of length 2 are  "00 ",  "01 ",  "10 " and  "11 ". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.

**Example 2:**

**Input:** s =  "0110 ", k = 1
**Output:** true
**Explanation:** The binary codes of length 1 are  "0 " and  "1 ", it is clear that both exist as a substring.

**Example 3:**

**Input:** s =  "0110 ", k = 2
**Output:** false
**Explanation:** The binary code  "00 " is of length 2 and does not exist in the array.

**Constraints:**

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

## A solution in Java

```java
int countOrders(int n) {
    long MOD = 1000000007;
    long ans = 1;
    for (int i = 1; i <= n; ++i) {
        ans = ans * (2 * i - 1) * i % MOD;
    }
    return (int) ans;
}
```
We need to arrange n pickup and n delivery services in a valid order. For the first order, we have 1 pickup and 1 delivery, i.e., 1 possible arrangement. For the second order, we have 3 possible spots for its pickup, as it must come before its delivery, and 2 spots for its delivery service (P = pickup, D = delivery):

- P2P1D1D2
- P1P2D1D2
- P1D1P2D2

This is (2 * 1 - 1) * 2 = 3 possible arrangements. For the third order, there are (2 * 2 - 1) * 3 possible spots for its pickup and 3 spots for its delivery, giving a total of 5 * 3 = 15 arrangements. Notice that this follows the equation: ans = ans * (2 * i - 1) * i. We iterate through all values from 1 to n and update ans with the mentioned equation. Finally, return the ans modulo 10^9 + 7 to avoid large numbers. This is a Time complexity O(n) solution.

## A solution in C++

```cpp
int countOrders(int n) {
    long long MOD = 1e9 + 7;
    long long ans = 1;
    for (int i = 1; i <= n; ++i) {
        ans = ans * (2 * i - 1) * i % MOD;
    }
    return ans;
}
```
We need to arrange n pickup and n delivery services in a valid order. For the first order, we have 1 pickup and 1 delivery, i.e., 1 possible arrangement. For the second order, we have 3 possible spots for its pickup, as it must come before its delivery, and 2 spots for its delivery service (P = pickup, D = delivery):

- P2P1D1D2
- P1P2D1D2
- P1D1P2D2

This is (2 * 1 - 1) * 2 = 3 possible arrangements. For the third order, there are (2 * 2 - 1) * 3 possible spots for its pickup and 3 spots for its delivery, giving a total of 5 * 3 = 15 arrangements. Notice that this follows the equation: ans = ans * (2 * i - 1) * i. We iterate through all values from 1 to n and update ans with the mentioned equation. Finally, return the ans modulo 10^9 + 7 to avoid large numbers. This is a Time complexity O(n) solution.

## A solution in Python

```python
def countOrders(n: int) -> int:
    MOD = 10**9 + 7
    ans = 1
    for i in range(1, n + 1):
        ans = ans * (2 * i - 1) * i % MOD
    return ans
```
We need to arrange n pickup and n delivery services in a valid order. For the first order, we have 1 pickup and 1 delivery, i.e., 1 possible arrangement. For the second order, we have 3 possible spots for its pickup, as it must come before its delivery, and 2 spots for its delivery service (P = pickup, D = delivery):

- P2P1D1D2
- P1P2D1D2
- P1D1P2D2

This is (2 * 1 - 1) * 2 = 3 possible arrangements. For the third order, there are (2 * 2 - 1) * 3 possible spots for its pickup and 3 spots for its delivery, giving a total of 5 * 3 = 15 arrangements. Notice that this follows the equation: ans = ans * (2 * i - 1) * i. We iterate through all values from 1 to n and update ans with the mentioned equation. Finally, return the ans modulo 10^9 + 7 to avoid large numbers. This is a Time complexity O(n) solution.

## A solution in Javascript

```javascript
function countOrders(n) {
    let MOD = 1e9 + 7;
    let ans = 1;
    for (let i = 1; i <= n; ++i) {
        ans = ans * (2 * i - 1) * i % MOD;
    }
    return ans;
}
```
We need to arrange n pickup and n delivery services in a valid order. For the first order, we have 1 pickup and 1 delivery, i.e., 1 possible arrangement. For the second order, we have 3 possible spots for its pickup, as it must come before its delivery, and 2 spots for its delivery service (P = pickup, D = delivery):

- P2P1D1D2
- P1P2D1D2
- P1D1P2D2

This is (2 * 1 - 1) * 2 = 3 possible arrangements. For the third order, there are (2 * 2 - 1) * 3 possible spots for its pickup and 3 spots for its delivery, giving a total of 5 * 3 = 15 arrangements. Notice that this follows the equation: ans = ans * (2 * i - 1) * i. We iterate through all values from 1 to n and update ans with the mentioned equation. Finally, return the ans modulo 10^9 + 7 to avoid large numbers. This is a Time complexity O(n) solution.


# Course Schedule IV

- slug: course-schedule-iv
- difficulty: Medium

There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`.

*   For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.

Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`.

You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not.

Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._

**Example 1:**

**Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\]
**Output:** \[false,true\]
**Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.

**Example 2:**

**Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\]
**Output:** \[false,false\]
**Explanation:** There are no prerequisites, and each course is independent.

**Example 3:**

**Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\]
**Output:** \[true,true\]

**Constraints:**

*   `2 <= numCourses <= 100`
*   `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)`
*   `prerequisites[i].length == 2`
*   `0 <= ai, bi <= n - 1`
*   `ai != bi`
*   All the pairs `[ai, bi]` are **unique**.
*   The prerequisites graph has no cycles.
*   `1 <= queries.length <= 104`
*   `0 <= ui, vi <= n - 1`
*   `ui != vi`

## A solution in Java

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

public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
    boolean[][] adj_matrix = new boolean[numCourses][numCourses];
    for (int[] pre : prerequisites) {
        adj_matrix[pre[0]][pre[1]] = true;
    }

    for (int k = 0; k < numCourses; k++) {
        for (int i = 0; i < numCourses; i++) {
            for (int j = 0; j < numCourses; j++) {
                adj_matrix[i][j] = adj_matrix[i][j] || (adj_matrix[i][k] && adj_matrix[k][j]);
            }
        }
    }

    List<Boolean> answer = new ArrayList<>();
    for (int[] query : queries) {
        answer.add(adj_matrix[query[0]][query[1]]);
    }
    return answer;
}
```
The algorithm constructs an adjacency matrix of prerequisites. Elements with a value of `true` on [i][j] represent that course i is a prerequisite of course j. After constructing the initial adjacency matrix, we use the Floyd–Warshall algorithm to fill the indirect prerequisites.

After computing the complete adjacency matrix, we iterate through the queries and get the required values from the matrix. If the value at [query[0]][query[1]] is `true`, then course query[0] is a prerequisite of course query[1], it answers the `jth` query. Finally, we return the resulting boolean array with the answers of the queries.

## A solution in C++

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

vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
    vector<vector<bool>> adj_matrix(numCourses, vector<bool>(numCourses, false));
    for (const auto& pre : prerequisites) {
        adj_matrix[pre[0]][pre[1]] = true;
    }

    for (int k = 0; k < numCourses; ++k) {
        for (int i = 0; i < numCourses; ++i) {
            for (int j = 0; j < numCourses; ++j) {
                adj_matrix[i][j] = adj_matrix[i][j] || (adj_matrix[i][k] && adj_matrix[k][j]);
            }
        }
    }

    vector<bool> answer;
    for (const auto& query : queries) {
        answer.push_back(adj_matrix[query[0]][query[1]]);
    }
    return answer;
}
```
The algorithm constructs an adjacency matrix of prerequisites. Elements with a value of `true` on [i][j] represent that course i is a prerequisite of course j. After constructing the initial adjacency matrix, we use the Floyd–Warshall algorithm to fill the indirect prerequisites.

After computing the complete adjacency matrix, we iterate through the queries and get the required values from the matrix. If the value at [query[0]][query[1]] is `true`, then course query[0] is a prerequisite of course query[1], it answers the `jth` query. Finally, we return the resulting boolean array with the answers of the queries.

## A solution in Python

```python
def checkIfPrerequisite(numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
    adj_matrix = [[False] * numCourses for _ in range(numCourses)]
    for pre in prerequisites:
        adj_matrix[pre[0]][pre[1]] = True

    for k in range(numCourses):
        for i in range(numCourses):
            for j in range(numCourses):
                adj_matrix[i][j] = adj_matrix[i][j] or (adj_matrix[i][k] and adj_matrix[k][j])

    return [adj_matrix[query[0]][query[1]] for query in queries]
```
The algorithm constructs an adjacency matrix of prerequisites. Elements with a value of `true` on [i][j] represent that course i is a prerequisite of course j. After constructing the initial adjacency matrix, we use the Floyd–Warshall algorithm to fill the indirect prerequisites.

After computing the complete adjacency matrix, we iterate through the queries and get the required values from the matrix. If the value at [query[0]][query[1]] is `true`, then course query[0] is a prerequisite of course query[1], it answers the `jth` query. Finally, we return the resulting boolean array with the answers of the queries.

## A solution in Javascript

```javascript
function checkIfPrerequisite(numCourses, prerequisites, queries) {
    const adj_matrix = Array.from({ length: numCourses }, () => Array(numCourses).fill(false));
    for (const pre of prerequisites) {
        adj_matrix[pre[0]][pre[1]] = true;
    }

    for (let k = 0; k < numCourses; k++) {
        for (let i = 0; i < numCourses; i++) {
            for (let j = 0; j < numCourses; j++) {
                adj_matrix[i][j] = adj_matrix[i][j] || (adj_matrix[i][k] && adj_matrix[k][j]);
            }
        }
    }

    return queries.map(query => adj_matrix[query[0]][query[1]]);
}
```
The algorithm constructs an adjacency matrix of prerequisites. Elements with a value of `true` on [i][j] represent that course i is a prerequisite of course j. After constructing the initial adjacency matrix, we use the Floyd–Warshall algorithm to fill the indirect prerequisites.

After computing the complete adjacency matrix, we iterate through the queries and get the required values from the matrix. If the value at [query[0]][query[1]] is `true`, then course query[0] is a prerequisite of course query[1], it answers the `jth` query. Finally, we return the resulting boolean array with the answers of the queries.


# Cherry Pickup II

- slug: cherry-pickup-ii
- difficulty: Hard

You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell.

You have two robots that can collect cherries for you:

*   **Robot #1** is located at the **top-left corner** `(0, 0)`, and
*   **Robot #2** is located at the **top-right corner** `(0, cols - 1)`.

Return _the maximum number of cherries collection using both robots by following the rules below_:

*   From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`.
*   When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
*   When both robots stay in the same cell, only one takes the cherries.
*   Both robots cannot move outside of the grid at any moment.
*   Both robots should reach the bottom row in `grid`.

**Example 1:**

**Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\]
**Output:** 24
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.

**Example 2:**

**Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\]
**Output:** 28
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.

**Constraints:**

*   `rows == grid.length`
*   `cols == grid[i].length`
*   `2 <= rows, cols <= 70`
*   `0 <= grid[i][j] <= 100`

## A solution in Java

```java
import java.util.*;

public int[] kWeakestRows(int[][] mat, int k) {
    int m = mat.length;
    int[] result = new int[k];
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);

    for (int i = 0; i < m; ++i) {
        int soldiers = 0;
        for (int val : mat[i]) {
            if (val == 1) {
                soldiers++;
            } else {
                break;
            }
        }
        pq.add(new int[]{soldiers, i});
    }

    for (int i = 0; i < k; ++i) {
        result[i] = pq.poll()[1];
    }
    return result;
}
```
The given problem can be solved by iterating through the matrix and counting the number of 1's (soldiers) in each row. We create a list `soldier_row` (or priority queue in java) of pairs (or arrays) such that pairs first element is the count of 1's and second element is the row index.

Then we sort the list `soldier_row` (not needed in java, as priority queue handles that internally). While sorting, if there is a tie for the number of soldiers, the row index will be the tiebreaker.

Finally, we create an output list by taking indices of the first `k` weakest rows from the sorted list and return that list as our answer.

## A solution in C++

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

using namespace std;

vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
    vector<pair<int, int>> soldier_row;
    for (int i = 0; i < mat.size(); ++i) {
        int soldiers = count(mat[i].begin(), mat[i].end(), 1);
        soldier_row.push_back({soldiers, i});
    }

    sort(soldier_row.begin(), soldier_row.end());

    vector<int> result;
    for (int i = 0; i < k; ++i) {
        result.push_back(soldier_row[i].second);
    }
    return result;
}
```
The given problem can be solved by iterating through the matrix and counting the number of 1's (soldiers) in each row. We create a list `soldier_row` (or priority queue in java) of pairs (or arrays) such that pairs first element is the count of 1's and second element is the row index.

Then we sort the list `soldier_row` (not needed in java, as priority queue handles that internally). While sorting, if there is a tie for the number of soldiers, the row index will be the tiebreaker.

Finally, we create an output list by taking indices of the first `k` weakest rows from the sorted list and return that list as our answer.

## A solution in Python

```python
from typing import List
import heapq

def kWeakestRows(mat: List[List[int]], k: int) -> List[int]:
    soldier_rows = [(row.count(1), i) for i, row in enumerate(mat)]
    heapq.heapify(soldier_rows)
    return [heapq.heappop(soldier_rows)[1] for _ in range(k)]
```
The given problem can be solved by iterating through the matrix and counting the number of 1's (soldiers) in each row. We create a list `soldier_row` (or priority queue in java) of pairs (or arrays) such that pairs first element is the count of 1's and second element is the row index.

Then we sort the list `soldier_row` (not needed in java, as priority queue handles that internally). While sorting, if there is a tie for the number of soldiers, the row index will be the tiebreaker.

Finally, we create an output list by taking indices of the first `k` weakest rows from the sorted list and return that list as our answer.

## A solution in Javascript

```javascript
function kWeakestRows(mat, k) {
    const soldierRows = mat.map((row, i) => [row.reduce((count, val) => count + val, 0), i]);
    soldierRows.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
    return soldierRows.slice(0, k).map(row => row[1]);
}
```
The given problem can be solved by iterating through the matrix and counting the number of 1's (soldiers) in each row. We create a list `soldier_row` (or priority queue in java) of pairs (or arrays) such that pairs first element is the count of 1's and second element is the row index.

Then we sort the list `soldier_row` (not needed in java, as priority queue handles that internally). While sorting, if there is a tie for the number of soldiers, the row index will be the tiebreaker.

Finally, we create an output list by taking indices of the first `k` weakest rows from the sorted list and return that list as our answer.


# Maximum Product of Two Elements in an Array

- slug: maximum-product-of-two-elements-in-an-array
- difficulty: Easy

Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.

**Example 1:**

**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.

**Example 2:**

**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.

**Example 3:**

**Input:** nums = \[3,7\]
**Output:** 12

**Constraints:**

*   `2 <= nums.length <= 500`
*   `1 <= nums[i] <= 10^3`

## A solution in Java

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

public int minSetSize(int[] arr) {
    HashMap<Integer, Integer> count = new HashMap<>();
    for (int value : arr)
        count.put(value, count.getOrDefault(value, 0) + 1);

    ArrayList<Integer> freq = new ArrayList<>(count.values());
    Collections.sort(freq, Collections.reverseOrder());

    int removed = 0, setSize = 0;
    for (int f : freq) {
        removed += f;
        setSize++;
        if (removed * 2 >= arr.length)
            return setSize;
    }

    return 0;
}
```
1. Create a map (or dictionary) to store the count of each unique integer in the input array.
2. Iterate through the input array, incrementing the count for each number in the map.
3. Create an array (or list) of the counts in the map, sorted in descending order.
4. Initialize variables `removed` and `setSize` to zero. `removed` tracks the number of elements removed so far, and `setSize` is the size of the set of integers.
5. Iterate through the sorted count array, adding the count to the `removed` variable and incrementing `setSize`. If the number of `removed` elements is at least half the size of the input array, return `setSize`.
6. If the loop completes without returning, return 0.

## A solution in C++

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

int minSetSize(std::vector<int>& arr) {
    std::unordered_map<int, int> count;
    for (auto value : arr)
        count[value]++;

    std::vector<int> freq;
    for (auto& entry : count)
        freq.push_back(entry.second);

    std::sort(freq.rbegin(), freq.rend());

    int removed = 0, setSize = 0;
    for (auto f : freq) {
        removed += f;
        setSize++;
        if (removed * 2 >= arr.size())
            return setSize;
    }

    return 0;
}
```
1. Create a map (or dictionary) to store the count of each unique integer in the input array.
2. Iterate through the input array, incrementing the count for each number in the map.
3. Create an array (or list) of the counts in the map, sorted in descending order.
4. Initialize variables `removed` and `setSize` to zero. `removed` tracks the number of elements removed so far, and `setSize` is the size of the set of integers.
5. Iterate through the sorted count array, adding the count to the `removed` variable and incrementing `setSize`. If the number of `removed` elements is at least half the size of the input array, return `setSize`.
6. If the loop completes without returning, return 0.

## A solution in Python

```python
from collections import Counter

def minSetSize(arr):
    count = Counter(arr)
    freq = list(count.values())
    freq.sort(reverse=True)

    removed, setSize = 0, 0
    for f in freq:
        removed += f
        setSize += 1
        if removed * 2 >= len(arr):
            return setSize

    return 0
```
1. Create a map (or dictionary) to store the count of each unique integer in the input array.
2. Iterate through the input array, incrementing the count for each number in the map.
3. Create an array (or list) of the counts in the map, sorted in descending order.
4. Initialize variables `removed` and `setSize` to zero. `removed` tracks the number of elements removed so far, and `setSize` is the size of the set of integers.
5. Iterate through the sorted count array, adding the count to the `removed` variable and incrementing `setSize`. If the number of `removed` elements is at least half the size of the input array, return `setSize`.
6. If the loop completes without returning, return 0.

## A solution in Javascript

```javascript
function minSetSize(arr) {
    const count = new Map();
    for (const value of arr)
        count.set(value, (count.get(value) || 0) + 1);

    const freq = Array.from(count.values());
    freq.sort((a, b) => b - a);

    let removed = 0, setSize = 0;
    for (const f of freq) {
        removed += f;
        setSize++;
        if (removed * 2 >= arr.length)
            return setSize;
    }

    return 0;
}
```
1. Create a map (or dictionary) to store the count of each unique integer in the input array.
2. Iterate through the input array, incrementing the count for each number in the map.
3. Create an array (or list) of the counts in the map, sorted in descending order.
4. Initialize variables `removed` and `setSize` to zero. `removed` tracks the number of elements removed so far, and `setSize` is the size of the set of integers.
5. Iterate through the sorted count array, adding the count to the `removed` variable and incrementing `setSize`. If the number of `removed` elements is at least half the size of the input array, return `setSize`.
6. If the loop completes without returning, return 0.


# Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts

- slug: maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
- difficulty: Medium

You are given a rectangular cake of size `h x w` and two arrays of integers `horizontalCuts` and `verticalCuts` where:

*   `horizontalCuts[i]` is the distance from the top of the rectangular cake to the `ith` horizontal cut and similarly, and
*   `verticalCuts[j]` is the distance from the left of the rectangular cake to the `jth` vertical cut.

Return _the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays_ `horizontalCuts` _and_ `verticalCuts`. Since the answer can be a large number, return this **modulo** `109 + 7`.

**Example 1:**

**Input:** h = 5, w = 4, horizontalCuts = \[1,2,4\], verticalCuts = \[1,3\]
**Output:** 4
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.

**Example 2:**

**Input:** h = 5, w = 4, horizontalCuts = \[3,1\], verticalCuts = \[1\]
**Output:** 6
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.

**Example 3:**

**Input:** h = 5, w = 4, horizontalCuts = \[3\], verticalCuts = \[3\]
**Output:** 9

**Constraints:**

*   `2 <= h, w <= 109`
*   `1 <= horizontalCuts.length <= min(h - 1, 105)`
*   `1 <= verticalCuts.length <= min(w - 1, 105)`
*   `1 <= horizontalCuts[i] < h`
*   `1 <= verticalCuts[i] < w`
*   All the elements in `horizontalCuts` are distinct.
*   All the elements in `verticalCuts` are distinct.

## A solution in Java

```java
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    private static final int MOD = 1000000007;

    public int maxProduct(TreeNode root) {
        long total = dfs(root), result = 0;
        return (int) (dfs2(root, total / 2, result, total) % MOD);
    }

    private int dfs(TreeNode root) {
        return root == null ? 0 : root.val + dfs(root.left) + dfs(root.right);
    }

    private long dfs2(TreeNode root, double half, long result, long total) {
        if (root == null) return 0;
        int curSum = root.val + dfs2(root.left, half, result, total) + dfs2(root.right, half, result, total);
        result = Math.max(result, (total - curSum) * curSum);
        return curSum;
    }
}
```
We first find the total sum of the tree by doing a simple DFS traversal. Then, we do another DFS traversal to find the optimal edge to remove to maximize the product of the sums of the two subtrees. In this second DFS traversal, we calculate the sum of the current subtree rooted at the current node, and check if the product of the current subtree sum and the remaining sum (total - current subtree sum) is larger than the current result. If so, we update the result. Finally, we return the result modulo 1e9+7 as required.

## A solution in C++

```cpp
#include<bits/stdc++.h>
using namespace std;

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

class Solution {
public:
    int maxProduct(TreeNode* root) {
        long total = dfs(root), result = 0;
        dfs2(root, total/2, result, total);
        return result % 1000000007;
    }

    int dfs(TreeNode* root) {
        if (!root) return 0;
        return root->val + dfs(root->left) + dfs(root->right);
    }

    int dfs2(TreeNode* root, double half, long& result, long total) {
        if (!root) return 0;
        int curSum = root->val + dfs2(root->left, half, result, total) + dfs2(root->right, half, result, total);
        result = max(result, (total - curSum) * curSum);
        return curSum;
    }
};
```
We first find the total sum of the tree by doing a simple DFS traversal. Then, we do another DFS traversal to find the optimal edge to remove to maximize the product of the sums of the two subtrees. In this second DFS traversal, we calculate the sum of the current subtree rooted at the current node, and check if the product of the current subtree sum and the remaining sum (total - current subtree sum) is larger than the current result. If so, we update the result. Finally, we return the result modulo 1e9+7 as required.

## A solution in Python

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

class Solution:
    def maxProduct(self, root: TreeNode) -> int:
        def dfs(node):
            if not node:
                return 0
            return node.val + dfs(node.left) + dfs(node.right)

        def dfs2(node, half):
            nonlocal result

            if not node:
                return 0
            cur_sum = node.val + dfs2(node.left, half) + dfs2(node.right, half)
            result = max(result, (total - cur_sum) * cur_sum)
            return cur_sum

        total = dfs(root)
        result = 0
        dfs2(root, total / 2)
        return result % (10**9 + 7)
```
We first find the total sum of the tree by doing a simple DFS traversal. Then, we do another DFS traversal to find the optimal edge to remove to maximize the product of the sums of the two subtrees. In this second DFS traversal, we calculate the sum of the current subtree rooted at the current node, and check if the product of the current subtree sum and the remaining sum (total - current subtree sum) is larger than the current result. If so, we update the result. Finally, we return the result modulo 1e9+7 as required.

## A solution in Javascript

```javascript
class TreeNode {
    constructor(val, left, right) {
        this.val = (val === undefined ? 0 : val)
        this.left = (left === undefined ? null : left)
        this.right = (right === undefined ? null : right)
    }
}

var maxProduct = function(root) {
    const mod = BigInt(10 ** 9 + 7);
    let total, result = 0n;

    function dfs(node) {
        if (!node) return 0;
        return node.val + dfs(node.left) + dfs(node.right);
    }

    function dfs2(node) {
        if (!node) return 0;
        let curSum = node.val + dfs2(node.left) + dfs2(node.right);
        result = BigInt(Math.max(Number(result), Number((total - curSum) * curSum)));
        return curSum;
    }

    total = BigInt(dfs(root));
    dfs2(root);
    return Number(result % mod);
};
```
We first find the total sum of the tree by doing a simple DFS traversal. Then, we do another DFS traversal to find the optimal edge to remove to maximize the product of the sums of the two subtrees. In this second DFS traversal, we calculate the sum of the current subtree rooted at the current node, and check if the product of the current subtree sum and the remaining sum (total - current subtree sum) is larger than the current result. If so, we update the result. Finally, we return the result modulo 1e9+7 as required.


# Reorder Routes to Make All Paths Lead to the City Zero

- slug: reorder-routes-to-make-all-paths-lead-to-the-city-zero
- difficulty: Medium

There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.

Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`.

This year, there will be a big event in the capital (city `0`), and many people want to travel to this city.

Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed.

It's **guaranteed** that each city can reach city `0` after reorder.

**Example 1:**

**Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\]
**Output:** 3
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).

**Example 2:**

**Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\]
**Output:** 2
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).

**Example 3:**

**Input:** n = 3, connections = \[\[1,0\],\[2,0\]\]
**Output:** 0

**Constraints:**

*   `2 <= n <= 5 * 104`
*   `connections.length == n - 1`
*   `connections[i].length == 2`
*   `0 <= ai, bi <= n - 1`
*   `ai != bi`

## A solution in Java

```java
import java.util.Arrays;

public int maxJumps(int[] arr, int d) {
    int n = arr.length;
    int[] dp = new int[n];
    Arrays.fill(dp, 1);

    for (int i = 0; i < n; i++) {
        maxJumpsHelper(arr, d, dp, i);
    }

    return Arrays.stream(dp).max().getAsInt();
}

private int maxJumpsHelper(int[] arr, int d, int[] dp, int idx) {
    if (dp[idx] > 1) return dp[idx];
    int maximum = 1;

    for (int i = 1; i <= d; i++) {
        if (idx + i < arr.length && arr[idx] <= arr[idx + i]) break;
        if (idx + i < arr.length)
            maximum = Math.max(maximum, 1 + maxJumpsHelper(arr, d, dp, idx + i));

        if (idx - i >= 0 && arr[idx] <= arr[idx - i]) break;
        if (idx - i >= 0)
            maximum = Math.max(maximum, 1 + maxJumpsHelper(arr, d, dp, idx - i));
    }
    dp[idx] = maximum;
    return maximum;
}
```
1. Initialize dp array which helps to store the maximum indices visited for each index. Fill the dp array with 1 as the minimum value.
2. Write a helper function that takes an index as input and does the following:
   a. If there is already a calculated value in the dp array for this index, return it (memoization).
   b. Initialize a variable maximum with 1 as the minimum value.
   c. Iterate i from 1 to d (inclusive), and update maximum in the following manner:
      - Check if there is a possible right jump (i.e. idx+i is within range and arr[idx] > arr[idx+i]) and update `maximum` by choosing the maximum of its current value and 1 plus the helper value of idx+i.
      - Same goes for the left jump (i.e. idx-i is within range and arr[idx] > arr[idx-i]), updating maximum accordingly.
   d. Assign maximum to the dp value for idx and return it.
3. Loop over all indices and call the helper function.
4. Return the maximum value in the dp array as the final answer.

## A solution in C++

```cpp
#include <vector>

int maxJumps(std::vector<int>& arr, int d) {
    int n = arr.size();
    std::vector<int> dp(n, 1);

    auto helper = [&](auto &&self, int idx) -> int {
        if(dp[idx] > 1) return dp[idx];
        int maximum = 1;
        for(int i = 1; i <= d; i++) {
            if(idx + i < n && arr[idx] <= arr[idx + i]) break;
            if(idx + i < n)
                maximum = std::max(maximum, 1 + self(self, idx + i));

            if(idx - i >= 0 && arr[idx] <= arr[idx - i]) break;
            if(idx - i >= 0)
                maximum = std::max(maximum, 1 + self(self, idx - i));
        }
        return dp[idx] = maximum;
    };

    for(int i = 0; i < n; i++)
        helper(helper, i);

    return *std::max_element(dp.begin(), dp.end());
}
```
1. Initialize dp array which helps to store the maximum indices visited for each index. Fill the dp array with 1 as the minimum value.
2. Write a helper function that takes an index as input and does the following:
   a. If there is already a calculated value in the dp array for this index, return it (memoization).
   b. Initialize a variable maximum with 1 as the minimum value.
   c. Iterate i from 1 to d (inclusive), and update maximum in the following manner:
      - Check if there is a possible right jump (i.e. idx+i is within range and arr[idx] > arr[idx+i]) and update `maximum` by choosing the maximum of its current value and 1 plus the helper value of idx+i.
      - Same goes for the left jump (i.e. idx-i is within range and arr[idx] > arr[idx-i]), updating maximum accordingly.
   d. Assign maximum to the dp value for idx and return it.
3. Loop over all indices and call the helper function.
4. Return the maximum value in the dp array as the final answer.

## A solution in Python

```python
def maxJumps(arr, d):
    n = len(arr)
    dp = [1] * n

    def helper(idx):
        if dp[idx] > 1:
            return dp[idx]
        maximum = 1
        for i in range(1, d + 1):
            if idx + i < n and arr[idx] <= arr[idx + i]:
                break
            if idx + i < n:
                maximum = max(maximum, 1 + helper(idx + i))

            if idx - i >= 0 and arr[idx] <= arr[idx - i]:
                break
            if idx - i >= 0:
                maximum = max(maximum, 1 + helper(idx - i))

        dp[idx] = maximum
        return maximum

    for i in range(n):
        helper(i)

    return max(dp)
```
1. Initialize dp array which helps to store the maximum indices visited for each index. Fill the dp array with 1 as the minimum value.
2. Write a helper function that takes an index as input and does the following:
   a. If there is already a calculated value in the dp array for this index, return it (memoization).
   b. Initialize a variable maximum with 1 as the minimum value.
   c. Iterate i from 1 to d (inclusive), and update maximum in the following manner:
      - Check if there is a possible right jump (i.e. idx+i is within range and arr[idx] > arr[idx+i]) and update `maximum` by choosing the maximum of its current value and 1 plus the helper value of idx+i.
      - Same goes for the left jump (i.e. idx-i is within range and arr[idx] > arr[idx-i]), updating maximum accordingly.
   d. Assign maximum to the dp value for idx and return it.
3. Loop over all indices and call the helper function.
4. Return the maximum value in the dp array as the final answer.

## A solution in Javascript

```javascript
function maxJumps(arr, d) {
    const n = arr.length;
    const dp = new Array(n).fill(1);

    function helper(idx) {
        if (dp[idx] > 1) {
            return dp[idx];
        }
        let maximum = 1;

        for (let i = 1; i <= d; i++) {
            if (idx + i < n && arr[idx] <= arr[idx + i]) break;
            if (idx + i < n)
                maximum = Math.max(maximum, 1 + helper(idx + i));

            if (idx - i >= 0 && arr[idx] <= arr[idx - i]) break;
            if (idx - i >= 0)
                maximum = Math.max(maximum, 1 + helper(idx - i));
        }
        dp[idx] = maximum;
        return maximum;
    }

    for (let i = 0; i < n; i++) {
        helper(i);
    }

    return Math.max(...dp);
}
```
1. Initialize dp array which helps to store the maximum indices visited for each index. Fill the dp array with 1 as the minimum value.
2. Write a helper function that takes an index as input and does the following:
   a. If there is already a calculated value in the dp array for this index, return it (memoization).
   b. Initialize a variable maximum with 1 as the minimum value.
   c. Iterate i from 1 to d (inclusive), and update maximum in the following manner:
      - Check if there is a possible right jump (i.e. idx+i is within range and arr[idx] > arr[idx+i]) and update `maximum` by choosing the maximum of its current value and 1 plus the helper value of idx+i.
      - Same goes for the left jump (i.e. idx-i is within range and arr[idx] > arr[idx-i]), updating maximum accordingly.
   d. Assign maximum to the dp value for idx and return it.
3. Loop over all indices and call the helper function.
4. Return the maximum value in the dp array as the final answer.


# Probability of a Two Boxes Having The Same Number of Distinct Balls

- slug: probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
- difficulty: Hard

Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`.

All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).

Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a)` (Please read the explanation of the first example carefully).

Return _the probability_ that the two boxes have the same number of distinct balls. Answers within `10-5` of the actual value will be accepted as correct.

**Example 1:**

**Input:** balls = \[1,1\]
**Output:** 1.00000
**Explanation:** Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1

**Example 2:**

**Input:** balls = \[2,1,1\]
**Output:** 0.66667
**Explanation:** We have the set of balls \[1, 1, 2, 3\]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
\[1,1 / 2,3\], \[1,1 / 3,2\], \[1,2 / 1,3\], \[1,2 / 3,1\], \[1,3 / 1,2\], \[1,3 / 2,1\], \[2,1 / 1,3\], \[2,1 / 3,1\], \[2,3 / 1,1\], \[3,1 / 1,2\], \[3,1 / 2,1\], \[3,2 / 1,1\]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667

**Example 3:**

**Input:** balls = \[1,2,1,2\]
**Output:** 0.60000
**Explanation:** The set of balls is \[1, 2, 2, 3, 4, 4\]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6

**Constraints:**

*   `1 <= balls.length <= 8`
*   `1 <= balls[i] <= 6`
*   `sum(balls)` is even.

## A solution in Java

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

public double factorial(int num) {
    double result = 1;
    for (int i = 1; i <= num; i++)
        result *= i;
    return result;
}

public double countCombinations(int[] balls, List<Integer> combinations, int currBall) {
    double totalCombinations = 1;
    for (int i = 0; i < currBall; i++)
        totalCombinations *= factorial(balls[i] + combinations.get(i)) / (factorial(balls[i]) * factorial(combinations.get(i)));

    return totalCombinations;
}

public double dfs(int[] balls, List<Integer> combinations, int currBall) {
    if (currBall == balls.length) {
        if (combinations.get(combinations.size() - 1).equals(combinations.get(0)))
            return countCombinations(balls, combinations, currBall);
        else
            return 0;
    }

    double result = 0;
    for (int i = 0; i <= balls[currBall]; i++) {
        combinations.add(i);
        result += dfs(balls, combinations, currBall + 1);
        combinations.remove(combinations.size() - 1);
    }

    return result;
}

public double getProbability(int[] balls) {
    int sumBalls = 0;
    for (int ball : balls)
        sumBalls += ball;

    double totalCombinations = 1;
    for (int ball : balls)
        totalCombinations *= factorial(ball);

    List<Integer> combinations = new ArrayList<>();
    return dfs(balls, combinations, 0) / totalCombinations;
}
```
The algorithm is based on recursion and backtracking. We do a depth-first search for each ball in the input array, and use a variable called `combinations` to help compute the probabilities considering all arrangements of balls.

1. First, we calculate the factorial of each ball count to simplify probability calculation later.
2. We use a depth-first search approach to explore possible combinations of ball arrangements.
3. We exclude any combinations in which the last and the first elements in the `combinations` array do not have the same value. If the values are the same, we continue and compute the total probability for the current combination using the helper function `count_combinations`.
4. We recursively extend the `combinations` array and accumulate the probabilities in the `result`.
5. Finally, we return the sum of probabilities divided by the total number of combinations.

The time complexity of the algorithm is O(KN), where K is the number of distinct colors, and N is the total number of balls. The space complexity is also O(KN) as we store the `combinations` array for each color during the recursion.

## A solution in C++

```cpp
#include <vector>

double factorial(int num) {
    double result = 1;
    for (int i = 1; i <= num; i++)
        result *= i;
    return result;
}

double countCombinations(std::vector<int>& balls, std::vector<int>& combinations, int currBall) {
    double totalCombinations = 1;
    for (int i = 0; i < currBall; i++)
        totalCombinations *= factorial(balls[i] + combinations[i]) / (factorial(balls[i]) * factorial(combinations[i]));

    return totalCombinations;
}

double dfs(std::vector<int>& balls, std::vector<int>& combinations, int currBall) {
    if (currBall == balls.size()) {
        if (combinations.back() == combinations.front())
            return countCombinations(balls, combinations, currBall);
        else
            return 0;
    }

    double result = 0;
    for (int i = 0; i <= balls[currBall]; i++) {
        combinations.push_back(i);
        result += dfs(balls, combinations, currBall + 1);
        combinations.pop_back();
    }

    return result;
}

double getProbability(std::vector<int>& balls) {
    int sumBalls = 0;
    for (int ball : balls)
        sumBalls += ball;

    double totalCombinations = 1;
    for (int ball : balls)
        totalCombinations *= factorial(ball);

    std::vector<int> combinations;
    return dfs(balls, combinations, 0) / totalCombinations;
}
```
The algorithm is based on recursion and backtracking. We do a depth-first search for each ball in the input array, and use a variable called `combinations` to help compute the probabilities considering all arrangements of balls.

1. First, we calculate the factorial of each ball count to simplify probability calculation later.
2. We use a depth-first search approach to explore possible combinations of ball arrangements.
3. We exclude any combinations in which the last and the first elements in the `combinations` array do not have the same value. If the values are the same, we continue and compute the total probability for the current combination using the helper function `count_combinations`.
4. We recursively extend the `combinations` array and accumulate the probabilities in the `result`.
5. Finally, we return the sum of probabilities divided by the total number of combinations.

The time complexity of the algorithm is O(KN), where K is the number of distinct colors, and N is the total number of balls. The space complexity is also O(KN) as we store the `combinations` array for each color during the recursion.

## A solution in Python

```python
from math import factorial

def count_combinations(balls, combinations, curr_ball):
    total_combinations = 1
    for i in range(curr_ball):
        total_combinations *= factorial(balls[i] + combinations[i]) / (factorial(balls[i]) * factorial(combinations[i]))

    return total_combinations

def dfs(balls, combinations, curr_ball):
    if curr_ball == len(balls):
        if combinations[-1] == combinations[0]:
            return count_combinations(balls, combinations, curr_ball)
        else:
            return 0

    result = 0
    for i in range(balls[curr_ball] + 1):
        combinations.append(i)
        result += dfs(balls, combinations, curr_ball + 1)
        combinations.pop()

    return result

def get_probability(balls):
    sum_balls = sum(balls)

    total_combinations = 1
    for ball in balls:
        total_combinations *= factorial(ball)

    combinations = []
    return dfs(balls, combinations, 0) / total_combinations
```
The algorithm is based on recursion and backtracking. We do a depth-first search for each ball in the input array, and use a variable called `combinations` to help compute the probabilities considering all arrangements of balls.

1. First, we calculate the factorial of each ball count to simplify probability calculation later.
2. We use a depth-first search approach to explore possible combinations of ball arrangements.
3. We exclude any combinations in which the last and the first elements in the `combinations` array do not have the same value. If the values are the same, we continue and compute the total probability for the current combination using the helper function `count_combinations`.
4. We recursively extend the `combinations` array and accumulate the probabilities in the `result`.
5. Finally, we return the sum of probabilities divided by the total number of combinations.

The time complexity of the algorithm is O(KN), where K is the number of distinct colors, and N is the total number of balls. The space complexity is also O(KN) as we store the `combinations` array for each color during the recursion.

## A solution in Javascript

```javascript
function factorial(num) {
    let result = 1;
    for (let i = 1; i <= num; i++)
        result *= i;
    return result;
}

function countCombinations(balls, combinations, currBall) {
    let totalCombinations = 1;
    for (let i = 0; i < currBall; i++)
        totalCombinations *= factorial(balls[i] + combinations[i]) / (factorial(balls[i]) * factorial(combinations[i]));

    return totalCombinations;
}

function dfs(balls, combinations, currBall) {
    if (currBall === balls.length) {
        if (combinations[combinations.length - 1] === combinations[0])
            return countCombinations(balls, combinations, currBall);
        else
            return 0;
    }

    let result = 0;
    for (let i = 0; i <= balls[currBall]; i++) {
        combinations.push(i);
        result += dfs(balls, combinations, currBall + 1);
        combinations.pop();
    }

    return result;
}

function getProbability(balls) {
    let sumBalls = balls.reduce((a, b) => a + b);

    let totalCombinations = 1;
    for (let ball of balls)
        totalCombinations *= factorial(ball);

    let combinations = [];
    return dfs(balls, combinations, 0) / totalCombinations;
}
```
The algorithm is based on recursion and backtracking. We do a depth-first search for each ball in the input array, and use a variable called `combinations` to help compute the probabilities considering all arrangements of balls.

1. First, we calculate the factorial of each ball count to simplify probability calculation later.
2. We use a depth-first search approach to explore possible combinations of ball arrangements.
3. We exclude any combinations in which the last and the first elements in the `combinations` array do not have the same value. If the values are the same, we continue and compute the total probability for the current combination using the helper function `count_combinations`.
4. We recursively extend the `combinations` array and accumulate the probabilities in the `result`.
5. Finally, we return the sum of probabilities divided by the total number of combinations.

The time complexity of the algorithm is O(KN), where K is the number of distinct colors, and N is the total number of balls. The space complexity is also O(KN) as we store the `combinations` array for each color during the recursion.


# Find All The Lonely Nodes

- slug: find-all-the-lonely-nodes
- difficulty: Easy

In a binary tree, a **lonely** node is a node that is the only child of its parent node. The root of the tree is not lonely because it does not have a parent node.

Given the `root` of a binary tree, return _an array containing the values of all lonely nodes_ in the tree. Return the list **in any order**.

**Example 1:**

**Input:** root = \[1,2,3,null,4\]
**Output:** \[4\]
**Explanation:** Light blue node is the only lonely node.
Node 1 is the root and is not lonely.
Nodes 2 and 3 have the same parent and are not lonely.

**Example 2:**

**Input:** root = \[7,1,4,6,null,5,3,null,null,null,null,null,2\]
**Output:** \[6,2\]
**Explanation:** Light blue nodes are lonely nodes.
Please remember that order doesn't matter, \[2,6\] is also an acceptable answer.

**Example 3:**

**Input:** root = \[11,99,88,77,null,null,66,55,null,null,44,33,null,null,22\]
**Output:** \[77,55,33,66,44,22\]
**Explanation:** Nodes 99 and 88 share the same parent. Node 11 is the root.
All other nodes are lonely.

**Constraints:**

*   The number of nodes in the `tree` is in the range `[1, 1000].`
*   `1 <= Node.val <= 106`

## A solution in Java

```java
public int minSteps(String s, String t) {
    int[] countS = new int[26];
    int[] countT = new int[26];
    int steps = 0;

    for (char c : s.toCharArray()) countS[c - 'a']++;
    for (char c : t.toCharArray()) countT[c - 'a']++;

    for (int i = 0; i < 26; i++) {
        steps += Math.abs(countS[i] - countT[i]);
    }

    return steps / 2;
}
```
1. Initialize two frequency count arrays `countS` and `countT` of size 26 (to represent the English alphabet) and fill it with zeros.
2. Loop through the string `s` and increment the count of each character in `countS`.
3. Loop through the string `t` and increment the count of each character in `countT`.
4. Loop through the frequency arrays from 0 to 25, calculate the absolute difference of the count of each character in `countS` and `countT`, and add the differences to a variable `steps`.
5. Return half of the `steps` since the question asks for the minimum number of steps to make `t` an anagram of `s`. All differences in characters count are double-accounted when calculating the absolute difference (e.g., one less of a character in `t` also counts as one more of the same character in `s`).

## A solution in C++

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

int minSteps(string s, string t) {
    vector<int> countS(26, 0);
    vector<int> countT(26, 0);
    int steps = 0;

    for (char c : s) countS[c - 'a']++;
    for (char c : t) countT[c - 'a']++;

    for (int i = 0; i < 26; i++) {
        steps += abs(countS[i] - countT[i]);
    }

    return steps / 2;
}
```
1. Initialize two frequency count arrays `countS` and `countT` of size 26 (to represent the English alphabet) and fill it with zeros.
2. Loop through the string `s` and increment the count of each character in `countS`.
3. Loop through the string `t` and increment the count of each character in `countT`.
4. Loop through the frequency arrays from 0 to 25, calculate the absolute difference of the count of each character in `countS` and `countT`, and add the differences to a variable `steps`.
5. Return half of the `steps` since the question asks for the minimum number of steps to make `t` an anagram of `s`. All differences in characters count are double-accounted when calculating the absolute difference (e.g., one less of a character in `t` also counts as one more of the same character in `s`).

## A solution in Python

```python
def min_steps(s, t):
    count_s = [0] * 26
    count_t = [0] * 26
    steps = 0

    for c in s:
        count_s[ord(c) - ord('a')] += 1
    for c in t:
        count_t[ord(c) - ord('a')] += 1

    for i in range(26):
        steps += abs(count_s[i] - count_t[i])

    return steps // 2
```
1. Initialize two frequency count arrays `countS` and `countT` of size 26 (to represent the English alphabet) and fill it with zeros.
2. Loop through the string `s` and increment the count of each character in `countS`.
3. Loop through the string `t` and increment the count of each character in `countT`.
4. Loop through the frequency arrays from 0 to 25, calculate the absolute difference of the count of each character in `countS` and `countT`, and add the differences to a variable `steps`.
5. Return half of the `steps` since the question asks for the minimum number of steps to make `t` an anagram of `s`. All differences in characters count are double-accounted when calculating the absolute difference (e.g., one less of a character in `t` also counts as one more of the same character in `s`).

## A solution in Javascript

```javascript
function minSteps(s, t) {
    const countS = new Array(26).fill(0);
    const countT = new Array(26).fill(0);
    let steps = 0;

    for (let c of s) countS[c.charCodeAt() - 'a'.charCodeAt()]++;
    for (let c of t) countT[c.charCodeAt() - 'a'.charCodeAt()]++;

    for (let i = 0; i < 26; i++) {
        steps += Math.abs(countS[i] - countT[i]);
    }

    return steps / 2;
}
```
1. Initialize two frequency count arrays `countS` and `countT` of size 26 (to represent the English alphabet) and fill it with zeros.
2. Loop through the string `s` and increment the count of each character in `countS`.
3. Loop through the string `t` and increment the count of each character in `countT`.
4. Loop through the frequency arrays from 0 to 25, calculate the absolute difference of the count of each character in `countS` and `countT`, and add the differences to a variable `steps`.
5. Return half of the `steps` since the question asks for the minimum number of steps to make `t` an anagram of `s`. All differences in characters count are double-accounted when calculating the absolute difference (e.g., one less of a character in `t` also counts as one more of the same character in `s`).


# Shuffle the Array

- slug: shuffle-the-array
- difficulty: Easy

Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.

_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.

**Example 1:**

**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].

**Example 2:**

**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]

**Example 3:**

**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]

**Constraints:**

*   `1 <= n <= 500`
*   `nums.length == 2n`
*   `1 <= nums[i] <= 10^3`

## A solution in Java

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

public class TweetCounts {
    public void recordTweet(String tweetName, int time) {
        tweetRecords.computeIfAbsent(tweetName, k -> new TreeMap<>())
        .compute(time, (k, v) -> v == null ? 1 : v + 1);
    }

    public List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) {
        int interval;
        if (freq.equals("minute")) interval = 60;
        else if (freq.equals("hour")) interval = 3600;
        else interval = 86400;

        List<Integer> result = new ArrayList<>((endTime - startTime) / interval + 1);
        for (int i = 0; i < (endTime - startTime) / interval + 1; i++) result.add(0);

        if (!tweetRecords.containsKey(tweetName)) return result;

        for (int time : tweetRecords.get(tweetName).navigableKeySet()) {
            if (time >= startTime && time <= endTime) {
                result.set((time - startTime) / interval,
                        result.get((time - startTime) / interval) + tweetRecords.get(tweetName).get(time));
            }
        }

        return result;
    }

    private HashMap<String, TreeMap<Integer, Integer>> tweetRecords = new HashMap<>();
}
```
The `TweetCounts` class holds a data structure to store the frequency of tweet occurrences at a certain timestamp. This data structure is created as a nested map (unordered_map in C++), where the outer map uses `tweetName` as key, and the inner map uses time (in seconds) as key and count of tweets at that time as value. Whenever a new tweet is recorded, the count is incremented for the corresponding`tweetName` and time.

The `getTweetCountsPerFrequency` function accepts the frequency (minute, hour or day), `tweetName`, startTime and endTime as parameters. It calculates the interval in seconds based on the given frequency, and initializes an empty result vector, which will store the count of tweets for each partitioned chunk.

Iterate through the time and count pairs for the given `tweetName`. If the time lies within startTime and endTime, the count is added to the appropriate index in the result vector.

Finally, return the result vector.

## A solution in C++

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

class TweetCounts {
public:
    void recordTweet(string tweetName, int time) {
        tweetRecords[tweetName][time]++;
    }

    vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {
        int interval;
        if(freq == "minute") interval = 60;
        else if(freq == "hour") interval = 3600;
        else interval = 86400;

        vector<int> result((endTime - startTime) / interval + 1);
        for(const auto &timeCount : tweetRecords[tweetName]) {
            int time = timeCount.first, count = timeCount.second;
            if(time >= startTime && time <= endTime) {
                result[(time - startTime) / interval] += count;
            }
        }

        return result;
    }

private:
    unordered_map<string, map<int, int>> tweetRecords;
};
```
The `TweetCounts` class holds a data structure to store the frequency of tweet occurrences at a certain timestamp. This data structure is created as a nested map (unordered_map in C++), where the outer map uses `tweetName` as key, and the inner map uses time (in seconds) as key and count of tweets at that time as value. Whenever a new tweet is recorded, the count is incremented for the corresponding`tweetName` and time.

The `getTweetCountsPerFrequency` function accepts the frequency (minute, hour or day), `tweetName`, startTime and endTime as parameters. It calculates the interval in seconds based on the given frequency, and initializes an empty result vector, which will store the count of tweets for each partitioned chunk.

Iterate through the time and count pairs for the given `tweetName`. If the time lies within startTime and endTime, the count is added to the appropriate index in the result vector.

Finally, return the result vector.

## A solution in Python

```python
from collections import defaultdict
from typing import List

class TweetCounts:

    def __init__(self):
        self.tweet_records = defaultdict(lambda: defaultdict(int))

    def recordTweet(self, tweetName: str, time: int) -> None:
        self.tweet_records[tweetName][time] += 1

    def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:
        if freq == "minute":
            interval = 60
        elif freq == "hour":
            interval = 3600
        else:
            interval = 86400

        result = [0] * ((endTime - startTime) // interval + 1)
        for time, count in self.tweet_records[tweetName].items():
            if startTime <= time <= endTime:
                result[(time - startTime) // interval] += count

        return result
```
The `TweetCounts` class holds a data structure to store the frequency of tweet occurrences at a certain timestamp. This data structure is created as a nested map (unordered_map in C++), where the outer map uses `tweetName` as key, and the inner map uses time (in seconds) as key and count of tweets at that time as value. Whenever a new tweet is recorded, the count is incremented for the corresponding`tweetName` and time.

The `getTweetCountsPerFrequency` function accepts the frequency (minute, hour or day), `tweetName`, startTime and endTime as parameters. It calculates the interval in seconds based on the given frequency, and initializes an empty result vector, which will store the count of tweets for each partitioned chunk.

Iterate through the time and count pairs for the given `tweetName`. If the time lies within startTime and endTime, the count is added to the appropriate index in the result vector.

Finally, return the result vector.

## A solution in Javascript

```javascript
class TweetCounts {
    constructor() {
        this.tweetRecords = new Map();
    }

    recordTweet(tweetName, time) {
        if (!this.tweetRecords.has(tweetName)) {
            this.tweetRecords.set(tweetName, new Map());
        }
        const tweetTimeMap = this.tweetRecords.get(tweetName);
        tweetTimeMap.set(time, (tweetTimeMap.get(time) || 0) + 1);
    }

    getTweetCountsPerFrequency(freq, tweetName, startTime, endTime) {
        const interval = freq === "minute" ? 60 : freq === "hour" ? 3600 : 86400;
        const result = new Array(Math.floor((endTime - startTime) / interval) + 1).fill(0);
        if (!this.tweetRecords.has(tweetName)) return result;
        const tweetTimeMap = this.tweetRecords.get(tweetName);

        for (const [time, count] of tweetTimeMap.entries()) {
            if (time >= startTime && time <= endTime) {
                result[Math.floor((time - startTime) / interval)] += count;
            }
        }

        return result;
    }
}
```
The `TweetCounts` class holds a data structure to store the frequency of tweet occurrences at a certain timestamp. This data structure is created as a nested map (unordered_map in C++), where the outer map uses `tweetName` as key, and the inner map uses time (in seconds) as key and count of tweets at that time as value. Whenever a new tweet is recorded, the count is incremented for the corresponding`tweetName` and time.

The `getTweetCountsPerFrequency` function accepts the frequency (minute, hour or day), `tweetName`, startTime and endTime as parameters. It calculates the interval in seconds based on the given frequency, and initializes an empty result vector, which will store the count of tweets for each partitioned chunk.

Iterate through the time and count pairs for the given `tweetName`. If the time lies within startTime and endTime, the count is added to the appropriate index in the result vector.

Finally, return the result vector.


# The k Strongest Values in an Array

- slug: the-k-strongest-values-in-an-array
- difficulty: Medium

Given an array of integers `arr` and an integer `k`.

A value `arr[i]` is said to be stronger than a value `arr[j]` if `|arr[i] - m| > |arr[j] - m|` where `m` is the **median** of the array.
If `|arr[i] - m| == |arr[j] - m|`, then `arr[i]` is said to be stronger than `arr[j]` if `arr[i] > arr[j]`.

Return _a list of the strongest `k`_ values in the array. return the answer **in any arbitrary order**.

**Median** is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position `((n - 1) / 2)` in the sorted list **(0-indexed)**.

*   For `arr = [6, -3, 7, 2, 11]`, `n = 5` and the median is obtained by sorting the array `arr = [-3, 2, 6, 7, 11]` and the median is `arr[m]` where `m = ((5 - 1) / 2) = 2`. The median is `6`.
*   For `arr = [-7, 22, 17, 3]`, `n = 4` and the median is obtained by sorting the array `arr = [-7, 3, 17, 22]` and the median is `arr[m]` where `m = ((4 - 1) / 2) = 1`. The median is `3`.

**Example 1:**

**Input:** arr = \[1,2,3,4,5\], k = 2
**Output:** \[5,1\]
**Explanation:** Median is 3, the elements of the array sorted by the strongest are \[5,1,4,2,3\]. The strongest 2 elements are \[5, 1\]. \[1, 5\] is also **accepted** answer.
Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.

**Example 2:**

**Input:** arr = \[1,1,3,5,5\], k = 2
**Output:** \[5,5\]
**Explanation:** Median is 3, the elements of the array sorted by the strongest are \[5,5,1,1,3\]. The strongest 2 elements are \[5, 5\].

**Example 3:**

**Input:** arr = \[6,7,11,7,6,8\], k = 5
**Output:** \[11,8,6,6,7\]
**Explanation:** Median is 7, the elements of the array sorted by the strongest are \[11,8,6,6,7,7\].
Any permutation of \[11,8,6,6,7\] is **accepted**.

**Constraints:**

*   `1 <= arr.length <= 105`
*   `-105 <= arr[i] <= 105`
*   `1 <= k <= arr.length`

## A solution in Java

```java
int maxStudents(char[][] seats) {
    int m = seats.length, n = seats[0].length;
    int[] validRows = new int[m];
    int max_valid = (1 << n) - 1;
    for (int i = 0; i < m; i++) {
        int state = 0;
        for (int j = 0; j < n; j++) {
            state |= (seats[i][j] == '.') ? (1 << j) : 0;
        }
        validRows[i] = state;
    }

    int[][] memo = new int[m][1 << n];
    for(int i = 0; i < m; i++) {
        Arrays.fill(memo[i], -1);
    }
    return dfs(0, 0, validRows, m, n, max_valid, memo);
}

int dfs(int rowIndex, int prevState, int[] validRows, int m, int n, int max_valid, int[][] memo) {
    if (rowIndex == m) {
        return 0;
    }

    if (memo[rowIndex][prevState] != -1) {
        return memo[rowIndex][prevState];
    }

    int maxStudents = 0;
    for (int curState = 0; curState <= max_valid; curState++) {
        if ((curState & validRows[rowIndex]) != curState) continue;
        if ((curState & (curState << 1)) != 0) continue;
        if ((curState & (prevState << 1)) != 0 || (prevState & (curState << 1)) != 0) continue;

        maxStudents = Math.max(maxStudents, dfs(rowIndex + 1, curState, validRows, m, n, max_valid, memo) + Integer.bitCount(curState));
    }

    memo[rowIndex][prevState] = maxStudents;
    return maxStudents;
}
```
1. Convert each row into binary representation where '1' denotes a good seat and '0' denotes a broken seat.
2. Use a depth-first search with memorization to explore all valid states of students sitting in the classroom.
3. For each seat arrangement in a row, apply three conditions:
    a. Ensure students only sit on good seats.
    b. Students don't sit next to each other (left and right).
    c. Students don't sit on upper-left and upper-right seats of students from the previous row.
4. Recursively call the dfs function for each row, until all rows have been processed.
5. Keep track of the maximum number of students that can sit without cheating using memo table.
6. Return the maximum number of students that can take the exam together without any cheating being possible.

## A solution in C++

```cpp
int maxStudents(vector<vector<char>>& seats) {
    int m = seats.size();
    int n = seats[0].size();
    vector<int> validRows(m);
    int max_valid = (1 << n) - 1;
    for (int i = 0; i < m; i++) {
        int state = 0;
        for (int j = 0; j < n; j++) {
            state |= (seats[i][j] == '.') << j;
        }
        validRows[i] = state;
    }

    vector<vector<int>> dp(m, vector<int>(1<<n, -1));
    function<int(int, int)> dfs = [&](int rowIndex, int prevState) {
        if (rowIndex >= m) return 0;
        if (dp[rowIndex][prevState] != -1) return dp[rowIndex][prevState];

        int maxStudents = 0;
        for (int curState = 0; curState <= max_valid; curState++) {
            if ((curState & validRows[rowIndex]) != curState) continue;
            if (curState & (curState << 1)) continue;
            if (curState & (prevState << 1) || prevState & (curState << 1)) continue;

            maxStudents = max(maxStudents, dfs(rowIndex + 1, curState) + __builtin_popcount(curState));
        }

        dp[rowIndex][prevState] = maxStudents;
        return maxStudents;
    };

    return dfs(0, 0);
}
```
1. Convert each row into binary representation where '1' denotes a good seat and '0' denotes a broken seat.
2. Use a depth-first search with memorization to explore all valid states of students sitting in the classroom.
3. For each seat arrangement in a row, apply three conditions:
    a. Ensure students only sit on good seats.
    b. Students don't sit next to each other (left and right).
    c. Students don't sit on upper-left and upper-right seats of students from the previous row.
4. Recursively call the dfs function for each row, until all rows have been processed.
5. Keep track of the maximum number of students that can sit without cheating using memo table.
6. Return the maximum number of students that can take the exam together without any cheating being possible.

## A solution in Python

```python
def maxStudents(seats):
    m, n = len(seats), len(seats[0])
    valid_rows = [0] * m
    max_valid = (1 << n) - 1
    for i in range(m):
        state = 0
        for j in range(n):
            state |= (seats[i][j] == '.') << j
        valid_rows[i] = state

    memo = [[-1] * (1 << n) for _ in range(m)]
    return dfs(0, 0, valid_rows, m, n, max_valid, memo)

def dfs(row_index, prev_state, valid_rows, m, n, max_valid, memo):
    if row_index == m:
        return 0

    if memo[row_index][prev_state] != -1:
        return memo[row_index][prev_state]

    max_students = 0
    for cur_state in range(max_valid + 1):
        if (cur_state & valid_rows[row_index]) != cur_state:
            continue
        if cur_state & (cur_state << 1):
            continue
        if cur_state & (prev_state << 1) or prev_state & (cur_state << 1):
            continue

        max_students = max(max_students, dfs(row_index + 1, cur_state, valid_rows, m, n, max_valid, memo) + bin(cur_state).count('1'))

    memo[row_index][prev_state] = max_students
    return max_students
```
1. Convert each row into binary representation where '1' denotes a good seat and '0' denotes a broken seat.
2. Use a depth-first search with memorization to explore all valid states of students sitting in the classroom.
3. For each seat arrangement in a row, apply three conditions:
    a. Ensure students only sit on good seats.
    b. Students don't sit next to each other (left and right).
    c. Students don't sit on upper-left and upper-right seats of students from the previous row.
4. Recursively call the dfs function for each row, until all rows have been processed.
5. Keep track of the maximum number of students that can sit without cheating using memo table.
6. Return the maximum number of students that can take the exam together without any cheating being possible.

## A solution in Javascript

```javascript
function maxStudents(seats) {
    const m = seats.length;
    const n = seats[0].length;
    let validRows = new Array(m);
    const max_valid = (1 << n) - 1;

    for (let i = 0; i < m; i++) {
        let state = 0;
        for (let j = 0; j < n; j++) {
            state |= (seats[i][j] === '.') << j;
        }
        validRows[i] = state;
    }

    const memo = Array.from({ length: m }, () => Array(1 << n).fill(-1));
    return dfs(0, 0, validRows, m, n, max_valid, memo);
}

function dfs(rowIndex, prevState, validRows, m, n, max_valid, memo) {
    if (rowIndex === m) {
        return 0;
    }

    if (memo[rowIndex][prevState] !== -1) {
        return memo[rowIndex][prevState];
    }

    let maxStudents = 0;
    for (let curState = 0; curState <= max_valid; curState++) {
        if ((curState & validRows[rowIndex]) !== curState) continue;
        if (curState & (curState << 1)) continue;
        if (curState & (prevState << 1) || prevState & (curState << 1)) continue;

        const curStateCount = curState.toString(2).split("").reduce((sum, bit) => sum + (bit === '1' ? 1 : 0), 0);
        maxStudents = Math.max(maxStudents, dfs(rowIndex + 1, curState, validRows, m, n, max_valid, memo) + curStateCount);
    }

    memo[rowIndex][prevState] = maxStudents;
    return maxStudents;
}
```
1. Convert each row into binary representation where '1' denotes a good seat and '0' denotes a broken seat.
2. Use a depth-first search with memorization to explore all valid states of students sitting in the classroom.
3. For each seat arrangement in a row, apply three conditions:
    a. Ensure students only sit on good seats.
    b. Students don't sit next to each other (left and right).
    c. Students don't sit on upper-left and upper-right seats of students from the previous row.
4. Recursively call the dfs function for each row, until all rows have been processed.
5. Keep track of the maximum number of students that can sit without cheating using memo table.
6. Return the maximum number of students that can take the exam together without any cheating being possible.