# Number of Ways to Stay in the Same Place After Some Steps

- slug: number-of-ways-to-stay-in-the-same-place-after-some-steps
- difficulty: Hard

You have a pointer at index `0` in an array of size `arrLen`. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).

Given two integers `steps` and `arrLen`, return the number of ways such that your pointer is still at index `0` after **exactly** `steps` steps. Since the answer may be too large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** steps = 3, arrLen = 2
**Output:** 4
**Explanation:** There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay

**Example 2:**

**Input:** steps = 2, arrLen = 4
**Output:** 2
**Explanation:** There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay

**Example 3:**

**Input:** steps = 4, arrLen = 2
**Output:** 8

**Constraints:**

*   `1 <= steps <= 500`
*   `1 <= arrLen <= 106`

## A solution in Java

```java
final int mod = 1000000007;

public int numOfWays(int steps, int arrLen) {
  int maxPos = Math.min(steps / 2, arrLen - 1);
  int[][] dp = new int[2][maxPos + 1];
  dp[0][0] = 1;
  for (int s = 1; s <= steps; ++s) {
    for (int p = 0; p <= maxPos; ++p) {
      dp[s % 2][p] = dp[(s - 1) % 2][p];
      if (p > 0)
        dp[s % 2][p] += dp[(s - 1) % 2][p - 1];
      if (p < maxPos)
        dp[s % 2][p] += dp[(s - 1) % 2][p + 1];
      dp[s % 2][p] %= mod;
    }
  }
  return dp[steps % 2][0];
}
```

    We use dynamic programming to solve this problem. The state of our dynamic programming is `dp[s][p]`, which represents the number of ways to be at position `p` after `s` steps.

The base case is `dp[0][0] = 1`, which means there is only one way to be at position `0` (stay there).

Our transition function is as follows:
```
dp[s][p] = dp[s - 1][p - 1] + dp[s - 1][p] + dp[s - 1][p + 1] (% mod)
```
In plain words, for every `s` steps, we can either go left, right, or stay at the current position. We iterate from `s = 1` to `steps`. We also set an upper limit on the maximum position we can consider, which is the minimum between `steps / 2` and `arrLen - 1`. This is because we have to return to position `0` after taking `steps`, and while traversing more than `steps / 2` steps, we can't reach position `0`.

At the end, we return `dp[steps % 2][0]`, which is the number of ways to be at index `0` after `steps` steps.

## A solution in C++

```cpp
const int mod = 1e9 + 7;

int numOfWays(int steps, int arrLen) {
  int max_pos = min(steps / 2, arrLen - 1);
  vector<vector<int>> dp(2, vector<int>(max_pos + 1));
  dp[0][0] = 1;
  for (int s = 1; s <= steps; ++s) {
    for (int p = 0; p <= max_pos; ++p) {
      dp[s % 2][p] = dp[(s - 1) % 2][p];
      if (p > 0) {
        dp[s % 2][p] += dp[(s - 1) % 2][p - 1];
      }
      if (p < max_pos) {
        dp[s % 2][p] += dp[(s - 1) % 2][p + 1];
      }
      dp[s % 2][p] %= mod;
    }
  }
  return dp[steps % 2][0];
}
```

    We use dynamic programming to solve this problem. The state of our dynamic programming is `dp[s][p]`, which represents the number of ways to be at position `p` after `s` steps.

The base case is `dp[0][0] = 1`, which means there is only one way to be at position `0` (stay there).

Our transition function is as follows:
```
dp[s][p] = dp[s - 1][p - 1] + dp[s - 1][p] + dp[s - 1][p + 1] (% mod)
```
In plain words, for every `s` steps, we can either go left, right, or stay at the current position. We iterate from `s = 1` to `steps`. We also set an upper limit on the maximum position we can consider, which is the minimum between `steps / 2` and `arrLen - 1`. This is because we have to return to position `0` after taking `steps`, and while traversing more than `steps / 2` steps, we can't reach position `0`.

At the end, we return `dp[steps % 2][0]`, which is the number of ways to be at index `0` after `steps` steps.

## A solution in Python

```python
from functools import lru_cache

mod = 10**9 + 7

def numOfWays(steps: int, arrLen: int) -> int:
    @lru_cache(None)
    def dp(s, p):
        if p < 0 or p >= arrLen or p > steps - p:
            return 0
        if s == 0:
            return p == 0
        return (dp(s - 1, p - 1) + dp(s - 1, p) + dp(s - 1, p + 1)) % mod

    return dp(steps, 0)
```

    We use dynamic programming to solve this problem. The state of our dynamic programming is `dp[s][p]`, which represents the number of ways to be at position `p` after `s` steps.

The base case is `dp[0][0] = 1`, which means there is only one way to be at position `0` (stay there).

Our transition function is as follows:
```
dp[s][p] = dp[s - 1][p - 1] + dp[s - 1][p] + dp[s - 1][p + 1] (% mod)
```
In plain words, for every `s` steps, we can either go left, right, or stay at the current position. We iterate from `s = 1` to `steps`. We also set an upper limit on the maximum position we can consider, which is the minimum between `steps / 2` and `arrLen - 1`. This is because we have to return to position `0` after taking `steps`, and while traversing more than `steps / 2` steps, we can't reach position `0`.

At the end, we return `dp[steps % 2][0]`, which is the number of ways to be at index `0` after `steps` steps.

## A solution in Javascript

```javascript
const mod = 1e9 + 7;

function numOfWays(steps, arrLen) {
  const maxPos = Math.min(Math.floor(steps / 2), arrLen - 1);
  const dp = [[], []];
  dp[0][0] = 1;

  for (let s = 1; s <= steps; s++) {
    for (let p = 0; p <= maxPos; p++) {
      dp[s % 2][p] = dp[(s - 1) % 2][p];
      if (p > 0) {
        dp[s % 2][p] += dp[(s - 1) % 2][p - 1];
      }
      if (p < maxPos) {
        dp[s % 2][p] += dp[(s - 1) % 2][p + 1];
      }
      dp[s % 2][p] %= mod;
    }
  }
  return dp[steps % 2][0];
}
```

    We use dynamic programming to solve this problem. The state of our dynamic programming is `dp[s][p]`, which represents the number of ways to be at position `p` after `s` steps.

The base case is `dp[0][0] = 1`, which means there is only one way to be at position `0` (stay there).

Our transition function is as follows:
```
dp[s][p] = dp[s - 1][p - 1] + dp[s - 1][p] + dp[s - 1][p + 1] (% mod)
```
In plain words, for every `s` steps, we can either go left, right, or stay at the current position. We iterate from `s = 1` to `steps`. We also set an upper limit on the maximum position we can consider, which is the minimum between `steps / 2` and `arrLen - 1`. This is because we have to return to position `0` after taking `steps`, and while traversing more than `steps / 2` steps, we can't reach position `0`.

At the end, we return `dp[steps % 2][0]`, which is the number of ways to be at index `0` after `steps` steps.


# Hexspeak

- slug: hexspeak
- difficulty: Easy

A decimal number can be converted to its **Hexspeak representation** by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit `'0'` with the letter `'O'`, and the digit `'1'` with the letter `'I'`. Such a representation is valid if and only if it consists only of the letters in the set `{'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}`.

Given a string `num` representing a decimal integer `n`, _return the **Hexspeak representation** of_ `n` _if it is valid, otherwise return_ `"ERROR "`.

**Example 1:**

**Input:** num =  "257 "
**Output:**  "IOI "
**Explanation:** 257 is 101 in hexadecimal.

**Example 2:**

**Input:** num =  "3 "
**Output:**  "ERROR "

**Constraints:**

*   `1 <= num.length <= 12`
*   `num` does not contain leading zeros.
*   num represents an integer in the range `[1, 1012]`.

## A solution in Java

```java
public String toHexspeak(String num) {
    long n = Long.parseLong(num);
    StringBuilder hex = new StringBuilder();
    while (n != 0) {
        int rem = (int)(n % 16);
        if (rem == 1) hex.insert(0, 'I');
        else if (rem == 0) hex.insert(0, 'O');
        else if (rem > 9) hex.insert(0, (char)(rem - 10 + 'A'));
        else return "ERROR";
        n /= 16;
    }
    return hex.toString();
}
```
The algorithm first converts the input number (given as a string) to a long integer (we'll call it `n`). We then use a loop to construct the Hexspeak representation in reverse order. In each iteration, we calculate the remainder `rem` of `n` divided by 16. If `rem` is 1, we append 'I' to the beginning of the string; if it is 0, we append 'O'; if it is greater than 9, we append the corresponding letter ('A' to 'F'); and if it is none of these, then the Hexspeak representation is invalid, and we return "ERROR". After processing each character, we update `n` by dividing it by 16. Finally, we return the constructed Hexspeak representation.

This algorithm runs in O(log(n)) time complexity, as each iteration of the loop reduces `n` by a factor of 16. The space complexity is also O(log(n)), as the constructed Hexspeak representation string has a length proportional to the number of hexadecimal digits in `n`.

## A solution in C++

```cpp
#include <string>

std::string toHexspeak(std::string num) {
    long n = std::stol(num);
    std::string hex = "";
    while (n) {
        int rem = n % 16;
        if (rem == 1) hex = "I" + hex;
        else if (rem == 0) hex = "O" + hex;
        else if (rem > 9) hex = (char)(rem - 10 + 'A') + hex;
        else return "ERROR";
        n /= 16;
    }
    return hex;
}
```
The algorithm first converts the input number (given as a string) to a long integer (we'll call it `n`). We then use a loop to construct the Hexspeak representation in reverse order. In each iteration, we calculate the remainder `rem` of `n` divided by 16. If `rem` is 1, we append 'I' to the beginning of the string; if it is 0, we append 'O'; if it is greater than 9, we append the corresponding letter ('A' to 'F'); and if it is none of these, then the Hexspeak representation is invalid, and we return "ERROR". After processing each character, we update `n` by dividing it by 16. Finally, we return the constructed Hexspeak representation.

This algorithm runs in O(log(n)) time complexity, as each iteration of the loop reduces `n` by a factor of 16. The space complexity is also O(log(n)), as the constructed Hexspeak representation string has a length proportional to the number of hexadecimal digits in `n`.

## A solution in Python

```python
def to_hexspeak(num: str) -> str:
    n = int(num)
    hex_str = []
    while n:
        rem = n % 16
        if rem == 1: hex_str.insert(0, 'I')
        elif rem == 0: hex_str.insert(0, 'O')
        elif rem > 9: hex_str.insert(0, chr(rem - 10 + ord('A')))
        else: return 'ERROR'
        n //= 16
    return ''.join(hex_str)
```
The algorithm first converts the input number (given as a string) to a long integer (we'll call it `n`). We then use a loop to construct the Hexspeak representation in reverse order. In each iteration, we calculate the remainder `rem` of `n` divided by 16. If `rem` is 1, we append 'I' to the beginning of the string; if it is 0, we append 'O'; if it is greater than 9, we append the corresponding letter ('A' to 'F'); and if it is none of these, then the Hexspeak representation is invalid, and we return "ERROR". After processing each character, we update `n` by dividing it by 16. Finally, we return the constructed Hexspeak representation.

This algorithm runs in O(log(n)) time complexity, as each iteration of the loop reduces `n` by a factor of 16. The space complexity is also O(log(n)), as the constructed Hexspeak representation string has a length proportional to the number of hexadecimal digits in `n`.

## A solution in Javascript

```javascript
function toHexspeak(num) {
    let n = BigInt(num);
    let hex = '';
    while (n) {
        let rem = Number(n % 16n);
        if (rem === 1) hex = 'I' + hex;
        else if (rem === 0) hex = 'O' + hex;
        else if (rem > 9) hex = String.fromCharCode(rem - 10 + 'A'.charCodeAt(0)) + hex;
        else return 'ERROR';
        n /= 16n;
    }
    return hex;
}
```
The algorithm first converts the input number (given as a string) to a long integer (we'll call it `n`). We then use a loop to construct the Hexspeak representation in reverse order. In each iteration, we calculate the remainder `rem` of `n` divided by 16. If `rem` is 1, we append 'I' to the beginning of the string; if it is 0, we append 'O'; if it is greater than 9, we append the corresponding letter ('A' to 'F'); and if it is none of these, then the Hexspeak representation is invalid, and we return "ERROR". After processing each character, we update `n` by dividing it by 16. Finally, we return the constructed Hexspeak representation.

This algorithm runs in O(log(n)) time complexity, as each iteration of the loop reduces `n` by a factor of 16. The space complexity is also O(log(n)), as the constructed Hexspeak representation string has a length proportional to the number of hexadecimal digits in `n`.


# Remove Interval

- slug: remove-interval
- difficulty: Medium

A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form `[a, b)`. A real number `x` is in the set if one of its intervals `[a, b)` contains `x` (i.e. `a <= x < b`).

You are given a **sorted** list of disjoint intervals `intervals` representing a set of real numbers as described above, where `intervals[i] = [ai, bi]` represents the interval `[ai, bi)`. You are also given another interval `toBeRemoved`.

Return _the set of real numbers with the interval_ `toBeRemoved` _**removed** from_ `intervals`_. In other words, return the set of real numbers such that every_ `x` _in the set is in_ `intervals` _but **not** in_ `toBeRemoved`_. Your answer should be a **sorted** list of disjoint intervals as described above._

**Example 1:**

**Input:** intervals = \[\[0,2\],\[3,4\],\[5,7\]\], toBeRemoved = \[1,6\]
**Output:** \[\[0,1\],\[6,7\]\]

**Example 2:**

**Input:** intervals = \[\[0,5\]\], toBeRemoved = \[2,3\]
**Output:** \[\[0,2\],\[3,5\]\]

**Example 3:**

**Input:** intervals = \[\[-5,-4\],\[-3,-2\],\[1,2\],\[3,5\],\[8,9\]\], toBeRemoved = \[-1,4\]
**Output:** \[\[-5,-4\],\[-3,-2\],\[4,5\],\[8,9\]\]

**Constraints:**

*   `1 <= intervals.length <= 104`
*   `-109 <= ai < bi <= 109`

## A solution in Java

```java
import java.util.*;

public List<String> invalidTransactions(String[] transactions) {
    Map<String, List<String[]>> trans_map = new HashMap<>();

    for (String trans : transactions) {
        String[] temp = trans.split(",");
        trans_map.putIfAbsent(temp[0], new ArrayList<>());
        trans_map.get(temp[0]).add(temp);
    }

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

    for (String trans : transactions) {
        String[] temp = trans.split(",");

        if (Integer.parseInt(temp[2]) > 1000) {
            ans.add(trans);
            continue;
        }

        List<String[]> others = trans_map.get(temp[0]);

        for (String[] other : others) {
            if (!other[3].equals(temp[3]) && Math.abs(Integer.parseInt(other[1]) - Integer.parseInt(temp[1])) <= 60) {
                ans.add(trans);
                break;
            }
        }
    }

    return ans;
}
```
The algorithm consists of the following steps:

1. Create a map to store transactions by names.
2. For each transaction, split it by the comma and add it to the map based on the name.
3. Initialize an empty array to store invalid transactions.
4. For each transaction, if the amount is greater than 1000, add it to the invalid transactions array.
5. Iterate through the transactions of the same name and check if the city is different and the time difference is less than or equal to 60. If yes, add the transaction to the invalid transactions array.
6. Return the invalid transactions array.

## A solution in C++

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

std::vector<std::string> invalidTransactions(std::vector<std::string>& transactions) {
    std::unordered_map<std::string, std::vector<std::vector<std::string>>> trans_map;

    for (const auto& trans : transactions) {
        std::stringstream ss(trans);
        std::vector<std::string> temp;
        std::string s;

        while (std::getline(ss, s, ','))
            temp.push_back(s);

        trans_map[temp[0]].push_back(temp);
    }

    std::vector<std::string> ans;

    for (const auto& trans : transactions) {
        std::stringstream ss(trans);
        std::vector<std::string> temp;
        std::string s;

        while (std::getline(ss, s, ','))
            temp.push_back(s);

        if (std::stoi(temp[2]) > 1000) {
            ans.push_back(trans);
            continue;
        }

        for (const auto& other : trans_map[temp[0]]) {
            if (other[3] != temp[3] && std::abs(std::stoi(other[1]) - std::stoi(temp[1])) <= 60) {
                ans.push_back(trans);
                break;
            }
        }
    }

    return ans;
}
```
The algorithm consists of the following steps:

1. Create a map to store transactions by names.
2. For each transaction, split it by the comma and add it to the map based on the name.
3. Initialize an empty array to store invalid transactions.
4. For each transaction, if the amount is greater than 1000, add it to the invalid transactions array.
5. Iterate through the transactions of the same name and check if the city is different and the time difference is less than or equal to 60. If yes, add the transaction to the invalid transactions array.
6. Return the invalid transactions array.

## A solution in Python

```python
def invalid_transactions(transactions):
    trans_map = {}

    for trans in transactions:
        temp = trans.split(",")
        trans_map.setdefault(temp[0], []).append(temp)

    ans = []

    for trans in transactions:
        temp = trans.split(",")

        if int(temp[2]) > 1000:
            ans.append(trans)
            continue

        for other in trans_map[temp[0]]:
            if other[3] != temp[3] and abs(int(other[1]) - int(temp[1])) <= 60:
                ans.append(trans)
                break

    return ans
```
The algorithm consists of the following steps:

1. Create a map to store transactions by names.
2. For each transaction, split it by the comma and add it to the map based on the name.
3. Initialize an empty array to store invalid transactions.
4. For each transaction, if the amount is greater than 1000, add it to the invalid transactions array.
5. Iterate through the transactions of the same name and check if the city is different and the time difference is less than or equal to 60. If yes, add the transaction to the invalid transactions array.
6. Return the invalid transactions array.

## A solution in Javascript

```javascript
function invalidTransactions(transactions) {
    const trans_map = new Map();

    for (let trans of transactions) {
        let temp = trans.split(",");
        if (!trans_map.has(temp[0])) {
            trans_map.set(temp[0], []);
        }
        trans_map.get(temp[0]).push(temp);
    }

    let ans = [];

    for (let trans of transactions) {
        let temp = trans.split(",");

        if (parseInt(temp[2]) > 1000) {
            ans.push(trans);
            continue;
        }

        let others = trans_map.get(temp[0]);

        for (let other of others) {
            if (other[3] !== temp[3] && Math.abs(parseInt(other[1]) - parseInt(temp[1])) <= 60) {
                ans.push(trans);
                break;
            }
        }
    }

    return ans;
}
```
The algorithm consists of the following steps:

1. Create a map to store transactions by names.
2. For each transaction, split it by the comma and add it to the map based on the name.
3. Initialize an empty array to store invalid transactions.
4. For each transaction, if the amount is greater than 1000, add it to the invalid transactions array.
5. Iterate through the transactions of the same name and check if the city is different and the time difference is less than or equal to 60. If yes, add the transaction to the invalid transactions array.
6. Return the invalid transactions array.


# Delete Tree Nodes

- slug: delete-tree-nodes
- difficulty: Medium

A tree rooted at node 0 is given as follows:

*   The number of nodes is `nodes`;
*   The value of the `ith` node is `value[i]`;
*   The parent of the `ith` node is `parent[i]`.

Remove every subtree whose sum of values of nodes is zero.

Return _the number of the remaining nodes in the tree_.

**Example 1:**

**Input:** nodes = 7, parent = \[-1,0,0,1,2,2,2\], value = \[1,-2,4,0,-2,-1,-1\]
**Output:** 2

**Example 2:**

**Input:** nodes = 7, parent = \[-1,0,0,1,2,2,2\], value = \[1,-2,4,0,-2,-1,-2\]
**Output:** 6

**Constraints:**

*   `1 <= nodes <= 104`
*   `parent.length == nodes`
*   `0 <= parent[i] <= nodes - 1`
*   `parent[0] == -1` which indicates that `0` is the root.
*   `value.length == nodes`
*   `-105 <= value[i] <= 105`
*   The given input is **guaranteed** to represent a **valid tree**.

## A solution in Java

```java
import java.util.Arrays;

public int[] countSmallerFrequencies(String[] words, String[] queries) {
    int[] freqWords = new int[words.length];

    for (int i = 0; i < words.length; i++) {
        char minChar = words[i].chars().min().getAsInt();
        freqWords[i] = (int) words[i].chars().filter(c -> c == minChar).count();
    }

    int[] ans = new int[queries.length];
    for (int i = 0; i < queries.length; i++) {
        char minChar = queries[i].chars().min().getAsInt();
        int freqQuery = (int) queries[i].chars().filter(c -> c == minChar).count();

        ans[i] = (int) Arrays.stream(freqWords).filter(f -> f > freqQuery).count();
    }

    return ans;
}
```
1. First, we calculate the frequencies of the lexicographically smallest characters in each word of `words`. This is done by iterating through the words, finding the smallest character, counting its frequency, and store the result in a new array named `freqWords`.
2. Next, we iterate through the queries in `queries`. For each query, we find the lexicographically smallest character, and count its frequency `freqQuery`.
3. For each query, we count the number of elements in `freqWords` that are greater than the `freqQuery`. This is done using `count_if` in C++, `filter` followed by `count` in Java, a list comprehension with `sum` in Python, and `filter` followed by `length` in JavaScript.
4. The result is appended to the `ans` array and returned at the end.

## A solution in C++

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

std::vector<int> countSmallerFrequencies(const std::vector<std::string>& words, const std::vector<std::string>& queries) {
    std::vector<int> freqWords(words.size(), 0);

    for (int i = 0; i < words.size(); ++i) {
        char minChar = *min_element(words[i].begin(), words[i].end());
        freqWords[i] = count(words[i].begin(), words[i].end(), minChar);
    }

    std::vector<int> ans(queries.size(), 0);
    for (int i = 0; i < queries.size(); ++i) {
        char minChar = *min_element(queries[i].begin(), queries[i].end());
        int freqQuery = count(queries[i].begin(), queries[i].end(), minChar);

        ans[i] = count_if(freqWords.begin(), freqWords.end(), [freqQuery](int f) { return f > freqQuery; });
    }

    return ans;
}
```
1. First, we calculate the frequencies of the lexicographically smallest characters in each word of `words`. This is done by iterating through the words, finding the smallest character, counting its frequency, and store the result in a new array named `freqWords`.
2. Next, we iterate through the queries in `queries`. For each query, we find the lexicographically smallest character, and count its frequency `freqQuery`.
3. For each query, we count the number of elements in `freqWords` that are greater than the `freqQuery`. This is done using `count_if` in C++, `filter` followed by `count` in Java, a list comprehension with `sum` in Python, and `filter` followed by `length` in JavaScript.
4. The result is appended to the `ans` array and returned at the end.

## A solution in Python

```python
def countSmallerFrequencies(words, queries):
    freqWords = [word.count(min(word)) for word in words]

    ans = []
    for query in queries:
        freqQuery = query.count(min(query))
        ans.append(sum(f > freqQuery for f in freqWords))

    return ans
```
1. First, we calculate the frequencies of the lexicographically smallest characters in each word of `words`. This is done by iterating through the words, finding the smallest character, counting its frequency, and store the result in a new array named `freqWords`.
2. Next, we iterate through the queries in `queries`. For each query, we find the lexicographically smallest character, and count its frequency `freqQuery`.
3. For each query, we count the number of elements in `freqWords` that are greater than the `freqQuery`. This is done using `count_if` in C++, `filter` followed by `count` in Java, a list comprehension with `sum` in Python, and `filter` followed by `length` in JavaScript.
4. The result is appended to the `ans` array and returned at the end.

## A solution in Javascript

```javascript
function countSmallerFrequencies(words, queries) {
    const freqWords = words.map(word => {
        const minChar = Math.min(...word);
        return word.split(minChar).length - 1;
    });

    const ans = [];
    for (const query of queries) {
        const minChar = Math.min(...query);
        const freqQuery = query.split(minChar).length - 1;

        ans.push(freqWords.filter(f => f > freqQuery).length);
    }

    return ans;
}
```
1. First, we calculate the frequencies of the lexicographically smallest characters in each word of `words`. This is done by iterating through the words, finding the smallest character, counting its frequency, and store the result in a new array named `freqWords`.
2. Next, we iterate through the queries in `queries`. For each query, we find the lexicographically smallest character, and count its frequency `freqQuery`.
3. For each query, we count the number of elements in `freqWords` that are greater than the `freqQuery`. This is done using `count_if` in C++, `filter` followed by `count` in Java, a list comprehension with `sum` in Python, and `filter` followed by `length` in JavaScript.
4. The result is appended to the `ans` array and returned at the end.


# Number of Ships in a Rectangle

- slug: number-of-ships-in-a-rectangle
- difficulty: Hard

_(This problem is an **interactive problem**.)_

Each ship is located at an integer point on the sea represented by a cartesian plane, and each integer point may contain at most 1 ship.

You have a function `Sea.hasShips(topRight, bottomLeft)` which takes two points as arguments and returns `true` If there is at least one ship in the rectangle represented by the two points, including on the boundary.

Given two points: the top right and bottom left corners of a rectangle, return the number of ships present in that rectangle. It is guaranteed that there are **at most 10 ships** in that rectangle.

Submissions making **more than 400 calls** to `hasShips` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification.

**Example :**

**Input:**
ships = \[\[1,1\],\[2,2\],\[3,3\],\[5,5\]\], topRight = \[4,4\], bottomLeft = \[0,0\]
**Output:** 3
**Explanation:** From \[0,0\] to \[4,4\] we can count 3 ships within the range.

**Example 2:**

**Input:** ans = \[\[1,1\],\[2,2\],\[3,3\]\], topRight = \[1000,1000\], bottomLeft = \[0,0\]
**Output:** 3

**Constraints:**

*   On the input `ships` is only given to initialize the map internally. You must solve this problem "blindfolded ". In other words, you must find the answer using the given `hasShips` API, without knowing the `ships` position.
*   `0 <= bottomLeft[0] <= topRight[0] <= 1000`
*   `0 <= bottomLeft[1] <= topRight[1] <= 1000`
*   `topRight != bottomLeft`

## A solution in Java

```java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public int countDaysBetweenDates(String date1, String date2) {
    LocalDate localDate1 = LocalDate.parse(date1);
    LocalDate localDate2 = LocalDate.parse(date2);
    return (int)ChronoUnit.DAYS.between(localDate1, localDate2);
}
```
The algorithm to calculate the number of days between two dates is the same for all languages. First, parse the input strings into date objects. Then, calculate the time difference between the two date objects. Finally, convert the time difference into days.

For C++, we use `istringstream`, `tm`, and `get_time` for string parsing, and `mktime` and `difftime` for time calculation.

For Java, we use `LocalDate.parse` and `ChronoUnit.DAYS.between` methods from the java.time package.

For Python, we use `datetime.strptime` for string parsing and calculate the difference using the `-` (minus) operator.

For JavaScript, we parse the input strings into date objects using the `Date` constructor and calculate the time difference by subtracting them directly. Finally, we convert the time difference (in milliseconds) to days.

## A solution in C++

```cpp
#include <ctime>
#include <iostream>
#include <sstream>

int countDaysBetweenDates(const std::string& date1, const std::string& date2) {
    std::tm tm1 = {}, tm2 = {};
    std::istringstream ss1(date1), ss2(date2);
    ss1 >> std::get_time(&tm1, "%Y-%m-%d");
    ss2 >> std::get_time(&tm2, "%Y-%m-%d");

    std::time_t time1 = std::mktime(&tm1);
    std::time_t time2 = std::mktime(&tm2);
    double difference = std::difftime(time2, time1);
    return difference / 86400;
}
```
The algorithm to calculate the number of days between two dates is the same for all languages. First, parse the input strings into date objects. Then, calculate the time difference between the two date objects. Finally, convert the time difference into days.

For C++, we use `istringstream`, `tm`, and `get_time` for string parsing, and `mktime` and `difftime` for time calculation.

For Java, we use `LocalDate.parse` and `ChronoUnit.DAYS.between` methods from the java.time package.

For Python, we use `datetime.strptime` for string parsing and calculate the difference using the `-` (minus) operator.

For JavaScript, we parse the input strings into date objects using the `Date` constructor and calculate the time difference by subtracting them directly. Finally, we convert the time difference (in milliseconds) to days.

## A solution in Python

```python
from datetime import datetime

def countDaysBetweenDates(date1, date2):
    d1 = datetime.strptime(date1, "%Y-%m-%d")
    d2 = datetime.strptime(date2, "%Y-%m-%d")
    return abs((d2 - d1).days)
```
The algorithm to calculate the number of days between two dates is the same for all languages. First, parse the input strings into date objects. Then, calculate the time difference between the two date objects. Finally, convert the time difference into days.

For C++, we use `istringstream`, `tm`, and `get_time` for string parsing, and `mktime` and `difftime` for time calculation.

For Java, we use `LocalDate.parse` and `ChronoUnit.DAYS.between` methods from the java.time package.

For Python, we use `datetime.strptime` for string parsing and calculate the difference using the `-` (minus) operator.

For JavaScript, we parse the input strings into date objects using the `Date` constructor and calculate the time difference by subtracting them directly. Finally, we convert the time difference (in milliseconds) to days.

## A solution in Javascript

```javascript
function countDaysBetweenDates(date1, date2) {
    const d1 = new Date(date1);
    const d2 = new Date(date2);
    const difference = Math.abs(d2 - d1);
    return Math.floor(difference / (1000 * 3600 * 24));
}
```
The algorithm to calculate the number of days between two dates is the same for all languages. First, parse the input strings into date objects. Then, calculate the time difference between the two date objects. Finally, convert the time difference into days.

For C++, we use `istringstream`, `tm`, and `get_time` for string parsing, and `mktime` and `difftime` for time calculation.

For Java, we use `LocalDate.parse` and `ChronoUnit.DAYS.between` methods from the java.time package.

For Python, we use `datetime.strptime` for string parsing and calculate the difference using the `-` (minus) operator.

For JavaScript, we parse the input strings into date objects using the `Date` constructor and calculate the time difference by subtracting them directly. Finally, we convert the time difference (in milliseconds) to days.


# Find Winner on a Tic Tac Toe Game

- slug: find-winner-on-a-tic-tac-toe-game
- difficulty: Easy

**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are:

*   Players take turns placing characters into empty squares `' '`.
*   The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters.
*   `'X'` and `'O'` characters are always placed into empty squares, never on filled ones.
*   The game ends when there are **three** of the same (non-empty) character filling any row, column, or diagonal.
*   The game also ends if all squares are non-empty.
*   No more moves can be played if the game is over.

Given a 2D integer array `moves` where `moves[i] = [rowi, coli]` indicates that the `ith` move will be played on `grid[rowi][coli]`. return _the winner of the game if it exists_ (`A` or `B`). In case the game ends in a draw return `"Draw "`. If there are still movements to play return `"Pending "`.

You can assume that `moves` is valid (i.e., it follows the rules of **Tic-Tac-Toe**), the grid is initially empty, and `A` will play first.

**Example 1:**

**Input:** moves = \[\[0,0\],\[2,0\],\[1,1\],\[2,1\],\[2,2\]\]
**Output:**  "A "
**Explanation:** A wins, they always play first.

**Example 2:**

**Input:** moves = \[\[0,0\],\[1,1\],\[0,1\],\[0,2\],\[1,0\],\[2,0\]\]
**Output:**  "B "
**Explanation:** B wins.

**Example 3:**

**Input:** moves = \[\[0,0\],\[1,1\],\[2,0\],\[1,0\],\[1,2\],\[2,1\],\[0,1\],\[0,2\],\[2,2\]\]
**Output:**  "Draw "
**Explanation:** The game ends in a draw since there are no moves to make.

**Constraints:**

*   `1 <= moves.length <= 9`
*   `moves[i].length == 2`
*   `0 <= rowi, coli <= 2`
*   There are no repeated elements on `moves`.
*   `moves` follow the rules of tic tac toe.

## A solution in Java

```java
public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
    int[] parent = new int[n];
    Arrays.fill(parent, -1);
    for (int i = 0; i < n; i++) {
        if (leftChild[i] != -1) {
            if (parent[leftChild[i]] != -1) return false;
            parent[leftChild[i]] = i;
        }
        if (rightChild[i] != -1) {
            if (parent[rightChild[i]] != -1) return false;
            parent[rightChild[i]] = i;
        }
    }
    int root = -1;
    for (int i = 0; i < n; i++) {
        if (parent[i] == -1) {
            if (root != -1) return false;
            root = i;
        }
    }
    return root != -1;
}
```
1. Create an array `parent` to keep track of the parent of each node. Initialize each element to -1.
2. Iterate through each node i:
   a. Check the left child of i. If it's not -1, check if it already has a parent. If it does, return false (two parents for a node makes it an invalid tree). Set the parent of the left child to i.
   b. Do the same for the right child.
3. Iterate through the parent array to find a node without a parent (root). If a root is found and another node without a parent is found later, return false (more than one tree).
4. If a root is found, return true (a valid tree). Otherwise, return false (no tree found).

## A solution in C++

```cpp
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
    vector<int> parent(n, -1);
    for (int i = 0; i < n; ++i) {
        if (leftChild[i] != -1) {
            if (parent[leftChild[i]] != -1) return false;
            parent[leftChild[i]] = i;
        }
        if (rightChild[i] != -1) {
            if (parent[rightChild[i]] != -1) return false;
            parent[rightChild[i]] = i;
        }
    }
    int root = -1;
    for (int i = 0; i < n; ++i) {
        if (parent[i] == -1) {
            if (root != -1) return false;
            root = i;
        }
    }
    return root != -1;
}
```
1. Create an array `parent` to keep track of the parent of each node. Initialize each element to -1.
2. Iterate through each node i:
   a. Check the left child of i. If it's not -1, check if it already has a parent. If it does, return false (two parents for a node makes it an invalid tree). Set the parent of the left child to i.
   b. Do the same for the right child.
3. Iterate through the parent array to find a node without a parent (root). If a root is found and another node without a parent is found later, return false (more than one tree).
4. If a root is found, return true (a valid tree). Otherwise, return false (no tree found).

## A solution in Python

```python
def validateBinaryTreeNodes(n, leftChild, rightChild):
    parent = [-1] * n
    for i in range(n):
        if leftChild[i] != -1:
            if parent[leftChild[i]] != -1:
                return False
            parent[leftChild[i]] = i
        if rightChild[i] != -1:
            if parent[rightChild[i]] != -1:
                return False
            parent[rightChild[i]] = i

    root = -1
    for i in range(n):
        if parent[i] == -1:
            if root != -1:
                return False
            root = i

    return root != -1
```
1. Create an array `parent` to keep track of the parent of each node. Initialize each element to -1.
2. Iterate through each node i:
   a. Check the left child of i. If it's not -1, check if it already has a parent. If it does, return false (two parents for a node makes it an invalid tree). Set the parent of the left child to i.
   b. Do the same for the right child.
3. Iterate through the parent array to find a node without a parent (root). If a root is found and another node without a parent is found later, return false (more than one tree).
4. If a root is found, return true (a valid tree). Otherwise, return false (no tree found).

## A solution in Javascript

```javascript
function validateBinaryTreeNodes(n, leftChild, rightChild) {
    const parent = new Array(n).fill(-1);
    for (let i = 0; i < n; i++) {
        if (leftChild[i] !== -1) {
            if (parent[leftChild[i]] !== -1) return false;
            parent[leftChild[i]] = i;
        }
        if (rightChild[i] !== -1) {
            if (parent[rightChild[i]] !== -1) return false;
            parent[rightChild[i]] = i;
        }
    }
    let root = -1;
    for (let i = 0; i < n; i++) {
        if (parent[i] === -1) {
            if (root !== -1) return false;
            root = i;
        }
    }
    return root !== -1;
}
```
1. Create an array `parent` to keep track of the parent of each node. Initialize each element to -1.
2. Iterate through each node i:
   a. Check the left child of i. If it's not -1, check if it already has a parent. If it does, return false (two parents for a node makes it an invalid tree). Set the parent of the left child to i.
   b. Do the same for the right child.
3. Iterate through the parent array to find a node without a parent (root). If a root is found and another node without a parent is found later, return false (more than one tree).
4. If a root is found, return true (a valid tree). Otherwise, return false (no tree found).


# Number of Burgers with No Waste of Ingredients

- slug: number-of-burgers-with-no-waste-of-ingredients
- difficulty: Medium

Given two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows:

*   **Jumbo Burger:** `4` tomato slices and `1` cheese slice.
*   **Small Burger:** `2` Tomato slices and `1` cheese slice.

Return `[total_jumbo, total_small]` so that the number of remaining `tomatoSlices` equal to `0` and the number of remaining `cheeseSlices` equal to `0`. If it is not possible to make the remaining `tomatoSlices` and `cheeseSlices` equal to `0` return `[]`.

**Example 1:**

**Input:** tomatoSlices = 16, cheeseSlices = 7
**Output:** \[1,6\]
**Explantion:** To make one jumbo burger and 6 small burgers we need 4\*1 + 2\*6 = 16 tomato and 1 + 6 = 7 cheese.
There will be no remaining ingredients.

**Example 2:**

**Input:** tomatoSlices = 17, cheeseSlices = 4
**Output:** \[\]
**Explantion:** There will be no way to use all ingredients to make small and jumbo burgers.

**Example 3:**

**Input:** tomatoSlices = 4, cheeseSlices = 17
**Output:** \[\]
**Explantion:** Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.

**Constraints:**

*   `0 <= tomatoSlices, cheeseSlices <= 107`

## A solution in Java

```java
public int[] closestFactors(int num) {
    int factor1 = (int) Math.sqrt(num + 2);
    while (true) {
        int factor2 = (num + 2) / factor1;
        if (factor1 * factor2 == num + 2) {
            return new int[] {factor1, factor2};
        }
        factor2 = (num + 1) / factor1;
        if (factor1 * factor2 == num + 1) {
            return new int[] {factor1, factor2};
        }
        factor1--;
    }
}
```
1. Initialize factor1 as the square root of num + 2, rounded down to an integer.
2. In an infinite loop (which will eventually be broken), do the following:
3. Calculate factor2 as the integer division of (num + 2) by factor1. Check if the product of factor1 and factor2 equals num + 2; if so, return the pair (factor1, factor2).
4. Calculate factor2 as the integer division of (num + 1) by factor1. Check if the product of factor1 and factor2 equals num + 1; if so, return the pair (factor1, factor2).
5. If neither multiplication has produced num + 1 or num + 2, decrement factor1 and continue to the next iteration.
6. Since the loop will eventually find a valid pair of factors, this algorithm will always return a solution.

## A solution in C++

```cpp
std::pair<int, int> closestFactors(int num) {
    int factor1 = std::sqrt(num + 2);
    while (true) {
        int factor2 = (num + 2) / factor1;
        if (factor1 * factor2 == num + 2) {
            return std::make_pair(factor1, factor2);
        }
        factor2 = (num + 1) / factor1;
        if (factor1 * factor2 == num + 1) {
            return std::make_pair(factor1, factor2);
        }
        factor1--;
    }
}
```
1. Initialize factor1 as the square root of num + 2, rounded down to an integer.
2. In an infinite loop (which will eventually be broken), do the following:
3. Calculate factor2 as the integer division of (num + 2) by factor1. Check if the product of factor1 and factor2 equals num + 2; if so, return the pair (factor1, factor2).
4. Calculate factor2 as the integer division of (num + 1) by factor1. Check if the product of factor1 and factor2 equals num + 1; if so, return the pair (factor1, factor2).
5. If neither multiplication has produced num + 1 or num + 2, decrement factor1 and continue to the next iteration.
6. Since the loop will eventually find a valid pair of factors, this algorithm will always return a solution.

## A solution in Python

```python
def closest_factors(num):
    factor1 = int((num + 2) ** 0.5)
    while True:
        factor2 = (num + 2) // factor1
        if factor1 * factor2 == num + 2:
            return factor1, factor2
        factor2 = (num + 1) // factor1
        if factor1 * factor2 == num + 1:
            return factor1, factor2
        factor1 -= 1
```
1. Initialize factor1 as the square root of num + 2, rounded down to an integer.
2. In an infinite loop (which will eventually be broken), do the following:
3. Calculate factor2 as the integer division of (num + 2) by factor1. Check if the product of factor1 and factor2 equals num + 2; if so, return the pair (factor1, factor2).
4. Calculate factor2 as the integer division of (num + 1) by factor1. Check if the product of factor1 and factor2 equals num + 1; if so, return the pair (factor1, factor2).
5. If neither multiplication has produced num + 1 or num + 2, decrement factor1 and continue to the next iteration.
6. Since the loop will eventually find a valid pair of factors, this algorithm will always return a solution.

## A solution in Javascript

```javascript
function closestFactors(num) {
    let factor1 = Math.floor(Math.sqrt(num + 2));
    while (true) {
        let factor2 = Math.floor((num + 2) / factor1);
        if (factor1 * factor2 === num + 2) {
            return [factor1, factor2];
        }
        factor2 = Math.floor((num + 1) / factor1);
        if (factor1 * factor2 === num + 1) {
            return [factor1, factor2];
        }
        factor1--;
    }
}
```
1. Initialize factor1 as the square root of num + 2, rounded down to an integer.
2. In an infinite loop (which will eventually be broken), do the following:
3. Calculate factor2 as the integer division of (num + 2) by factor1. Check if the product of factor1 and factor2 equals num + 2; if so, return the pair (factor1, factor2).
4. Calculate factor2 as the integer division of (num + 1) by factor1. Check if the product of factor1 and factor2 equals num + 1; if so, return the pair (factor1, factor2).
5. If neither multiplication has produced num + 1 or num + 2, decrement factor1 and continue to the next iteration.
6. Since the loop will eventually find a valid pair of factors, this algorithm will always return a solution.


# Count Square Submatrices with All Ones

- slug: count-square-submatrices-with-all-ones
- difficulty: Medium

Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones.

**Example 1:**

**Input:** matrix =
\[
  \[0,1,1,1\],
  \[1,1,1,1\],
  \[0,1,1,1\]
\]
**Output:** 15
**Explanation:**
There are **10** squares of side 1.
There are **4** squares of side 2.
There is  **1** square of side 3.
Total number of squares = 10 + 4 + 1 = **15**.

**Example 2:**

**Input:** matrix =
\[
  \[1,0,1\],
  \[1,1,0\],
  \[1,1,0\]
\]
**Output:** 7
**Explanation:**
There are **6** squares of side 1.
There is **1** square of side 2.
Total number of squares = 6 + 1 = **7**.

**Constraints:**

*   `1 <= arr.length <= 300`
*   `1 <= arr[0].length <= 300`
*   `0 <= arr[i][j] <= 1`

## A solution in Java

```java
import java.util.*;

public String largestMultipleOfThree(int[] digits) {
    int sum = 0, count[] = new int[3];

    for (int d : digits) {
        sum += d;
        count[d % 3]++;
    }

    if (sum % 3 == 1) {
        if (count[1] >= 1) count[1]--;
        else count[2] -= 2;
    }
    else if (sum % 3 == 2) {
        if (count[2] >= 1) count[2]--;
        else count[1] -= 2;
    }

    StringBuilder res = new StringBuilder();
    for (int i = 0; i <= 9; ++i) {
        int n = count[i % 3];
        while (n-- > 0) res.append(i);
    }

    if (res.length() != 0 && res.charAt(res.length() - 1) == '0') return "0";
    return res.reverse().toString();
}
```
1. Calculate the sum of all digits in the input array, and maintain a count of each digit's frequency based on its value modulo 3.
2. If the sum modulo 3 is 1, remove either 1 element with value modulo 3 equals to 1 or remove 2 elements with value modulo 3 equals to 2.
3. If the sum modulo 3 is 2, remove either 1 element with value modulo 3 equals to 2 or remove 2 elements with value modulo 3 equals to 1.
4. Build the result string by iterating from 0 to 9, appending the digits remaining in 'count' array in descending order.
5. If the result string is non-empty and its last character is '0', return "0" since there are no unnecessary leading zeros.
6. Otherwise, reverse the result string and return it as the final answer.

## A solution in C++

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

std::string largestMultipleOfThree(std::vector<int>& digits) {
    int sum = 0, count[3] = {0};

    for (int d : digits) {
        sum += d;
        count[d % 3]++;
    }

    if (sum % 3 == 1) {
        if (count[1] >= 1) count[1]--;
        else count[2] -= 2;
    }
    else if (sum % 3 == 2) {
        if (count[2] >= 1) count[2]--;
        else count[1] -= 2;
    }

    std::string res = "";
    for (int i = 0; i <= 9; ++i) {
        int n = count[i % 3];
        while (n--) res += std::to_string(i);
    }

    if (!res.empty() && res.back() == '0') return "0";
    std::reverse(res.begin(), res.end());
    return res;
}
```
1. Calculate the sum of all digits in the input array, and maintain a count of each digit's frequency based on its value modulo 3.
2. If the sum modulo 3 is 1, remove either 1 element with value modulo 3 equals to 1 or remove 2 elements with value modulo 3 equals to 2.
3. If the sum modulo 3 is 2, remove either 1 element with value modulo 3 equals to 2 or remove 2 elements with value modulo 3 equals to 1.
4. Build the result string by iterating from 0 to 9, appending the digits remaining in 'count' array in descending order.
5. If the result string is non-empty and its last character is '0', return "0" since there are no unnecessary leading zeros.
6. Otherwise, reverse the result string and return it as the final answer.

## A solution in Python

```python
def largest_multiple_of_three(digits):
    count = [0] * 3
    num_sum = sum(digits)

    for d in digits:
        count[d % 3] += 1

    if num_sum % 3 == 1:
        if count[1] >= 1:
            count[1] -= 1
        else:
            count[2] -= 2
    elif num_sum % 3 == 2:
        if count[2] >= 1:
            count[2] -= 1
        else:
            count[1] -= 2

    res = ""
    for i in range(10):
        res += str(i) * count[i % 3]

    if res and res[-1] == "0":
        return "0"
    return res[::-1]
```
1. Calculate the sum of all digits in the input array, and maintain a count of each digit's frequency based on its value modulo 3.
2. If the sum modulo 3 is 1, remove either 1 element with value modulo 3 equals to 1 or remove 2 elements with value modulo 3 equals to 2.
3. If the sum modulo 3 is 2, remove either 1 element with value modulo 3 equals to 2 or remove 2 elements with value modulo 3 equals to 1.
4. Build the result string by iterating from 0 to 9, appending the digits remaining in 'count' array in descending order.
5. If the result string is non-empty and its last character is '0', return "0" since there are no unnecessary leading zeros.
6. Otherwise, reverse the result string and return it as the final answer.

## A solution in Javascript

```javascript
function largestMultipleOfThree(digits) {
    let sum = 0, count = [0, 0, 0];

    for (let d of digits) {
        sum += d;
        count[d % 3]++;
    }

    if (sum % 3 === 1) {
        if (count[1] >= 1) count[1]--;
        else count[2] -= 2;
    }
    else if (sum % 3 === 2) {
        if (count[2] >= 1) count[2]--;
        else count[1] -= 2;
    }

    let res = "";
    for (let i = 0; i <= 9; ++i) {
        let n = count[i % 3];
        while (n--) res += i;
    }

    if (res.length !== 0 && res[res.length - 1] === '0') return "0";
    return res.split("").reverse().join("");
}
```
1. Calculate the sum of all digits in the input array, and maintain a count of each digit's frequency based on its value modulo 3.
2. If the sum modulo 3 is 1, remove either 1 element with value modulo 3 equals to 1 or remove 2 elements with value modulo 3 equals to 2.
3. If the sum modulo 3 is 2, remove either 1 element with value modulo 3 equals to 2 or remove 2 elements with value modulo 3 equals to 1.
4. Build the result string by iterating from 0 to 9, appending the digits remaining in 'count' array in descending order.
5. If the result string is non-empty and its last character is '0', return "0" since there are no unnecessary leading zeros.
6. Otherwise, reverse the result string and return it as the final answer.


# Palindrome Partitioning III

- slug: palindrome-partitioning-iii
- difficulty: Hard

You are given a string `s` containing lowercase letters and an integer `k`. You need to :

*   First, change some characters of `s` to other lowercase English letters.
*   Then divide `s` into `k` non-empty disjoint substrings such that each substring is a palindrome.

Return _the minimal number of characters that you need to change to divide the string_.

**Example 1:**

**Input:** s =  "abc ", k = 2
**Output:** 1
**Explanation:** You can split the string into  "ab " and  "c ", and change 1 character in  "ab " to make it palindrome.

**Example 2:**

**Input:** s =  "aabbc ", k = 3
**Output:** 0
**Explanation:** You can split the string into  "aa ",  "bb " and  "c ", all of them are palindrome.

**Example 3:**

**Input:** s =  "leetcode ", k = 8
**Output:** 0

**Constraints:**

*   `1 <= k <= s.length <= 100`.
*   `s` only contains lowercase English letters.

## A solution in Java

```java
public int palindromePartition(String s, int k) {
    int n = s.length();
    int[][] dp = new int[n][n];

    for (int len = 2; len <= n; ++len) {
        for (int i = 0; i <= n - len; ++i) {
            int j = i + len - 1;
            dp[i][j] = dp[i + 1][j - 1] + (s.charAt(i) != s.charAt(j) ? 1 : 0);
        }
    }

    int[] memo = new int[n];
    for (int i = 0; i < n; ++i) {
        if (dp[0][i] == 0) {
            memo[i] = 0;
        } else {
            memo[i] = Integer.MAX_VALUE;
            for (int j = 0; j < i; ++j) {
                memo[i] = Math.min(memo[i], memo[j] + dp[j + 1][i]);
            }
        }
    }

    return memo[memo.length - 1] + k;
}
```
The core of this solution consists of two steps:

1. Compute the minimum number of changes required to convert each substring `s[i:j]` into a palindrome.
2. Find the minimum number of changes needed to split the input string into `k` palindromes.

Step 1 is performed by the dynamic programming approach. A 2D DP array is created to store the number of changes needed to make a substring a palindrome. The nested loop iterates over different lengths of substrings and computes the minimum changes necessary to make it palindrome. It fills the DP array with these values.

Step 2 also employs dynamic programming. It iterates through the input string and keeps track of the number of changes required to convert the substrings into palindromes. If a substring `[0:i]` is palindrome, no changes are needed. Otherwise, the number of changes is updated by iterating through each element and choosing the minimum cost necessary to make it palindrome.

Finally, it returns the sum of the number of changes in the memo array's last element and `k`.

## A solution in C++

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

int palindromePartition(std::string s, int k) {
    int n = s.size();
    std::vector<std::vector<int>> dp(n, std::vector<int>(n, 0));

    for (int len = 2; len <= n; ++len) {
        for (int i = 0; i <= n - len; ++i) {
            int j = i + len - 1;
            dp[i][j] = dp[i + 1][j - 1] + (s[i] != s[j]);
        }
    }

    std::vector<int> memo(n, 1e9);
    for (int i = 0; i < n; ++i) {
        if (dp[0][i] == 0) {
            memo[i] = 0;
        } else {
            for (int j = 0; j < i; ++j) {
                memo[i] = std::min(memo[i], memo[j] + dp[j + 1][i]);
            }
        }
    }

    return memo.back() + k;
}
```
The core of this solution consists of two steps:

1. Compute the minimum number of changes required to convert each substring `s[i:j]` into a palindrome.
2. Find the minimum number of changes needed to split the input string into `k` palindromes.

Step 1 is performed by the dynamic programming approach. A 2D DP array is created to store the number of changes needed to make a substring a palindrome. The nested loop iterates over different lengths of substrings and computes the minimum changes necessary to make it palindrome. It fills the DP array with these values.

Step 2 also employs dynamic programming. It iterates through the input string and keeps track of the number of changes required to convert the substrings into palindromes. If a substring `[0:i]` is palindrome, no changes are needed. Otherwise, the number of changes is updated by iterating through each element and choosing the minimum cost necessary to make it palindrome.

Finally, it returns the sum of the number of changes in the memo array's last element and `k`.

## A solution in Python

```python
def palindromePartition(s: str, k: int) -> int:
    n = len(s)
    dp = [[0] * n for _ in range(n)]

    for len in range(2, n + 1):
        for i in range(n - len + 1):
            j = i + len - 1
            dp[i][j] = dp[i + 1][j - 1] + (s[i] != s[j])

    memo = [float('inf')] * n
    for i in range(n):
        if dp[0][i] == 0:
            memo[i] = 0
        else:
            for j in range(i):
                memo[i] = min(memo[i], memo[j] + dp[j + 1][i])

    return memo[-1] + k
```
The core of this solution consists of two steps:

1. Compute the minimum number of changes required to convert each substring `s[i:j]` into a palindrome.
2. Find the minimum number of changes needed to split the input string into `k` palindromes.

Step 1 is performed by the dynamic programming approach. A 2D DP array is created to store the number of changes needed to make a substring a palindrome. The nested loop iterates over different lengths of substrings and computes the minimum changes necessary to make it palindrome. It fills the DP array with these values.

Step 2 also employs dynamic programming. It iterates through the input string and keeps track of the number of changes required to convert the substrings into palindromes. If a substring `[0:i]` is palindrome, no changes are needed. Otherwise, the number of changes is updated by iterating through each element and choosing the minimum cost necessary to make it palindrome.

Finally, it returns the sum of the number of changes in the memo array's last element and `k`.

## A solution in Javascript

```javascript
function palindromePartition(s, k) {
    const n = s.length;
    const dp = Array.from(Array(n), () => Array(n).fill(0));

    for (let len = 2; len <= n; ++len) {
        for (let i = 0; i <= n - len; ++i) {
            const j = i + len - 1;
            dp[i][j] = dp[i + 1][j - 1] + (s[i] !== s[j] ? 1 : 0);
        }
    }

    const memo = Array(n).fill(1e9);
    for (let i = 0; i < n; ++i) {
        if (dp[0][i] === 0) {
            memo[i] = 0;
        } else {
            for (let j = 0; j < i; ++j) {
                memo[i] = Math.min(memo[i], memo[j] + dp[j + 1][i]);
            }
        }
    }

    return memo[memo.length - 1] + k;
}
```
The core of this solution consists of two steps:

1. Compute the minimum number of changes required to convert each substring `s[i:j]` into a palindrome.
2. Find the minimum number of changes needed to split the input string into `k` palindromes.

Step 1 is performed by the dynamic programming approach. A 2D DP array is created to store the number of changes needed to make a substring a palindrome. The nested loop iterates over different lengths of substrings and computes the minimum changes necessary to make it palindrome. It fills the DP array with these values.

Step 2 also employs dynamic programming. It iterates through the input string and keeps track of the number of changes required to convert the substrings into palindromes. If a substring `[0:i]` is palindrome, no changes are needed. Otherwise, the number of changes is updated by iterating through each element and choosing the minimum cost necessary to make it palindrome.

Finally, it returns the sum of the number of changes in the memo array's last element and `k`.


# Subtract the Product and Sum of Digits of an Integer

- slug: subtract-the-product-and-sum-of-digits-of-an-integer
- difficulty: Easy

Given an integer number `n`, return the difference between the product of its digits and the sum of its digits.

**Example 1:**

**Input:** n = 234
**Output:** 15
**Explanation:**
Product of digits = 2 \* 3 \* 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15

**Example 2:**

**Input:** n = 4421
**Output:** 21
**Explanation:**
Product of digits = 4 \* 4 \* 2 \* 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21

**Constraints:**

*   `1 <= n <= 10^5`

## A solution in Java

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

public List<Boolean> canMakePaliQueries(String s, int[][] queries) {
    List<Boolean> result = new ArrayList<>();
    for (int[] query : queries) {
        int left = query[0], right = query[1], k = query[2];
        int[] count = new int[26];
        for (int i = left; i <= right; i++) {
            count[s.charAt(i) - 'a']++;
        }
        int odd_count = 0;
        for (int i = 0; i < 26; i++) {
            odd_count += count[i] % 2;
        }
        result.add(odd_count / 2 <= k);
    }
    return result;
}
```
1. Iterate through each query, and get the values of left, right, and k.
2. Create an array count with 26 elements for each English lowercase letter.
3. Iterate from left to right, count occurrences of each letter in the substring s[left...right].
4. Calculate the number of odd counts of the letters.
5. Determine if the number of odd counts divided by 2 is less than or equal to k. If true, append true to the result, otherwise append false.
6. After all queries are processed, return the result array.

## A solution in C++

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

std::vector<bool> canMakePaliQueries(std::string s, std::vector<std::vector<int>>& queries) {
    std::vector<bool> result;
    for (auto& query : queries) {
        int left = query[0], right = query[1], k = query[2];
        int count[26] = {0};
        for (int i = left; i <= right; i++) {
            count[s[i] - 'a']++;
        }
        int odd_count = 0;
        for (int i = 0; i < 26; i++) {
            odd_count += count[i] % 2;
        }
        result.push_back(odd_count / 2 <= k);
    }
    return result;
}
```
1. Iterate through each query, and get the values of left, right, and k.
2. Create an array count with 26 elements for each English lowercase letter.
3. Iterate from left to right, count occurrences of each letter in the substring s[left...right].
4. Calculate the number of odd counts of the letters.
5. Determine if the number of odd counts divided by 2 is less than or equal to k. If true, append true to the result, otherwise append false.
6. After all queries are processed, return the result array.

## A solution in Python

```python
def can_make_pali_queries(s, queries):
    result = []
    for left, right, k in queries:
        count = [0] * 26
        for i in range(left, right + 1):
            count[ord(s[i]) - ord('a')] += 1
        odd_count = sum(c % 2 for c in count)
        result.append(odd_count // 2 <= k)
    return result
```
1. Iterate through each query, and get the values of left, right, and k.
2. Create an array count with 26 elements for each English lowercase letter.
3. Iterate from left to right, count occurrences of each letter in the substring s[left...right].
4. Calculate the number of odd counts of the letters.
5. Determine if the number of odd counts divided by 2 is less than or equal to k. If true, append true to the result, otherwise append false.
6. After all queries are processed, return the result array.

## A solution in Javascript

```javascript
function canMakePaliQueries(s, queries) {
    const result = [];
    for (const query of queries) {
        const [left, right, k] = query;
        const count = Array(26).fill(0);
        for (let i = left; i <= right; i++) {
            count[s.charCodeAt(i) - 97]++;
        }
        const odd_count = count.reduce((acc, val) => acc + (val % 2), 0);
        result.push(Math.floor(odd_count / 2) <= k);
    }
    return result;
}
```
1. Iterate through each query, and get the values of left, right, and k.
2. Create an array count with 26 elements for each English lowercase letter.
3. Iterate from left to right, count occurrences of each letter in the substring s[left...right].
4. Calculate the number of odd counts of the letters.
5. Determine if the number of odd counts divided by 2 is less than or equal to k. If true, append true to the result, otherwise append false.
6. After all queries are processed, return the result array.


# Group the People Given the Group Size They Belong To

- slug: group-the-people-given-the-group-size-they-belong-to
- difficulty: Medium

There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.

You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.

Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.

Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.

**Example 1:**

**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].

**Example 2:**

**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]

**Constraints:**

*   `groupSizes.length == n`
*   `1 <= n <= 500`
*   `1 <= groupSizes[i] <= n`

## A solution in Java

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

public List<List<Integer>> groupThePeople(int[] groupSizes) {
    Map<Integer, List<Integer>> groups = new HashMap<>();
    List<List<Integer>> result = new ArrayList<>();

    for (int i = 0; i < groupSizes.length; i++) {
        groups.computeIfAbsent(groupSizes[i], k -> new ArrayList<>()).add(i);

        if (groups.get(groupSizes[i]).size() == groupSizes[i]) {
            result.add(groups.get(groupSizes[i]));
            groups.put(groupSizes[i], new ArrayList<>());
        }
    }

    return result;
}
```
The algorithm uses a hash map (unordered_map in C++, HashMap in Java, defaultdict in Python, plain object in JavaScript) to store the groups for each group size. For each person, their group size is added as a key if it doesn't exist, and then the person's index is added to the group.

When a group reaches the size defined by the key, it appends this group to the result list and clears the group from the hash map.

Finally, it returns the result list containing the groups with each person in their corresponding group size.

## A solution in C++

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

std::vector<std::vector<int>> groupThePeople(std::vector<int>& groupSizes) {
    std::unordered_map<int, std::vector<int>> groups;
    std::vector<std::vector<int>> result;

    for (int i = 0; i < groupSizes.size(); i++) {
        groups[groupSizes[i]].push_back(i);
        if (groups[groupSizes[i]].size() == groupSizes[i]) {
            result.push_back(groups[groupSizes[i]]);
            groups[groupSizes[i]].clear();
        }
    }

    return result;
}
```
The algorithm uses a hash map (unordered_map in C++, HashMap in Java, defaultdict in Python, plain object in JavaScript) to store the groups for each group size. For each person, their group size is added as a key if it doesn't exist, and then the person's index is added to the group.

When a group reaches the size defined by the key, it appends this group to the result list and clears the group from the hash map.

Finally, it returns the result list containing the groups with each person in their corresponding group size.

## A solution in Python

```python
from collections import defaultdict

def groupThePeople(groupSizes):
    groups = defaultdict(list)
    result = []

    for i, size in enumerate(groupSizes):
        groups[size].append(i)
        if len(groups[size]) == size:
            result.append(groups[size])
            groups[size] = []

    return result
```
The algorithm uses a hash map (unordered_map in C++, HashMap in Java, defaultdict in Python, plain object in JavaScript) to store the groups for each group size. For each person, their group size is added as a key if it doesn't exist, and then the person's index is added to the group.

When a group reaches the size defined by the key, it appends this group to the result list and clears the group from the hash map.

Finally, it returns the result list containing the groups with each person in their corresponding group size.

## A solution in Javascript

```javascript
function groupThePeople(groupSizes) {
    const groups = {};
    const result = [];

    for (let i = 0; i < groupSizes.length; i++) {
        const size = groupSizes[i];
        if (!groups[size]) {
            groups[size] = [];
        }
        groups[size].push(i);

        if (groups[size].length === size) {
            result.push(groups[size]);
            groups[size] = [];
        }
    }

    return result;
}
```
The algorithm uses a hash map (unordered_map in C++, HashMap in Java, defaultdict in Python, plain object in JavaScript) to store the groups for each group size. For each person, their group size is added as a key if it doesn't exist, and then the person's index is added to the group.

When a group reaches the size defined by the key, it appends this group to the result list and clears the group from the hash map.

Finally, it returns the result list containing the groups with each person in their corresponding group size.


# Find the Smallest Divisor Given a Threshold

- slug: find-the-smallest-divisor-given-a-threshold
- difficulty: Medium

Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.

Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: `7/3 = 3` and `10/2 = 5`).

The test cases are generated so that there will be an answer.

**Example 1:**

**Input:** nums = \[1,2,5,9\], threshold = 6
**Output:** 5
**Explanation:** We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).

**Example 2:**

**Input:** nums = \[44,22,33,11,1\], threshold = 5
**Output:** 44

**Constraints:**

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

## A solution in Java

```java
import java.util.HashMap;

public class DateFormatter {

    public static String formatDate(String date) {
        HashMap<String, String> months = new HashMap<>();
        months.put("Jan", "01");
        months.put("Feb", "02");
        months.put("Mar", "03");
        months.put("Apr", "04");
        months.put("May", "05");
        months.put("Jun", "06");
        months.put("Jul", "07");
        months.put("Aug", "08");
        months.put("Sep", "09");
        months.put("Oct", "10");
        months.put("Nov", "11");
        months.put("Dec", "12");

        String[] parts = date.split(" ");
        String day = parts[0], month = parts[1], year = parts[2];
        return year + "-" + months.get(month) + "-" + day;
    }
}
```
The algorithm first creates a mapping of month names to their numerical values. It then splits the input date string into three parts: day, month, and year. Finally, it constructs a new date string in the format "YYYY-MM-DD" using the mapping for the month and returns the result. This logic is implemented in each of the four languages.

## A solution in C++

```cpp
#include <iostream>
#include <sstream>
#include <unordered_map>

std::string format_date(const std::string &date) {
    std::unordered_map<std::string, std::string> months = {
        {"Jan", "01"},
        {"Feb", "02"},
        {"Mar", "03"},
        {"Apr", "04"},
        {"May", "05"},
        {"Jun", "06"},
        {"Jul", "07"},
        {"Aug", "08"},
        {"Sep", "09"},
        {"Oct", "10"},
        {"Nov", "11"},
        {"Dec", "12"},
    };

    std::stringstream ss(date);
    std::string day, month, year;
    ss >> day >> month >> year;
    return year + "-" + months[month] + "-" + day;
}
```
The algorithm first creates a mapping of month names to their numerical values. It then splits the input date string into three parts: day, month, and year. Finally, it constructs a new date string in the format "YYYY-MM-DD" using the mapping for the month and returns the result. This logic is implemented in each of the four languages.

## A solution in Python

```python
def format_date(date):
    months = {
        "Jan": "01",
        "Feb": "02",
        "Mar": "03",
        "Apr": "04",
        "May": "05",
        "Jun": "06",
        "Jul": "07",
        "Aug": "08",
        "Sep": "09",
        "Oct": "10",
        "Nov": "11",
        "Dec": "12",
    }

    day, month, year = date.split()
    return f"{year}-{months[month]}-{day}"
```
The algorithm first creates a mapping of month names to their numerical values. It then splits the input date string into three parts: day, month, and year. Finally, it constructs a new date string in the format "YYYY-MM-DD" using the mapping for the month and returns the result. This logic is implemented in each of the four languages.

## A solution in Javascript

```javascript
function formatDate(date) {
    const months = {
        "Jan": "01",
        "Feb": "02",
        "Mar": "03",
        "Apr": "04",
        "May": "05",
        "Jun": "06",
        "Jul": "07",
        "Aug": "08",
        "Sep": "09",
        "Oct": "10",
        "Nov": "11",
        "Dec": "12",
    };

    const [day, month, year] = date.split(" ");
    return `${year}-${months[month]}-${day}`;
}
```
The algorithm first creates a mapping of month names to their numerical values. It then splits the input date string into three parts: day, month, and year. Finally, it constructs a new date string in the format "YYYY-MM-DD" using the mapping for the month and returns the result. This logic is implemented in each of the four languages.


# Minimum Number of Flips to Convert Binary Matrix to Zero Matrix

- slug: minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix
- difficulty: Hard

Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edge.

Return the _minimum number of steps_ required to convert `mat` to a zero matrix or `-1` if you cannot.

A **binary matrix** is a matrix with all cells equal to `0` or `1` only.

A **zero matrix** is a matrix with all cells equal to `0`.

**Example 1:**

**Input:** mat = \[\[0,0\],\[0,1\]\]
**Output:** 3
**Explanation:** One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.

**Example 2:**

**Input:** mat = \[\[0\]\]
**Output:** 0
**Explanation:** Given matrix is a zero matrix. We do not need to change it.

**Example 3:**

**Input:** mat = \[\[1,0,0\],\[1,0,0\]\]
**Output:** -1
**Explanation:** Given matrix cannot be a zero matrix.

**Constraints:**

*   `m == mat.length`
*   `n == mat[i].length`
*   `1 <= m, n <= 3`
*   `mat[i][j]` is either `0` or `1`.

## A solution in Java

```java
public int sumOfDivisorsWithFourDivisors(int[] nums) {
    int sum = 0;
    for (int num : nums) {
        int divCount = 0;
        int divSum = 0;

        for (int i = 1; i * i <= num; ++i) {
            if (num % i == 0) {
                divSum += i;
                ++divCount;

                if (num / i != i) {
                    divSum += (num / i);
                    ++divCount;
                }
            }

            if (divCount > 4) {
                break;
            }
        }

        if (divCount == 4) {
            sum += divSum;
        }
    }

    return sum;
}
```
The algorithm starts by initializing a sum variable that will be used to store the sum of all divisors for the numbers with exactly four divisors. Then, we loop through each number in the input array. For each number, we initialize a div_count and div_sum variable to count the number of divisors and to store the sum of its divisors, respectively.

Inside the loop, we iterate from 1 to the square root of the current number (inclusive) using another loop. For each iteration, we check if the current number is divisible by the iterating variable 'i'. If it is, we add 'i' to the div_sum and increment the div_count. Next, we check if the result of the division (num / i) is different from 'i' and, if so, we add it to div_sum and increment div_count as well.

After checking all divisors, we exit the inner loop and check if div_count is equal to 4. If it is, we add div_sum to the total sum. The process continues until we reach the end of the input array.

Finally, we return the total sum.

## A solution in C++

```cpp
int sum_of_divisors_with_four_divisors(const std::vector<int>& nums) {
    int sum = 0;
    for (int num : nums) {
        int div_count = 0;
        int div_sum = 0;

        for (int i = 1; i * i <= num; ++i) {
            if (num % i == 0) {
                div_sum += i;
                ++div_count;

                if (num / i != i) {
                    div_sum += (num / i);
                    ++div_count;
                }
            }

            if (div_count > 4) {
                break;
            }
        }

        if (div_count == 4) {
            sum += div_sum;
        }
    }

    return sum;
}
```
The algorithm starts by initializing a sum variable that will be used to store the sum of all divisors for the numbers with exactly four divisors. Then, we loop through each number in the input array. For each number, we initialize a div_count and div_sum variable to count the number of divisors and to store the sum of its divisors, respectively.

Inside the loop, we iterate from 1 to the square root of the current number (inclusive) using another loop. For each iteration, we check if the current number is divisible by the iterating variable 'i'. If it is, we add 'i' to the div_sum and increment the div_count. Next, we check if the result of the division (num / i) is different from 'i' and, if so, we add it to div_sum and increment div_count as well.

After checking all divisors, we exit the inner loop and check if div_count is equal to 4. If it is, we add div_sum to the total sum. The process continues until we reach the end of the input array.

Finally, we return the total sum.

## A solution in Python

```python
def sum_of_divisors_with_four_divisors(nums):
    total_sum = 0

    for num in nums:
        div_count = 0
        div_sum = 0

        for i in range(1, int(num ** 0.5) + 1):
            if num % i == 0:
                div_sum += i
                div_count += 1

                if num // i != i:
                    div_sum += num // i
                    div_count += 1

            if div_count > 4:
                break

        if div_count == 4:
            total_sum += div_sum

    return total_sum
```
The algorithm starts by initializing a sum variable that will be used to store the sum of all divisors for the numbers with exactly four divisors. Then, we loop through each number in the input array. For each number, we initialize a div_count and div_sum variable to count the number of divisors and to store the sum of its divisors, respectively.

Inside the loop, we iterate from 1 to the square root of the current number (inclusive) using another loop. For each iteration, we check if the current number is divisible by the iterating variable 'i'. If it is, we add 'i' to the div_sum and increment the div_count. Next, we check if the result of the division (num / i) is different from 'i' and, if so, we add it to div_sum and increment div_count as well.

After checking all divisors, we exit the inner loop and check if div_count is equal to 4. If it is, we add div_sum to the total sum. The process continues until we reach the end of the input array.

Finally, we return the total sum.

## A solution in Javascript

```javascript
function sumOfDivisorsWithFourDivisors(nums) {
    let sum = 0;
    for (let num of nums) {
        let divCount = 0;
        let divSum = 0;

        for (let i = 1; i * i <= num; ++i) {
            if (num % i === 0) {
                divSum += i;
                ++divCount;

                if (num / i !== i) {
                    divSum += (num / i);
                    ++divCount;
                }
            }

            if (divCount > 4) {
                break;
            }
        }

        if (divCount === 4) {
            sum += divSum;
        }
    }

    return sum;
}
```
The algorithm starts by initializing a sum variable that will be used to store the sum of all divisors for the numbers with exactly four divisors. Then, we loop through each number in the input array. For each number, we initialize a div_count and div_sum variable to count the number of divisors and to store the sum of its divisors, respectively.

Inside the loop, we iterate from 1 to the square root of the current number (inclusive) using another loop. For each iteration, we check if the current number is divisible by the iterating variable 'i'. If it is, we add 'i' to the div_sum and increment the div_count. Next, we check if the result of the division (num / i) is different from 'i' and, if so, we add it to div_sum and increment div_count as well.

After checking all divisors, we exit the inner loop and check if div_count is equal to 4. If it is, we add div_sum to the total sum. The process continues until we reach the end of the input array.

Finally, we return the total sum.


# Iterator for Combination

- slug: iterator-for-combination
- difficulty: Medium

Design the `CombinationIterator` class:

*   `CombinationIterator(string characters, int combinationLength)` Initializes the object with a string `characters` of **sorted distinct** lowercase English letters and a number `combinationLength` as arguments.
*   `next()` Returns the next combination of length `combinationLength` in **lexicographical order**.
*   `hasNext()` Returns `true` if and only if there exists a next combination.

**Example 1:**

**Input**
\[ "CombinationIterator ",  "next ",  "hasNext ",  "next ",  "hasNext ",  "next ",  "hasNext "\]
\[\[ "abc ", 2\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null,  "ab ", true,  "ac ", true,  "bc ", false\]

**Explanation**
CombinationIterator itr = new CombinationIterator( "abc ", 2);
itr.next();    // return  "ab "
itr.hasNext(); // return True
itr.next();    // return  "ac "
itr.hasNext(); // return True
itr.next();    // return  "bc "
itr.hasNext(); // return False

**Constraints:**

*   `1 <= combinationLength <= characters.length <= 15`
*   All the characters of `characters` are **unique**.
*   At most `104` calls will be made to `next` and `hasNext`.
*   It is guaranteed that all calls of the function `next` are valid.

## A solution in Java

```java
public int maxSumSubsequence(int[] nums, int k) {
    int n = nums.length;
    int[] dp = new int[n];
    int result = 0;

    for (int i = 0; i < n; ++i) {
        dp[i] = nums[i];
        for (int j = Math.max(0, i - k); j < i; ++j) {
            dp[i] = Math.max(dp[i], dp[j] + nums[i]);
        }
        result = Math.max(result, dp[i]);
    }

    return result;
}
```
The algorithm creates a dynamic programming (DP) array `dp` with the same size as the input array `nums`. This DP array will store the maximum sum subsequence ending at each index. It initializes the maximum sum to 0, which needs to be updated during the dynamic programming process.

For each index `i` from 0 to n-1, it sets the value in the DP array as the value of `nums[i]`. Then, it checks all possible previous indices within the range of `k`, which indicates the maximum gap between the two consecutive elements in the subsequence. For each index `j`, it updates the DP value at the current index `i` as the maximum of the current DP value and the sum of the value of `nums[i]` and the previous value `dp[j]`.

Finally, it keeps track of the maximum sum found during this process in a variable `result`, and returns it after looping through the whole array.

## A solution in C++

```cpp
int maxSumSubsequence(vector<int>& nums, int k) {
    int n = nums.size();
    vector<int> dp(n, 0);
    int result = 0;

    for (int i = 0; i < n; ++i) {
        dp[i] = nums[i];
        for (int j = max(0, i - k); j < i; ++j) {
            dp[i] = max(dp[i], dp[j] + nums[i]);
        }
        result = max(result, dp[i]);
    }

    return result;
}
```
The algorithm creates a dynamic programming (DP) array `dp` with the same size as the input array `nums`. This DP array will store the maximum sum subsequence ending at each index. It initializes the maximum sum to 0, which needs to be updated during the dynamic programming process.

For each index `i` from 0 to n-1, it sets the value in the DP array as the value of `nums[i]`. Then, it checks all possible previous indices within the range of `k`, which indicates the maximum gap between the two consecutive elements in the subsequence. For each index `j`, it updates the DP value at the current index `i` as the maximum of the current DP value and the sum of the value of `nums[i]` and the previous value `dp[j]`.

Finally, it keeps track of the maximum sum found during this process in a variable `result`, and returns it after looping through the whole array.

## A solution in Python

```python
def max_sum_subsequence(nums: List[int], k: int) -> int:
    n = len(nums)
    dp = [0] * n
    result = 0

    for i in range(n):
        dp[i] = nums[i]
        for j in range(max(0, i - k), i):
            dp[i] = max(dp[i], dp[j] + nums[i])
        result = max(result, dp[i])

    return result
```
The algorithm creates a dynamic programming (DP) array `dp` with the same size as the input array `nums`. This DP array will store the maximum sum subsequence ending at each index. It initializes the maximum sum to 0, which needs to be updated during the dynamic programming process.

For each index `i` from 0 to n-1, it sets the value in the DP array as the value of `nums[i]`. Then, it checks all possible previous indices within the range of `k`, which indicates the maximum gap between the two consecutive elements in the subsequence. For each index `j`, it updates the DP value at the current index `i` as the maximum of the current DP value and the sum of the value of `nums[i]` and the previous value `dp[j]`.

Finally, it keeps track of the maximum sum found during this process in a variable `result`, and returns it after looping through the whole array.

## A solution in Javascript

```javascript
function maxSumSubsequence(nums, k) {
    const n = nums.length;
    const dp = new Array(n).fill(0);
    let result = 0;

    for (let i = 0; i < n; ++i) {
        dp[i] = nums[i];
        for (let j = Math.max(0, i - k); j < i; ++j) {
            dp[i] = Math.max(dp[i], dp[j] + nums[i]);
        }
        result = Math.max(result, dp[i]);
    }

    return result;
}
```
The algorithm creates a dynamic programming (DP) array `dp` with the same size as the input array `nums`. This DP array will store the maximum sum subsequence ending at each index. It initializes the maximum sum to 0, which needs to be updated during the dynamic programming process.

For each index `i` from 0 to n-1, it sets the value in the DP array as the value of `nums[i]`. Then, it checks all possible previous indices within the range of `k`, which indicates the maximum gap between the two consecutive elements in the subsequence. For each index `j`, it updates the DP value at the current index `i` as the maximum of the current DP value and the sum of the value of `nums[i]` and the previous value `dp[j]`.

Finally, it keeps track of the maximum sum found during this process in a variable `result`, and returns it after looping through the whole array.


# Element Appearing More Than 25% In Sorted Array

- slug: element-appearing-more-than-25-in-sorted-array
- difficulty: Easy

Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.

**Example 1:**

**Input:** arr = \[1,2,2,6,6,6,6,7,10\]
**Output:** 6

**Example 2:**

**Input:** arr = \[1,1\]
**Output:** 1

**Constraints:**

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

## A solution in Java

```java
public int shortestDistance(int[] distance, int start, int destination) {
    int total_distance = 0, clockwise_distance = 0;

    for(int i = 0; i < distance.length; ++i) {
        total_distance += distance[i];
        if(i >= start && i < destination) {
            clockwise_distance += distance[i];
        }
    }

    return Math.min(clockwise_distance, total_distance - clockwise_distance);
}
```
1. Initialize two variables `total_distance` and `clockwise_distance`.
2. Iterate through the input `distance` array and add the elements into the `total_distance`.
3. For elements between the `start` and the `destination`, add elements into the `clockwise_distance`.
4. After the iteration, we have the total distance of the circle and the distance from `start` to `destination` in the clockwise direction.
5. The counterclockwise distance is then `total_distance - clockwise_distance`.
6. Return the minimum of the clockwise and counterclockwise distances.

## A solution in C++

```cpp
int shortestDistance(vector<int>& distance, int start, int destination) {
    int total_distance = 0, clockwise_distance = 0;

    for (int i = 0; i < distance.size(); ++i) {
        total_distance += distance[i];
        if (i >= start && i < destination) {
            clockwise_distance += distance[i];
        }
    }

    return min(clockwise_distance, total_distance - clockwise_distance);
}
```
1. Initialize two variables `total_distance` and `clockwise_distance`.
2. Iterate through the input `distance` array and add the elements into the `total_distance`.
3. For elements between the `start` and the `destination`, add elements into the `clockwise_distance`.
4. After the iteration, we have the total distance of the circle and the distance from `start` to `destination` in the clockwise direction.
5. The counterclockwise distance is then `total_distance - clockwise_distance`.
6. Return the minimum of the clockwise and counterclockwise distances.

## A solution in Python

```python
def shortest_distance(distance, start, destination):
    total_distance = sum(distance)
    clockwise_distance = sum(distance[start:destination])

    return min(clockwise_distance, total_distance - clockwise_distance)
```
1. Initialize two variables `total_distance` and `clockwise_distance`.
2. Iterate through the input `distance` array and add the elements into the `total_distance`.
3. For elements between the `start` and the `destination`, add elements into the `clockwise_distance`.
4. After the iteration, we have the total distance of the circle and the distance from `start` to `destination` in the clockwise direction.
5. The counterclockwise distance is then `total_distance - clockwise_distance`.
6. Return the minimum of the clockwise and counterclockwise distances.

## A solution in Javascript

```javascript
function shortestDistance(distance, start, destination) {
    let total_distance = 0, clockwise_distance = 0;

    for (let i = 0; i < distance.length; ++i) {
        total_distance += distance[i];
        if (i >= start && i < destination) {
            clockwise_distance += distance[i];
        }
    }

    return Math.min(clockwise_distance, total_distance - clockwise_distance);
}
```
1. Initialize two variables `total_distance` and `clockwise_distance`.
2. Iterate through the input `distance` array and add the elements into the `total_distance`.
3. For elements between the `start` and the `destination`, add elements into the `clockwise_distance`.
4. After the iteration, we have the total distance of the circle and the distance from `start` to `destination` in the clockwise direction.
5. The counterclockwise distance is then `total_distance - clockwise_distance`.
6. Return the minimum of the clockwise and counterclockwise distances.