# Count Nodes Equal to Average of Subtree

- slug: count-nodes-equal-to-average-of-subtree
- difficulty: Medium

Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **average** of the values in its **subtree**_.

**Note:**

*   The **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
*   A **subtree** of `root` is a tree consisting of `root` and all of its descendants.

**Example 1:**

**Input:** root = \[4,8,5,0,1,null,6\]
**Output:** 5
**Explanation:**
For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.
For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.
For the node with value 0: The average of its subtree is 0 / 1 = 0.
For the node with value 1: The average of its subtree is 1 / 1 = 1.
For the node with value 6: The average of its subtree is 6 / 1 = 6.

**Example 2:**

**Input:** root = \[1\]
**Output:** 1
**Explanation:** For the node with value 1: The average of its subtree is 1 / 1 = 1.

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int[] rearrangeArrayAroundPivot(int[] nums, int pivot) {
    Arrays.sort(nums, (a, b) -> a < pivot && b >= pivot ? -1 : (a >= pivot && b < pivot ? 1 : 0));
    return nums;
}
```
For all language implementations, the algorithm is to sort the input array while comparing each pair of elements with the pivot. If one of the elements is less than the pivot and the other is greater or equal, the ordering is preserved or reversed according to this relation.

In C++, `std::partition` is used on the input vector, which rearranges elements within the range based on the predicate provided (checking if the element is less than pivot). In Java and JavaScript, a custom comparator is provided for the `Arrays.sort()` and `Array.prototype.sort()` functions, respectively. In Python, we use the `sorted()` function with a custom key function that returns a tuple, making use of lexicographic ordering based on two values: whether the element is greater than or equal to the pivot, and the element itself. This approach effectively places elements less than the pivot first and maintains their order relative to each other.

## A solution in C++

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

std::vector<int> rearrangeArrayAroundPivot(std::vector<int>& nums, int pivot) {
    std::partition(nums.begin(), nums.end(), [pivot](int num) { return num < pivot; });
    return nums;
}
```
For all language implementations, the algorithm is to sort the input array while comparing each pair of elements with the pivot. If one of the elements is less than the pivot and the other is greater or equal, the ordering is preserved or reversed according to this relation.

In C++, `std::partition` is used on the input vector, which rearranges elements within the range based on the predicate provided (checking if the element is less than pivot). In Java and JavaScript, a custom comparator is provided for the `Arrays.sort()` and `Array.prototype.sort()` functions, respectively. In Python, we use the `sorted()` function with a custom key function that returns a tuple, making use of lexicographic ordering based on two values: whether the element is greater than or equal to the pivot, and the element itself. This approach effectively places elements less than the pivot first and maintains their order relative to each other.

## A solution in Python

```python
def rearrange_array_around_pivot(nums, pivot):
    return sorted(nums, key=lambda x: (x >= pivot, x))
```
For all language implementations, the algorithm is to sort the input array while comparing each pair of elements with the pivot. If one of the elements is less than the pivot and the other is greater or equal, the ordering is preserved or reversed according to this relation.

In C++, `std::partition` is used on the input vector, which rearranges elements within the range based on the predicate provided (checking if the element is less than pivot). In Java and JavaScript, a custom comparator is provided for the `Arrays.sort()` and `Array.prototype.sort()` functions, respectively. In Python, we use the `sorted()` function with a custom key function that returns a tuple, making use of lexicographic ordering based on two values: whether the element is greater than or equal to the pivot, and the element itself. This approach effectively places elements less than the pivot first and maintains their order relative to each other.

## A solution in Javascript

```javascript
function rearrangeArrayAroundPivot(nums, pivot) {
    return nums.sort((a, b) => (a < pivot && b >= pivot) ? -1 : (a >= pivot && b < pivot) ? 1 : 0);
}
```
For all language implementations, the algorithm is to sort the input array while comparing each pair of elements with the pivot. If one of the elements is less than the pivot and the other is greater or equal, the ordering is preserved or reversed according to this relation.

In C++, `std::partition` is used on the input vector, which rearranges elements within the range based on the predicate provided (checking if the element is less than pivot). In Java and JavaScript, a custom comparator is provided for the `Arrays.sort()` and `Array.prototype.sort()` functions, respectively. In Python, we use the `sorted()` function with a custom key function that returns a tuple, making use of lexicographic ordering based on two values: whether the element is greater than or equal to the pivot, and the element itself. This approach effectively places elements less than the pivot first and maintains their order relative to each other.


# Count Number of Texts

- slug: count-number-of-texts
- difficulty: Medium

Alice is texting Bob using her phone. The **mapping** of digits to letters is shown in the figure below.

In order to **add** a letter, Alice has to **press** the key of the corresponding digit `i` times, where `i` is the position of the letter in the key.

*   For example, to add the letter `'s'`, Alice has to press `'7'` four times. Similarly, to add the letter `'k'`, Alice has to press `'5'` twice.
*   Note that the digits `'0'` and `'1'` do not map to any letters, so Alice **does not** use them.

However, due to an error in transmission, Bob did not receive Alice's text message but received a **string of pressed keys** instead.

*   For example, when Alice sent the message `"bob "`, Bob received the string `"2266622 "`.

Given a string `pressedKeys` representing the string received by Bob, return _the **total number of possible text messages** Alice could have sent_.

Since the answer may be very large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** pressedKeys =  "22233 "
**Output:** 8
**Explanation:**
The possible text messages Alice could have sent are:
 "aaadd ",  "abdd ",  "badd ",  "cdd ",  "aaae ",  "abe ",  "bae ", and  "ce ".
Since there are 8 possible messages, we return 8.

**Example 2:**

**Input:** pressedKeys =  "222222222222222222222222222222222222 "
**Output:** 82876089
**Explanation:**
There are 2082876103 possible text messages Alice could have sent.
Since we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089.

**Constraints:**

*   `1 <= pressedKeys.length <= 105`
*   `pressedKeys` only consists of digits from `'2'` - `'9'`.

## A solution in Java

```java
public int minCost(int startAt, int moveCost, int pushCost, int targetSeconds) {
    int min_cost = Integer.MAX_VALUE;

    for (int i = 0; i <= 99; i++) {
        for (int j = 0; j <= 99; j++) {
            if (i * 60 + j == targetSeconds) {
                int minute_move_cost = Math.abs(i - startAt) * moveCost;
                int second_move_cost = Math.abs(j - i) * moveCost;
                int total_push_cost = (j > 0 ? 2 : 0) + (j / 10 != 0 ? 1 : 0) + (i / 10 != 0 ? 1 : 0);

                min_cost = Math.min(min_cost, minute_move_cost + second_move_cost + total_push_cost * pushCost);
            }
        }
    }
    return min_cost;
}
```
1. Initialize `min_cost` to a large value.
2. Iterate over all possible combinations of minute digits (i) and second digits (j) in the range of [0, 99].
3. Check if the current combination (`i * 60 + j`) matches the target seconds. If it does:
   a. Calculate and store the move cost for minute and second digits.
   b. Calculate and store the push cost for the current combination.
   c. Update `min_cost` with the minimum value between the current `min_cost` and the sum of move cost and push cost.
4. After iterating through all possible combinations, return the `min_cost`.

## A solution in C++

```cpp
int minCost(int startAt, int moveCost, int pushCost, int targetSeconds) {
    int min_cost = INT_MAX;

    for (int i = 0; i <= 99; i++) {
        for (int j = 0; j <= 99; j++) {
            if (i * 60 + j == targetSeconds) {
                int minute_move_cost = abs(i - startAt) * moveCost;
                int second_move_cost = abs(j - i) * moveCost;
                int total_push_cost = (j > 0 ? 2 : 0) + (j / 10 != 0 ? 1 : 0) + (i / 10 != 0 ? 1 : 0);

                min_cost = min(min_cost, minute_move_cost + second_move_cost + total_push_cost * pushCost);
            }
        }
    }
    return min_cost;
}
```
1. Initialize `min_cost` to a large value.
2. Iterate over all possible combinations of minute digits (i) and second digits (j) in the range of [0, 99].
3. Check if the current combination (`i * 60 + j`) matches the target seconds. If it does:
   a. Calculate and store the move cost for minute and second digits.
   b. Calculate and store the push cost for the current combination.
   c. Update `min_cost` with the minimum value between the current `min_cost` and the sum of move cost and push cost.
4. After iterating through all possible combinations, return the `min_cost`.

## A solution in Python

```python
def min_cost(startAt, moveCost, pushCost, targetSeconds):
    min_cost = float('inf')

    for i in range(100):
        for j in range(100):
            if i * 60 + j == targetSeconds:
                minute_move_cost = abs(i - startAt) * moveCost
                second_move_cost = abs(j - i) * moveCost
                total_push_cost = (2 if j > 0 else 0) + (1 if j // 10 != 0 else 0) + (1 if i // 10 != 0 else 0)

                min_cost = min(min_cost, minute_move_cost + second_move_cost + total_push_cost * pushCost)

    return min_cost
```
1. Initialize `min_cost` to a large value.
2. Iterate over all possible combinations of minute digits (i) and second digits (j) in the range of [0, 99].
3. Check if the current combination (`i * 60 + j`) matches the target seconds. If it does:
   a. Calculate and store the move cost for minute and second digits.
   b. Calculate and store the push cost for the current combination.
   c. Update `min_cost` with the minimum value between the current `min_cost` and the sum of move cost and push cost.
4. After iterating through all possible combinations, return the `min_cost`.

## A solution in Javascript

```javascript
function minCost(startAt, moveCost, pushCost, targetSeconds) {
    let min_cost = Infinity;

    for (let i = 0; i <= 99; i++) {
        for (let j = 0; j <= 99; j++) {
            if (i * 60 + j === targetSeconds) {
                let minute_move_cost = Math.abs(i - startAt) * moveCost;
                let second_move_cost = Math.abs(j - i) * moveCost;
                let total_push_cost = (j > 0 ? 2 : 0) + (j / 10 !== 0 ? 1 : 0) + (i / 10 !== 0 ? 1 : 0);

                min_cost = Math.min(min_cost, minute_move_cost + second_move_cost + total_push_cost * pushCost);
            }
        }
    }
    return min_cost;
}
```
1. Initialize `min_cost` to a large value.
2. Iterate over all possible combinations of minute digits (i) and second digits (j) in the range of [0, 99].
3. Check if the current combination (`i * 60 + j`) matches the target seconds. If it does:
   a. Calculate and store the move cost for minute and second digits.
   b. Calculate and store the push cost for the current combination.
   c. Update `min_cost` with the minimum value between the current `min_cost` and the sum of move cost and push cost.
4. After iterating through all possible combinations, return the `min_cost`.


#  Check if There Is a Valid Parentheses String Path

- slug: check-if-there-is-a-valid-parentheses-string-path
- difficulty: Hard

A parentheses string is a **non-empty** string consisting only of `'('` and `')'`. It is **valid** if **any** of the following conditions is **true**:

*   It is `()`.
*   It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid parentheses strings.
*   It can be written as `(A)`, where `A` is a valid parentheses string.

You are given an `m x n` matrix of parentheses `grid`. A **valid parentheses string path** in the grid is a path satisfying **all** of the following conditions:

*   The path starts from the upper left cell `(0, 0)`.
*   The path ends at the bottom-right cell `(m - 1, n - 1)`.
*   The path only ever moves **down** or **right**.
*   The resulting parentheses string formed by the path is **valid**.

Return `true` _if there exists a **valid parentheses string path** in the grid._ Otherwise, return `false`.

**Example 1:**

**Input:** grid = \[\[ "( ", "( ", "( "\],\[ ") ", "( ", ") "\],\[ "( ", "( ", ") "\],\[ "( ", "( ", ") "\]\]
**Output:** true
**Explanation:** The above diagram shows two possible paths that form valid parentheses strings.
The first path shown results in the valid parentheses string  "()(()) ".
The second path shown results in the valid parentheses string  "((())) ".
Note that there may be other valid parentheses string paths.

**Example 2:**

**Input:** grid = \[\[ ") ", ") "\],\[ "( ", "( "\]\]
**Output:** false
**Explanation:** The two possible paths form the parentheses strings  "))( " and  ")(( ". Since neither of them are valid parentheses strings, we return false.

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 100`
*   `grid[i][j]` is either `'('` or `')'`.

## A solution in Java

```java
public int minDifference(int[] nums) {
    int n = nums.length / 3;
    int[] prefix = new int[n + 2];
    int[] suffix = new int[n + 2];
    TreeSet<Integer> window = new TreeSet<>();

    for (int i = 0; i < n; ++i) window.add(nums[i]);
    prefix[0] = window.stream().mapToInt(Integer::intValue).sum();

    for (int i = n, j = 1; i < 2 * n; ++i, ++j) {
        window.remove(nums[i - n]);
        window.add(nums[i]);
        prefix[j] = window.stream().mapToInt(Integer::intValue).sum();
    }

    window.clear();

    for (int i = 0; i < n; ++i) window.add(nums[3 * n - i - 1]);
    suffix[n] = window.stream().mapToInt(Integer::intValue).sum();

    for (int i = n - 1, j = 1; i < 2 * n - 1; --i, ++j) {
        window.remove(nums[3 * n - j]);
        window.add(nums[2 * n - j]);
        suffix[i] = window.stream().mapToInt(Integer::intValue).sum();
    }

    int min_diff = Integer.MAX_VALUE;

    for (int i = 0; i <= n; ++i) {
        min_diff = Math.min(min_diff, Math.abs(prefix[i] - suffix[i]));
    }

    return min_diff;
}
```
The algorithm works as follows:
1. Initialize a prefix and suffix array of length n+2 where prefix array will store the sum of elements in the current sliding window until 2n and suffix array will store the sum of elements in the current sliding window from 3n to 2n.
2. Use a set or multiset to store elements of the sliding window which will be of size n.
3. First calculate the prefix sums by looping from n to 2n and calculate the suffix sums by looping from 3n to 2n.
4. While calculating the prefix and suffix sums, maintain a sliding window by removing the unwanted element and inserting the new element.
5. At the end, iterate through the prefix and suffix arrays and find the minimum difference between the sums of two parts in the arrays. Return the minimum difference.

## A solution in C++

```cpp
int minDifference(vector<int>& nums) {
   int n = nums.size() / 3;
   vector<int> prefix(n + 2), suffix(n + 2);
   multiset<int> window;

   for (int i = 0; i < n; ++i) window.insert(nums[i]);
   prefix[0] = accumulate(begin(window), end(window), 0);

   for (int i = n, j = 1; i < 2 * n; ++i, ++j) {
      window.erase(window.find(nums[i - n]));
      window.insert(nums[i]);
      prefix[j] = accumulate(begin(window), end(window), 0);
   }

   window.clear();

   for (int i = 0; i < n; ++i) window.insert(nums[3 * n - i - 1]);
   suffix[n] = accumulate(begin(window), end(window), 0);

   for (int i = n - 1, j = 1; i < 2 * n - 1; --i, ++j) {
      window.erase(window.find(nums[3 * n - j]));
      window.insert(nums[2 * n - j]);
      suffix[i] = accumulate(begin(window), end(window), 0);
   }

   int min_diff = INT_MAX;

   for (int i = 0; i <= n; ++i) {
      min_diff = min(min_diff, abs(prefix[i] - suffix[i]));
   }

   return min_diff;
}
```
The algorithm works as follows:
1. Initialize a prefix and suffix array of length n+2 where prefix array will store the sum of elements in the current sliding window until 2n and suffix array will store the sum of elements in the current sliding window from 3n to 2n.
2. Use a set or multiset to store elements of the sliding window which will be of size n.
3. First calculate the prefix sums by looping from n to 2n and calculate the suffix sums by looping from 3n to 2n.
4. While calculating the prefix and suffix sums, maintain a sliding window by removing the unwanted element and inserting the new element.
5. At the end, iterate through the prefix and suffix arrays and find the minimum difference between the sums of two parts in the arrays. Return the minimum difference.

## A solution in Python

```python
def minDifference(nums):
    n = len(nums) // 3
    prefix, suffix = [0] * (n + 2), [0] * (n + 2)

    window = sorted(nums[:n])
    prefix[0] = sum(window)

    for i in range(n, 2 * n):
        window.remove(nums[i - n])
        bisect.insort(window, nums[i])
        prefix[i - n + 1] = sum(window)

    window = sorted(nums[-n:])
    suffix[n] = sum(window)

    for i in range(2 * n - 1, n - 1, -1):
        j = 3 * n - i - 1
        window.remove(nums[j])
        idx = bisect_left(window, nums[n * 2 - j - 1])
        window.insert(idx, nums[n * 2 - j - 1])
        suffix[i] = sum(window)

    return min(abs(a - b) for a, b in zip(prefix, suffix))
```
The algorithm works as follows:
1. Initialize a prefix and suffix array of length n+2 where prefix array will store the sum of elements in the current sliding window until 2n and suffix array will store the sum of elements in the current sliding window from 3n to 2n.
2. Use a set or multiset to store elements of the sliding window which will be of size n.
3. First calculate the prefix sums by looping from n to 2n and calculate the suffix sums by looping from 3n to 2n.
4. While calculating the prefix and suffix sums, maintain a sliding window by removing the unwanted element and inserting the new element.
5. At the end, iterate through the prefix and suffix arrays and find the minimum difference between the sums of two parts in the arrays. Return the minimum difference.

## A solution in Javascript

```javascript
function minDifference(nums) {
    const n = nums.length / 3;
    const prefix = new Array(n + 2).fill(0);
    const suffix = new Array(n + 2).fill(0);
    const window = new Set();

    for (let i = 0; i < n; ++i) window.add(nums[i]);
    prefix[0] = Array.from(window).reduce((a, b) => a + b, 0);

    for (let i = n, j = 1; i < 2 * n; ++i, ++j) {
        window.delete(nums[i - n]);
        window.add(nums[i]);
        prefix[j] = Array.from(window).reduce((a, b) => a + b, 0);
    }

    window.clear();

    for (let i = 0; i < n; ++i) window.add(nums[3 * n - i - 1]);
    suffix[n] = Array.from(window).reduce((a, b) => a + b, 0);

    for (let i = n - 1, j = 1; i < 2 * n - 1; --i, ++j) {
        window.delete(nums[3 * n - j]);
        window.add(nums[2 * n - j]);
        suffix[i] = Array.from(window).reduce((a, b) => a + b, 0);
    }

    let min_diff = Number.MAX_VALUE;

    for (let i = 0; i <= n; ++i) {
        min_diff = Math.min(min_diff, Math.abs(prefix[i] - suffix[i]));
    }

    return min_diff;
}
```
The algorithm works as follows:
1. Initialize a prefix and suffix array of length n+2 where prefix array will store the sum of elements in the current sliding window until 2n and suffix array will store the sum of elements in the current sliding window from 3n to 2n.
2. Use a set or multiset to store elements of the sliding window which will be of size n.
3. First calculate the prefix sums by looping from n to 2n and calculate the suffix sums by looping from 3n to 2n.
4. While calculating the prefix and suffix sums, maintain a sliding window by removing the unwanted element and inserting the new element.
5. At the end, iterate through the prefix and suffix arrays and find the minimum difference between the sums of two parts in the arrays. Return the minimum difference.


# Minimum Number of Keypresses

- slug: minimum-number-of-keypresses
- difficulty: Medium

You have a keypad with `9` buttons, numbered from `1` to `9`, each mapped to lowercase English letters. You can choose which characters each button is matched to as long as:

*   All 26 lowercase English letters are mapped to.
*   Each character is mapped to by **exactly** `1` button.
*   Each button maps to **at most** `3` characters.

To type the first character matched to a button, you press the button once. To type the second character, you press the button twice, and so on.

Given a string `s`, return _the **minimum** number of keypresses needed to type_ `s` _using your keypad._

**Note** that the characters mapped to by each button, and the order they are mapped in cannot be changed.

**Example 1:**

**Input:** s =  "apple "
**Output:** 5
**Explanation:** One optimal way to setup your keypad is shown above.
Type 'a' by pressing button 1 once.
Type 'p' by pressing button 6 once.
Type 'p' by pressing button 6 once.
Type 'l' by pressing button 5 once.
Type 'e' by pressing button 3 once.
A total of 5 button presses are needed, so return 5.

**Example 2:**

**Input:** s =  "abcdefghijkl "
**Output:** 15
**Explanation:** One optimal way to setup your keypad is shown above.
The letters 'a' to 'i' can each be typed by pressing a button once.
Type 'j' by pressing button 1 twice.
Type 'k' by pressing button 2 twice.
Type 'l' by pressing button 3 twice.
A total of 15 button presses are needed, so return 15.

**Constraints:**

*   `1 <= s.length <= 105`
*   `s` consists of lowercase English letters.

## A solution in Java

```java
public int minKeypresses(String s) {
    int[] keypresses = new int[26];
    for (int i = 0; i < 26; ++i) {
        keypresses[i] = (i % 9) + 1;
    }
    int result = 0;
    for (char c : s.toCharArray()) {
        result += keypresses[c - 'a'];
    }
    return result;
}
```
We first create an array `keypresses` of length 26 to represent all lowercase English letters, where each element maps the number of keypresses needed to type the corresponding character. Then, we iterate through the input string `s` and for each character `c`, we increment the `result` counter with the number of keypresses needed to type the `c`. In the end, we return the result counter.

## A solution in C++

```cpp
#include <vector>

int min_keypresses(const std::string& s) {
    std::vector<int> keypresses(26);
    for (int i = 0; i < 26; ++i) {
        keypresses[i] = (i % 9) + 1;
    }
    int result = 0;
    for (char c : s) {
        result += keypresses[c - 'a'];
    }
    return result;
}
```
We first create an array `keypresses` of length 26 to represent all lowercase English letters, where each element maps the number of keypresses needed to type the corresponding character. Then, we iterate through the input string `s` and for each character `c`, we increment the `result` counter with the number of keypresses needed to type the `c`. In the end, we return the result counter.

## A solution in Python

```python
def min_keypresses(s: str) -> int:
    keypresses = [(i % 9) + 1 for i in range(26)]
    result = 0
    for c in s:
        result += keypresses[ord(c) - ord('a')]
    return result
```
We first create an array `keypresses` of length 26 to represent all lowercase English letters, where each element maps the number of keypresses needed to type the corresponding character. Then, we iterate through the input string `s` and for each character `c`, we increment the `result` counter with the number of keypresses needed to type the `c`. In the end, we return the result counter.

## A solution in Javascript

```javascript
function minKeypresses(s) {
    const keypresses = Array.from({length: 26}, (_, i) => (i % 9) + 1);
    let result = 0;
    for (const c of s) {
        result += keypresses[c.charCodeAt(0) - 'a'.charCodeAt(0)];
    }
    return result;
}
```
We first create an array `keypresses` of length 26 to represent all lowercase English letters, where each element maps the number of keypresses needed to type the corresponding character. Then, we iterate through the input string `s` and for each character `c`, we increment the `result` counter with the number of keypresses needed to type the `c`. In the end, we return the result counter.


# Find the K-Beauty of a Number

- slug: find-the-k-beauty-of-a-number
- difficulty: Easy

The **k-beauty** of an integer `num` is defined as the number of **substrings** of `num` when it is read as a string that meet the following conditions:

*   It has a length of `k`.
*   It is a divisor of `num`.

Given integers `num` and `k`, return _the k-beauty of_ `num`.

Note:

*   **Leading zeros** are allowed.
*   `0` is not a divisor of any value.

A **substring** is a contiguous sequence of characters in a string.

**Example 1:**

**Input:** num = 240, k = 2
**Output:** 2
**Explanation:** The following are the substrings of num of length k:
-  "24 " from  "**24**0 ": 24 is a divisor of 240.
-  "40 " from  "2**40** ": 40 is a divisor of 240.
Therefore, the k-beauty is 2.

**Example 2:**

**Input:** num = 430043, k = 2
**Output:** 2
**Explanation:** The following are the substrings of num of length k:
-  "43 " from  "**43**0043 ": 43 is a divisor of 430043.
-  "30 " from  "4**30**043 ": 30 is not a divisor of 430043.
-  "00 " from  "43**00**43 ": 0 is not a divisor of 430043.
-  "04 " from  "430**04**3 ": 4 is not a divisor of 430043.
-  "43 " from  "4300**43** ": 43 is a divisor of 430043.
Therefore, the k-beauty is 2.

**Constraints:**

*   `1 <= num <= 109`
*   `1 <= k <= num.length` (taking `num` as a string)

## A solution in Java

```java
public int numElementsWithSmallerAndGreater(int[] nums) {
    int n = nums.length;
    int res = 0;
    for (int i = 0; i < n; i++) {
        boolean hasSmaller = false, hasGreater = false;
        for (int j = 0; j < n; j++) {
            if (i == j) continue;
            if (nums[j] > nums[i]) hasGreater = true;
            if (nums[j] < nums[i]) hasSmaller = true;
            if (hasSmaller && hasGreater) {
                res++;
                break;
            }
        }
    }
    return res;
}
```
The algorithm iterates through the input array `nums`. For each element, it checks if there are both smaller and greater elements in the array. To do this, it uses two boolean variables (`hasSmaller` and `hasGreater`). The inner loop iterates through the array again to compare each pair of distinct elements.

If a pair of elements that satisfies the condition (one is smaller and the other is greater) is found, the result is incremented by 1, and the inner loop is broken to avoid redundant checks for the current element.

After iterating through the entire array, the final result is returned.

## A solution in C++

```cpp
int numElementsWithSmallerAndGreater(const std::vector<int>& nums) {
    int n = nums.size();
    int res = 0;
    for (int i = 0; i < n; i++) {
        bool hasSmaller = false, hasGreater = false;
        for (int j = 0; j < n; j++) {
            if (i == j) continue;
            if (nums[j] > nums[i]) hasGreater = true;
            if (nums[j] < nums[i]) hasSmaller = true;
            if (hasSmaller && hasGreater) {
                res++;
                break;
            }
        }
    }
    return res;
}
```
The algorithm iterates through the input array `nums`. For each element, it checks if there are both smaller and greater elements in the array. To do this, it uses two boolean variables (`hasSmaller` and `hasGreater`). The inner loop iterates through the array again to compare each pair of distinct elements.

If a pair of elements that satisfies the condition (one is smaller and the other is greater) is found, the result is incremented by 1, and the inner loop is broken to avoid redundant checks for the current element.

After iterating through the entire array, the final result is returned.

## A solution in Python

```python
def num_elements_with_smaller_and_greater(nums):
    n = len(nums)
    res = 0
    for i in range(n):
        has_smaller = has_greater = False
        for j in range(n):
            if i == j:
                continue
            if nums[j] > nums[i]:
                has_greater = True
            if nums[j] < nums[i]:
                has_smaller = True
            if has_smaller and has_greater:
                res += 1
                break
    return res
```
The algorithm iterates through the input array `nums`. For each element, it checks if there are both smaller and greater elements in the array. To do this, it uses two boolean variables (`hasSmaller` and `hasGreater`). The inner loop iterates through the array again to compare each pair of distinct elements.

If a pair of elements that satisfies the condition (one is smaller and the other is greater) is found, the result is incremented by 1, and the inner loop is broken to avoid redundant checks for the current element.

After iterating through the entire array, the final result is returned.

## A solution in Javascript

```javascript
function numElementsWithSmallerAndGreater(nums) {
    let n = nums.length;
    let res = 0;
    for (let i = 0; i < n; i++) {
        let hasSmaller = false, hasGreater = false;
        for (let j = 0; j < n; j++) {
            if (i === j) continue;
            if (nums[j] > nums[i]) hasGreater = true;
            if (nums[j] < nums[i]) hasSmaller = true;
            if (hasSmaller && hasGreater) {
                res++;
                break;
            }
        }
    }
    return res;
}
```
The algorithm iterates through the input array `nums`. For each element, it checks if there are both smaller and greater elements in the array. To do this, it uses two boolean variables (`hasSmaller` and `hasGreater`). The inner loop iterates through the array again to compare each pair of distinct elements.

If a pair of elements that satisfies the condition (one is smaller and the other is greater) is found, the result is incremented by 1, and the inner loop is broken to avoid redundant checks for the current element.

After iterating through the entire array, the final result is returned.


# Number of Ways to Split Array

- slug: number-of-ways-to-split-array
- difficulty: Medium

You are given a **0-indexed** integer array `nums` of length `n`.

`nums` contains a **valid split** at index `i` if the following are true:

*   The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
*   There is **at least one** element to the right of `i`. That is, `0 <= i < n - 1`.

Return _the number of **valid splits** in_ `nums`.

**Example 1:**

**Input:** nums = \[10,4,-8,7\]
**Output:** 2
**Explanation:**
There are three ways of splitting nums into two non-empty parts:
- Split nums at index 0. Then, the first part is \[10\], and its sum is 10. The second part is \[4,-8,7\], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.
- Split nums at index 1. Then, the first part is \[10,4\], and its sum is 14. The second part is \[-8,7\], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.
- Split nums at index 2. Then, the first part is \[10,4,-8\], and its sum is 6. The second part is \[7\], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.
Thus, the number of valid splits in nums is 2.

**Example 2:**

**Input:** nums = \[2,3,1,0\]
**Output:** 2
**Explanation:**
There are two valid splits in nums:
- Split nums at index 1. Then, the first part is \[2,3\], and its sum is 5. The second part is \[1,0\], and its sum is 1. Since 5 >= 1, i = 1 is a valid split.
- Split nums at index 2. Then, the first part is \[2,3,1\], and its sum is 6. The second part is \[0\], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.

**Constraints:**

*   `2 <= nums.length <= 105`
*   `-105 <= nums[i] <= 105`

## A solution in Java

```java
import java.util.HashSet;
import java.util.ArrayList;

public ArrayList<Integer> lonelyNumbers(int[] nums) {
    HashSet<Integer> num_set = new HashSet<>();
    for (int num : nums) {
        num_set.add(num);
    }
    ArrayList<Integer> lonely = new ArrayList<>();
    for (int num : nums) {
        if (!num_set.contains(num - 1) && !num_set.contains(num + 1)) {
            lonely.add(num);
        }
    }
    return lonely;
}
```
1. Create a set `num_set` containing all the unique numbers in the given array `nums`.
2. Create an empty list or vector `lonely` to store the lonely numbers.
3. Iterate through the numbers in `nums`.
4. For each number `num`, check if `num - 1` and `num + 1` do not exist in the set `num_set`.
5. If both conditions are satisfied, the number is lonely, and we append it to our `lonely` list or vector.
6. Return the `lonely` list or vector containing all the lonely numbers.

## A solution in C++

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

vector<int> lonelyNumbers(vector<int>& nums) {
    unordered_set<int> num_set(nums.begin(), nums.end());
    vector<int> lonely;
    for (int num : nums) {
        if (!num_set.count(num - 1) && !num_set.count(num + 1)) {
            lonely.push_back(num);
        }
    }
    return lonely;
}
```
1. Create a set `num_set` containing all the unique numbers in the given array `nums`.
2. Create an empty list or vector `lonely` to store the lonely numbers.
3. Iterate through the numbers in `nums`.
4. For each number `num`, check if `num - 1` and `num + 1` do not exist in the set `num_set`.
5. If both conditions are satisfied, the number is lonely, and we append it to our `lonely` list or vector.
6. Return the `lonely` list or vector containing all the lonely numbers.

## A solution in Python

```python
def lonely_numbers(nums):
    num_set = set(nums)
    lonely = []
    for num in nums:
        if num - 1 not in num_set and num + 1 not in num_set:
            lonely.append(num)
    return lonely
```
1. Create a set `num_set` containing all the unique numbers in the given array `nums`.
2. Create an empty list or vector `lonely` to store the lonely numbers.
3. Iterate through the numbers in `nums`.
4. For each number `num`, check if `num - 1` and `num + 1` do not exist in the set `num_set`.
5. If both conditions are satisfied, the number is lonely, and we append it to our `lonely` list or vector.
6. Return the `lonely` list or vector containing all the lonely numbers.

## A solution in Javascript

```javascript
function lonelyNumbers(nums) {
    let numSet = new Set(nums);
    let lonely = [];
    for (let num of nums) {
        if (!numSet.has(num - 1) && !numSet.has(num + 1)) {
            lonely.push(num);
        }
    }
    return lonely;
}
```
1. Create a set `num_set` containing all the unique numbers in the given array `nums`.
2. Create an empty list or vector `lonely` to store the lonely numbers.
3. Iterate through the numbers in `nums`.
4. For each number `num`, check if `num - 1` and `num + 1` do not exist in the set `num_set`.
5. If both conditions are satisfied, the number is lonely, and we append it to our `lonely` list or vector.
6. Return the `lonely` list or vector containing all the lonely numbers.


# Maximum White Tiles Covered by a Carpet

- slug: maximum-white-tiles-covered-by-a-carpet
- difficulty: Medium

You are given a 2D integer array `tiles` where `tiles[i] = [li, ri]` represents that every tile `j` in the range `li <= j <= ri` is colored white.

You are also given an integer `carpetLen`, the length of a single carpet that can be placed **anywhere**.

Return _the **maximum** number of white tiles that can be covered by the carpet_.

**Example 1:**

**Input:** tiles = \[\[1,5\],\[10,11\],\[12,18\],\[20,25\],\[30,32\]\], carpetLen = 10
**Output:** 9
**Explanation:** Place the carpet starting on tile 10.
It covers 9 white tiles, so we return 9.
Note that there may be other places where the carpet covers 9 white tiles.
It can be shown that the carpet cannot cover more than 9 white tiles.

**Example 2:**

**Input:** tiles = \[\[10,11\],\[1,1\]\], carpetLen = 2
**Output:** 2
**Explanation:** Place the carpet starting on tile 10.
It covers 2 white tiles, so we return 2.

**Constraints:**

*   `1 <= tiles.length <= 5 * 104`
*   `tiles[i].length == 2`
*   `1 <= li <= ri <= 109`
*   `1 <= carpetLen <= 109`
*   The `tiles` are **non-overlapping**.

## A solution in Java

```java
import java.util.Arrays;

public int[] rearrangeArray(int[] nums) {
    Arrays.sort(nums);
    int[] result = new int[nums.length];
    int half = nums.length / 2;
    int j = 0;
    for (int i = 0; i < half; i++) {
        result[j] = nums[i];
        result[j + 1] = nums[half + i];
        j += 2;
    }
    return result;
}
```
The algorithm consists of the following steps:
1. Sort the input array in ascending order.
2. Initialize a new array of the same length as the input array, called 'result'.
3. Calculate half of the length of the array.
4. Iterate through the first half of the input array, placing one positive element and one negative element in the 'result' array alternatively.
5. Return the 'result' array.

The time complexity of this algorithm is O(nlogn), where n is the length of the input array, and it comes from the sorting step. The space complexity is O(n) due to the creation of the 'result' array.

## A solution in C++

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

std::vector<int> rearrangeArray(std::vector<int>& nums) {
    std::vector<int> result(nums.size());
    std::sort(nums.begin(), nums.end());
    int half = nums.size() / 2;
    int j = 0;
    for (int i = 0; i < half; i++) {
        result[j] = nums[i];
        result[j + 1] = nums[half + i];
        j += 2;
    }
    return result;
}
```
The algorithm consists of the following steps:
1. Sort the input array in ascending order.
2. Initialize a new array of the same length as the input array, called 'result'.
3. Calculate half of the length of the array.
4. Iterate through the first half of the input array, placing one positive element and one negative element in the 'result' array alternatively.
5. Return the 'result' array.

The time complexity of this algorithm is O(nlogn), where n is the length of the input array, and it comes from the sorting step. The space complexity is O(n) due to the creation of the 'result' array.

## A solution in Python

```python
def rearrange_array(nums):
    nums.sort()
    half = len(nums) // 2
    result = [0] * len(nums)
    j = 0
    for i in range(half):
        result[j] = nums[i]
        result[j + 1] = nums[half + i]
        j += 2
    return result
```
The algorithm consists of the following steps:
1. Sort the input array in ascending order.
2. Initialize a new array of the same length as the input array, called 'result'.
3. Calculate half of the length of the array.
4. Iterate through the first half of the input array, placing one positive element and one negative element in the 'result' array alternatively.
5. Return the 'result' array.

The time complexity of this algorithm is O(nlogn), where n is the length of the input array, and it comes from the sorting step. The space complexity is O(n) due to the creation of the 'result' array.

## A solution in Javascript

```javascript
function rearrangeArray(nums) {
    nums.sort((a, b) => a - b);
    const result = new Array(nums.length);
    const half = nums.length / 2;
    let j = 0;
    for (let i = 0; i < half; i++) {
        result[j] = nums[i];
        result[j + 1] = nums[half + i];
        j += 2;
    }
    return result;
}
```
The algorithm consists of the following steps:
1. Sort the input array in ascending order.
2. Initialize a new array of the same length as the input array, called 'result'.
3. Calculate half of the length of the array.
4. Iterate through the first half of the input array, placing one positive element and one negative element in the 'result' array alternatively.
5. Return the 'result' array.

The time complexity of this algorithm is O(nlogn), where n is the length of the input array, and it comes from the sorting step. The space complexity is O(n) due to the creation of the 'result' array.


# Substring With Largest Variance

- slug: substring-with-largest-variance
- difficulty: Hard

The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same.

Given a string `s` consisting of lowercase English letters only, return _the **largest variance** possible among all **substrings** of_ `s`.

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

**Example 1:**

**Input:** s =  "aababbb "
**Output:** 3
**Explanation:**
All possible variances along with their respective substrings are listed below:
- Variance 0 for substrings  "a ",  "aa ",  "ab ",  "abab ",  "aababb ",  "ba ",  "b ",  "bb ", and  "bbb ".
- Variance 1 for substrings  "aab ",  "aba ",  "abb ",  "aabab ",  "ababb ",  "aababbb ", and  "bab ".
- Variance 2 for substrings  "aaba ",  "ababbb ",  "abbb ", and  "babb ".
- Variance 3 for substring  "babbb ".
Since the largest possible variance is 3, we return it.

**Example 2:**

**Input:** s =  "abcde "
**Output:** 0
**Explanation:**
No letter occurs more than once in s, so the variance of every substring is 0.

**Constraints:**

*   `1 <= s.length <= 104`
*   `s` consists of lowercase English letters.

## A solution in Java

```java
public int maximumGoodPeople(int[][] statements) {
    int n = statements.length;
    int count_good = 0;
    for(int i = 0; i < n; i++) {
        boolean is_good = true;
        for(int j = 0; j < n; j++) {
            if(statements[j][i] == 1 && statements[i][j] == 0) {
                is_good = false;
                break;
            }
        }
        if(is_good) count_good++;
    }
    return count_good;
}
```
We iterate through each person, then we iterate through each statement made by other people about that person. If there are no contradicting statements (someone claims the person is good but the person claims that someone is not good), we consider the person to be good and increment the count. Finally, we return the total count of good people.

## A solution in C++

```cpp
#include <vector>

int maximumGoodPeople(std::vector<std::vector<int>>& statements) {
    int n = statements.size();
    int count_good = 0;
    for(int i = 0; i < n; i++) {
        bool is_good = true;
        for(int j = 0; j < n; j++) {
            if(statements[j][i] == 1 && statements[i][j] == 0) {
                is_good = false;
                break;
            }
        }
        if(is_good) count_good++;
    }
    return count_good;
}
```
We iterate through each person, then we iterate through each statement made by other people about that person. If there are no contradicting statements (someone claims the person is good but the person claims that someone is not good), we consider the person to be good and increment the count. Finally, we return the total count of good people.

## A solution in Python

```python
def maximum_good_people(statements):
    n = len(statements)
    count_good = 0
    for i in range(n):
        is_good = True
        for j in range(n):
            if statements[j][i] == 1 and statements[i][j] == 0:
                is_good = False
                break
        if is_good:
            count_good += 1
    return count_good
```
We iterate through each person, then we iterate through each statement made by other people about that person. If there are no contradicting statements (someone claims the person is good but the person claims that someone is not good), we consider the person to be good and increment the count. Finally, we return the total count of good people.

## A solution in Javascript

```javascript
function maximumGoodPeople(statements) {
    const n = statements.length;
    let count_good = 0;
    for(let i = 0; i < n; i++) {
        let is_good = true;
        for(let j = 0; j < n; j++) {
            if(statements[j][i] === 1 && statements[i][j] === 0) {
                is_good = false;
                break;
            }
        }
        if(is_good) count_good++;
    }
    return count_good;
}
```
We iterate through each person, then we iterate through each statement made by other people about that person. If there are no contradicting statements (someone claims the person is good but the person claims that someone is not good), we consider the person to be good and increment the count. Finally, we return the total count of good people.


# Find Resultant Array After Removing Anagrams

- slug: find-resultant-array-after-removing-anagrams
- difficulty: Easy

You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.

In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you can select an index that satisfies the conditions.

Return `words` _after performing all operations_. It can be shown that selecting the indices for each operation in **any** arbitrary order will lead to the same result.

An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, `"dacb "` is an anagram of `"abdc "`.

**Example 1:**

**Input:** words = \[ "abba ", "baba ", "bbaa ", "cd ", "cd "\]
**Output:** \[ "abba ", "cd "\]
**Explanation:**
One of the ways we can obtain the resultant array is by using the following operations:
- Since words\[2\] =  "bbaa " and words\[1\] =  "baba " are anagrams, we choose index 2 and delete words\[2\].
  Now words = \[ "abba ", "baba ", "cd ", "cd "\].
- Since words\[1\] =  "baba " and words\[0\] =  "abba " are anagrams, we choose index 1 and delete words\[1\].
  Now words = \[ "abba ", "cd ", "cd "\].
- Since words\[2\] =  "cd " and words\[1\] =  "cd " are anagrams, we choose index 2 and delete words\[2\].
  Now words = \[ "abba ", "cd "\].
We can no longer perform any operations, so \[ "abba ", "cd "\] is the final answer.

**Example 2:**

**Input:** words = \[ "a ", "b ", "c ", "d ", "e "\]
**Output:** \[ "a ", "b ", "c ", "d ", "e "\]
**Explanation:**
No two adjacent strings in words are anagrams of each other, so no operations are performed.

**Constraints:**

*   `1 <= words.length <= 100`
*   `1 <= words[i].length <= 10`
*   `words[i]` consists of lowercase English letters.

## A solution in Java

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

public List<String> anagramOperations(String[] words) {
    List<String> result = new ArrayList<>();
    result.add(words[0]);

    for (int i = 1; i < words.length; i++) {
        char[] first = words[i].toCharArray();
        char[] second = words[i - 1].toCharArray();
        Arrays.sort(first);
        Arrays.sort(second);

        if (!Arrays.equals(first, second)) {
            result.add(words[i]);
        }
    }

    return result;
}
```
The algorithm iterates through the input array `words` starting from index 1. For each index `i` it checks if `words[i]` and `words[i-1]` are anagrams by sorting the characters within the two strings and comparing if they are equal (sorting and comparing their characters arrays in Java and JavaScript). If they are anagrams, it removes `words[i]` from the array and decrements index `i`. If not, it increments `i`. This continues until `i` reaches the end of the array. The resulting array will have no adjacent strings that are anagrams, since it iterated through all adjacent pairs and removed anagrams where possible.

## A solution in C++

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

std::vector<std::string> anagramOperations(std::vector<std::string> &words) {
    for (int i = 1; i < words.size(); ++i) {
        std::string s1 = words[i];
        std::string s2 = words[i - 1];
        std::sort(s1.begin(), s1.end());
        std::sort(s2.begin(), s2.end());
        if (s1 == s2) {
            words.erase(words.begin() + i);
            --i;
        }
    }
    return words;
}
```
The algorithm iterates through the input array `words` starting from index 1. For each index `i` it checks if `words[i]` and `words[i-1]` are anagrams by sorting the characters within the two strings and comparing if they are equal (sorting and comparing their characters arrays in Java and JavaScript). If they are anagrams, it removes `words[i]` from the array and decrements index `i`. If not, it increments `i`. This continues until `i` reaches the end of the array. The resulting array will have no adjacent strings that are anagrams, since it iterated through all adjacent pairs and removed anagrams where possible.

## A solution in Python

```python
def anagramOperations(words):
    i = 1
    while i < len(words):
        word1 = sorted(words[i])
        word2 = sorted(words[i - 1])
        if word1 == word2:
            del words[i]
        else:
            i += 1
    return words
```
The algorithm iterates through the input array `words` starting from index 1. For each index `i` it checks if `words[i]` and `words[i-1]` are anagrams by sorting the characters within the two strings and comparing if they are equal (sorting and comparing their characters arrays in Java and JavaScript). If they are anagrams, it removes `words[i]` from the array and decrements index `i`. If not, it increments `i`. This continues until `i` reaches the end of the array. The resulting array will have no adjacent strings that are anagrams, since it iterated through all adjacent pairs and removed anagrams where possible.

## A solution in Javascript

```javascript
function anagramOperations(words) {
  let i = 1;
  while (i < words.length) {
    let word1 = words[i].split('').sort().join('');
    let word2 = words[i - 1].split('').sort().join('');

    if (word1 === word2) {
      words.splice(i, 1);
    } else {
      i++;
    }
  }
  return words;
}
```
The algorithm iterates through the input array `words` starting from index 1. For each index `i` it checks if `words[i]` and `words[i-1]` are anagrams by sorting the characters within the two strings and comparing if they are equal (sorting and comparing their characters arrays in Java and JavaScript). If they are anagrams, it removes `words[i]` from the array and decrements index `i`. If not, it increments `i`. This continues until `i` reaches the end of the array. The resulting array will have no adjacent strings that are anagrams, since it iterated through all adjacent pairs and removed anagrams where possible.


# Maximum Consecutive Floors Without Special Floors

- slug: maximum-consecutive-floors-without-special-floors
- difficulty: Medium

Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be **special floors**, used for relaxation only.

You are given two integers `bottom` and `top`, which denote that Alice has rented all the floors from `bottom` to `top` (**inclusive**). You are also given the integer array `special`, where `special[i]` denotes a special floor that Alice has designated for relaxation.

Return _the **maximum** number of consecutive floors without a special floor_.

**Example 1:**

**Input:** bottom = 2, top = 9, special = \[4,6\]
**Output:** 3
**Explanation:** The following are the ranges (inclusive) of consecutive floors without a special floor:
- (2, 3) with a total amount of 2 floors.
- (5, 5) with a total amount of 1 floor.
- (7, 9) with a total amount of 3 floors.
Therefore, we return the maximum number which is 3 floors.

**Example 2:**

**Input:** bottom = 6, top = 8, special = \[7,6,8\]
**Output:** 0
**Explanation:** Every floor rented is a special floor, so we return 0.

**Constraints:**

*   `1 <= special.length <= 105`
*   `1 <= bottom <= special[i] <= top <= 109`
*   All the values of `special` are **unique**.

## A solution in Java

```java
int finalValue(int[] nums, int original) {
    boolean found = true;
    while (found) {
        found = false;
        for (int num : nums) {
            if (num == original) {
                original++;
                found = true;
                break;
            }
        }
    }
    return original;
}
```
The algorithm is pretty straightforward for all implementations. Declare function `finalValue` that accepts an array of integers `nums` and an integer `original` as input arguments.

Then, execute a while loop which continues until `original` is not found in the `nums` array. Inside the while loop, increment the value of the `original` by 1 (+1) for each iteration.

Once the loop ends, return the final value of `original`.

Note that the algorithm is almost the same for each programming language, with only minor syntax adjustments needed.

## A solution in C++

```cpp
int finalValue(vector<int>& nums, int original) {
    while (find(nums.begin(), nums.end(), original) != nums.end()) {
        original++;
    }
    return original;
}
```
The algorithm is pretty straightforward for all implementations. Declare function `finalValue` that accepts an array of integers `nums` and an integer `original` as input arguments.

Then, execute a while loop which continues until `original` is not found in the `nums` array. Inside the while loop, increment the value of the `original` by 1 (+1) for each iteration.

Once the loop ends, return the final value of `original`.

Note that the algorithm is almost the same for each programming language, with only minor syntax adjustments needed.

## A solution in Python

```python
def final_value(nums, original):
    while original in nums:
        original += 1
    return original
```
The algorithm is pretty straightforward for all implementations. Declare function `finalValue` that accepts an array of integers `nums` and an integer `original` as input arguments.

Then, execute a while loop which continues until `original` is not found in the `nums` array. Inside the while loop, increment the value of the `original` by 1 (+1) for each iteration.

Once the loop ends, return the final value of `original`.

Note that the algorithm is almost the same for each programming language, with only minor syntax adjustments needed.

## A solution in Javascript

```javascript
function finalValue(nums, original) {
    while (nums.includes(original)) {
        original++;
    }
    return original;
}
```
The algorithm is pretty straightforward for all implementations. Declare function `finalValue` that accepts an array of integers `nums` and an integer `original` as input arguments.

Then, execute a while loop which continues until `original` is not found in the `nums` array. Inside the while loop, increment the value of the `original` by 1 (+1) for each iteration.

Once the loop ends, return the final value of `original`.

Note that the algorithm is almost the same for each programming language, with only minor syntax adjustments needed.


# Largest Combination With Bitwise AND Greater Than Zero

- slug: largest-combination-with-bitwise-and-greater-than-zero
- difficulty: Medium

The **bitwise AND** of an array `nums` is the bitwise AND of all integers in `nums`.

*   For example, for `nums = [1, 5, 3]`, the bitwise AND is equal to `1 & 5 & 3 = 1`.
*   Also, for `nums = [7]`, the bitwise AND is `7`.

You are given an array of positive integers `candidates`. Evaluate the **bitwise AND** of every **combination** of numbers of `candidates`. Each number in `candidates` may only be used **once** in each combination.

Return _the size of the **largest** combination of_ `candidates` _with a bitwise AND **greater** than_ `0`.

**Example 1:**

**Input:** candidates = \[16,17,71,62,12,24,14\]
**Output:** 4
**Explanation:** The combination \[16,17,62,24\] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.
The size of the combination is 4.
It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.
Note that more than one combination may have the largest size.
For example, the combination \[62,12,24,14\] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.

**Example 2:**

**Input:** candidates = \[8,8\]
**Output:** 2
**Explanation:** The largest combination \[8,8\] has a bitwise AND of 8 & 8 = 8 > 0.
The size of the combination is 2, so we return 2.

**Constraints:**

*   `1 <= candidates.length <= 105`
*   `1 <= candidates[i] <= 107`

## A solution in Java

```java
public String findSubstring(String s, int power, int modulo, int k, int hashValue) {
    long currentHash = 0;
    long powerK = 1;

    for (int i = 0; i < k; i++) {
        currentHash = (currentHash * power + (s.charAt(i) - 'a' + 1)) % modulo;
        powerK = (powerK * power) % modulo;
    }

    if (currentHash == hashValue) return s.substring(0, k);

    for (int i = k; i < s.length(); i++) {
        currentHash = ((currentHash - (s.charAt(i - k) - 'a' + 1) * powerK) % modulo + modulo) % modulo;
        currentHash = (currentHash * power + (s.charAt(i) - 'a' + 1)) % modulo;
        if (currentHash == hashValue) return s.substring(i - k + 1, i + 1);
    }

    throw new RuntimeException("No matching substring found");
}
```
The algorithm first calculates the hash of the first `k` characters of the string `s`. It also computes `power^K % modulo`. Then it iterates through the rest of the string and tries to find a substring with the target hash value by using a sliding window of size `k`.

For each iteration, the hash of the current substring is adjusted by removing the contribution of the first character on the previous substring and adding the contribution of the new character. This approach prevents recomputation and maintains a running hash of the current substring.

Once a substring with the target hash value is found, it is returned. If no valid substring is found, an error is raised (in some languages, an exception is thrown).

## A solution in C++

```cpp
#include <string>
#include <stdexcept>
using std::string;

string findSubstring(const string& s, int power, int modulo, int k, int hashValue) {
    long long currentHash = 0;
    long long powerK = 1;

    for (int i = 0; i < k; ++i) {
        currentHash = (currentHash * power + (s[i] - 'a' + 1)) % modulo;
        powerK = (powerK * power) % modulo;
    }

    if (currentHash == hashValue) return s.substr(0, k);

    for (int i = k; i < s.size(); ++i) {
        currentHash = ((currentHash - (s[i - k] - 'a' + 1) * powerK) % modulo + modulo) % modulo;
        currentHash = (currentHash * power + (s[i] - 'a' + 1)) % modulo;
        if (currentHash == hashValue) return s.substr(i - k + 1, k);
    }

    throw std::runtime_error("No matching substring found");
}
```
The algorithm first calculates the hash of the first `k` characters of the string `s`. It also computes `power^K % modulo`. Then it iterates through the rest of the string and tries to find a substring with the target hash value by using a sliding window of size `k`.

For each iteration, the hash of the current substring is adjusted by removing the contribution of the first character on the previous substring and adding the contribution of the new character. This approach prevents recomputation and maintains a running hash of the current substring.

Once a substring with the target hash value is found, it is returned. If no valid substring is found, an error is raised (in some languages, an exception is thrown).

## A solution in Python

```python
def find_substring(s, power, modulo, k, hash_value):
    current_hash = 0
    power_k = 1

    for i in range(k):
        current_hash = (current_hash * power + (ord(s[i]) - ord('a') + 1)) % modulo
        power_k = (power_k * power) % modulo

    if current_hash == hash_value:
        return s[:k]

    for i in range(k, len(s)):
        current_hash = ((current_hash - (ord(s[i - k]) - ord('a') + 1) * power_k) % modulo + modulo) % modulo
        current_hash = (current_hash * power + (ord(s[i]) - ord('a') + 1)) % modulo
        if current_hash == hash_value:
            return s[i - k + 1:i + 1]

    raise AssertionError("No matching substring found")
```
The algorithm first calculates the hash of the first `k` characters of the string `s`. It also computes `power^K % modulo`. Then it iterates through the rest of the string and tries to find a substring with the target hash value by using a sliding window of size `k`.

For each iteration, the hash of the current substring is adjusted by removing the contribution of the first character on the previous substring and adding the contribution of the new character. This approach prevents recomputation and maintains a running hash of the current substring.

Once a substring with the target hash value is found, it is returned. If no valid substring is found, an error is raised (in some languages, an exception is thrown).

## A solution in Javascript

```javascript
function findSubstring(s, power, modulo, k, hashValue) {
    let currentHash = 0;
    let powerK = 1;

    for (let i = 0; i < k; i++) {
        currentHash = (currentHash * power + (s.charCodeAt(i) - 'a'.charCodeAt(0) + 1)) % modulo;
        powerK = (powerK * power) % modulo;
    }

    if (currentHash === hashValue) return s.slice(0, k);

    for (let i = k; i < s.length; i++) {
        currentHash = (((currentHash - (s.charCodeAt(i - k) - 'a'.charCodeAt(0) + 1) * powerK) % modulo) + modulo) % modulo;
        currentHash = (currentHash * power + (s.charCodeAt(i) - 'a'.charCodeAt(0) + 1)) % modulo;
        if (currentHash === hashValue) return s.slice(i - k + 1, i + 1);
    }

    throw Error("No matching substring found");
}
```
The algorithm first calculates the hash of the first `k` characters of the string `s`. It also computes `power^K % modulo`. Then it iterates through the rest of the string and tries to find a substring with the target hash value by using a sliding window of size `k`.

For each iteration, the hash of the current substring is adjusted by removing the contribution of the first character on the previous substring and adding the contribution of the new character. This approach prevents recomputation and maintains a running hash of the current substring.

Once a substring with the target hash value is found, it is returned. If no valid substring is found, an error is raised (in some languages, an exception is thrown).


# Count Integers in Intervals

- slug: count-integers-in-intervals
- difficulty: Hard

Given an **empty** set of intervals, implement a data structure that can:

*   **Add** an interval to the set of intervals.
*   **Count** the number of integers that are present in **at least one** interval.

Implement the `CountIntervals` class:

*   `CountIntervals()` Initializes the object with an empty set of intervals.
*   `void add(int left, int right)` Adds the interval `[left, right]` to the set of intervals.
*   `int count()` Returns the number of integers that are present in **at least one** interval.

**Note** that an interval `[left, right]` denotes all the integers `x` where `left <= x <= right`.

**Example 1:**

**Input**
\[ "CountIntervals ",  "add ",  "add ",  "count ",  "add ",  "count "\]
\[\[\], \[2, 3\], \[7, 10\], \[\], \[5, 8\], \[\]\]
**Output**
\[null, null, null, 6, null, 8\]

**Explanation**
CountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals.
countIntervals.add(2, 3);  // add \[2, 3\] to the set of intervals.
countIntervals.add(7, 10); // add \[7, 10\] to the set of intervals.
countIntervals.count();    // return 6
                           // the integers 2 and 3 are present in the interval \[2, 3\].
                           // the integers 7, 8, 9, and 10 are present in the interval \[7, 10\].
countIntervals.add(5, 8);  // add \[5, 8\] to the set of intervals.
countIntervals.count();    // return 8
                           // the integers 2 and 3 are present in the interval \[2, 3\].
                           // the integers 5 and 6 are present in the interval \[5, 8\].
                           // the integers 7 and 8 are present in the intervals \[5, 8\] and \[7, 10\].
                           // the integers 9 and 10 are present in the interval \[7, 10\].

**Constraints:**

*   `1 <= left <= right <= 109`
*   At most `105` calls **in total** will be made to `add` and `count`.
*   At least **one** call will be made to `count`.

## A solution in Java

```java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public int[] groupStrings(String[] words) {
    Map<String, Integer> groups = new HashMap<>();
    int groupsCount = 0;

    for (String word : words) {
        char[] chars = word.toCharArray();
        Arrays.sort(chars);
        String sKey = new String(chars);

        if (!groups.containsKey(sKey)) {
            groups.put(sKey, groupsCount);
            groupsCount++;
        }
    }

    return new int[]{groupsCount, words.length - groupsCount};
}
```
The algorithm first initializes an empty map (or dictionary) called `groups`, which will store the unique combinations of letters within the words. It also initializes a counter `groupsCount`, which will count the number of unique groups.

Then, for each word in the input array, it sorts the characters of the word and creates a new string `sKey` from the sorted characters.

If the `sKey` is not present in the `groups` map, it defines a new group for that `sKey` and increments the `groupsCount`.

Finally, the algorithm returns an array containing the total number of groups (`groupsCount`) and the number of strings in the array minus the groups count. This difference will be the required number of operations to achieve the grouping.

The language-specific implementation details are minimal, mainly in the way maps/dictionaries are accessed and defining return types.

## A solution in C++

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

std::vector<int> groupStrings(std::vector<std::string>& words) {
    std::unordered_map<std::string, int> groups;
    int groupsCount = 0;

    for (const std::string& word : words) {
        std::string sKey(word);
        sort(sKey.begin(), sKey.end());

        if (groups.find(sKey) == groups.end()) {
            groups[sKey] = groupsCount;
            groupsCount++;
        }
    }

    return {groupsCount, words.size() - groupsCount};
}
```
The algorithm first initializes an empty map (or dictionary) called `groups`, which will store the unique combinations of letters within the words. It also initializes a counter `groupsCount`, which will count the number of unique groups.

Then, for each word in the input array, it sorts the characters of the word and creates a new string `sKey` from the sorted characters.

If the `sKey` is not present in the `groups` map, it defines a new group for that `sKey` and increments the `groupsCount`.

Finally, the algorithm returns an array containing the total number of groups (`groupsCount`) and the number of strings in the array minus the groups count. This difference will be the required number of operations to achieve the grouping.

The language-specific implementation details are minimal, mainly in the way maps/dictionaries are accessed and defining return types.

## A solution in Python

```python
def group_strings(words):
    groups = {}
    groups_count = 0

    for word in words:
        s_key = ''.join(sorted(word))

        if s_key not in groups:
            groups[s_key] = groups_count
            groups_count += 1

    return [groups_count, len(words) - groups_count]
```
The algorithm first initializes an empty map (or dictionary) called `groups`, which will store the unique combinations of letters within the words. It also initializes a counter `groupsCount`, which will count the number of unique groups.

Then, for each word in the input array, it sorts the characters of the word and creates a new string `sKey` from the sorted characters.

If the `sKey` is not present in the `groups` map, it defines a new group for that `sKey` and increments the `groupsCount`.

Finally, the algorithm returns an array containing the total number of groups (`groupsCount`) and the number of strings in the array minus the groups count. This difference will be the required number of operations to achieve the grouping.

The language-specific implementation details are minimal, mainly in the way maps/dictionaries are accessed and defining return types.

## A solution in Javascript

```javascript
function groupStrings(words) {
    const groups = new Map();
    let groupsCount = 0;

    words.forEach(word => {
        const sKey = word.split("").sort().join("");

        if (!groups.has(sKey)) {
            groups.set(sKey, groupsCount);
            groupsCount++;
        }
    });

    return [groupsCount, words.length - groupsCount];
}
```
The algorithm first initializes an empty map (or dictionary) called `groups`, which will store the unique combinations of letters within the words. It also initializes a counter `groupsCount`, which will count the number of unique groups.

Then, for each word in the input array, it sorts the characters of the word and creates a new string `sKey` from the sorted characters.

If the `sKey` is not present in the `groups` map, it defines a new group for that `sKey` and increments the `groupsCount`.

Finally, the algorithm returns an array containing the total number of groups (`groupsCount`) and the number of strings in the array minus the groups count. This difference will be the required number of operations to achieve the grouping.

The language-specific implementation details are minimal, mainly in the way maps/dictionaries are accessed and defining return types.


# Closest Node to Path in Tree

- slug: closest-node-to-path-in-tree
- difficulty: Hard

You are given a positive integer `n` representing the number of nodes in a tree, numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges` of length `n - 1`, where `edges[i] = [node1i, node2i]` denotes that there is a **bidirectional** edge connecting `node1i` and `node2i` in the tree.

You are given a **0-indexed** integer array `query` of length `m` where `query[i] = [starti, endi, nodei]` means that for the `ith` query, you are tasked with finding the node on the path from `starti` to `endi` that is **closest** to `nodei`.

Return _an integer array_ `answer` _of length_ `m`_, where_ `answer[i]` _is the answer to the_ `ith` _query_.

**Example 1:**

**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[0,3\],\[1,4\],\[2,5\],\[2,6\]\], query = \[\[5,3,4\],\[5,3,6\]\]
**Output:** \[0,2\]
**Explanation:**
The path from node 5 to node 3 consists of the nodes 5, 2, 0, and 3.
The distance between node 4 and node 0 is 2.
Node 0 is the node on the path closest to node 4, so the answer to the first query is 0.
The distance between node 6 and node 2 is 1.
Node 2 is the node on the path closest to node 6, so the answer to the second query is 2.

**Example 2:**

**Input:** n = 3, edges = \[\[0,1\],\[1,2\]\], query = \[\[0,1,2\]\]
**Output:** \[1\]
**Explanation:**
The path from node 0 to node 1 consists of the nodes 0, 1.
The distance between node 2 and node 1 is 1.
Node 1 is the node on the path closest to node 2, so the answer to the first query is 1.

**Example 3:**

**Input:** n = 3, edges = \[\[0,1\],\[1,2\]\], query = \[\[0,0,0\]\]
**Output:** \[0\]
**Explanation:**
The path from node 0 to node 0 consists of the node 0.
Since 0 is the only node on the path, the answer to the first query is 0.

**Constraints:**

*   `1 <= n <= 1000`
*   `edges.length == n - 1`
*   `edges[i].length == 2`
*   `0 <= node1i, node2i <= n - 1`
*   `node1i != node2i`
*   `1 <= query.length <= 1000`
*   `query[i].length == 3`
*   `0 <= starti, endi, nodei <= n - 1`
*   The graph is a tree.

## A solution in Java

```java
import java.util.*;

public List<Integer> closestNodes(int n, List<List<Integer>> edges, List<List<Integer>> query) {
    List<Integer> answer = new ArrayList<>();
    List<List<Integer>> tree = new ArrayList<>();

    for (int i = 0; i < n; i++) {
        tree.add(new ArrayList<>());
    }

    for (List<Integer> edge : edges) {
        tree.get(edge.get(0)).add(edge.get(1));
        tree.get(edge.get(1)).add(edge.get(0));
    }

    for (List<Integer> q : query) {
        int lca = bfs(q.get(0), q.get(1), tree);
        int node1 = bfs(lca, q.get(0), tree);
        int node2 = bfs(lca, q.get(1), tree);
        answer.add(node1 == q.get(2) ? q.get(0) : q.get(1));
    }

    return answer;
}

private int bfs(int start, int end, List<List<Integer>> tree) {
    Queue<Integer> queue = new LinkedList<>();
    Set<Integer> visited = new HashSet<>();
    queue.add(start);
    visited.add(start);

    while (!queue.isEmpty()) {
        int current = queue.poll();

        if (current == end) {
            return current;
        }

        for (int neighbor : tree.get(current)) {
            if (!visited.contains(neighbor)) {
                queue.add(neighbor);
                visited.add(neighbor);
            }
        }
    }

    return -1;
}
```
1. Create an adjacency list `tree` using the given `edges`.
2. Define a `bfs` function that performs a breadth-first search of the tree and returns the target node when it's found. The `bfs` function takes two arguments: the starting node and the target node.
3. Initialize an empty list called `answer`.
4. Iterate through the `query` list, and for each query, find the least common ancestor (LCA) of the `start` and `end` nodes using the `bfs` function.
5. Based on the result of the LCA, find which of the `start` or `end` nodes is closest to the given `node` using the `bfs` function again.
6. Add the result to the `answer` list.
7. Once all queries have been iterated, return the `answer` list.

## A solution in C++

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

std::vector<int> closestNodes(int n, std::vector<std::vector<int>>& edges, std::vector<std::vector<int>>& query) {
    std::vector<int> answer;

    std::vector<std::vector<int>> tree(n);
    for (auto& edge : edges) {
        tree[edge[0]].push_back(edge[1]);
        tree[edge[1]].push_back(edge[0]);
    }

    auto bfs = [&](int start, int end) {
        std::queue<int> q;
        std::vector<bool> visited(n, false);
        q.push(start);
        visited[start] = true;

        while (!q.empty()) {
            int current = q.front();
            q.pop();

            if (current == end) {
                return current;
            }

            for (int neighbor : tree[current]) {
                if (!visited[neighbor]) {
                    q.push(neighbor);
                    visited[neighbor] = true;
                }
            }
        }
        return -1;
    };

    for (auto& q : query) {
        int lca = bfs(q[0], q[1]);
        int node1 = bfs(lca, q[0]);
        int node2 = bfs(lca, q[1]);
        answer.push_back(node1 == q[2] ? q[0] : q[1]);
    }

    return answer;
}
```
1. Create an adjacency list `tree` using the given `edges`.
2. Define a `bfs` function that performs a breadth-first search of the tree and returns the target node when it's found. The `bfs` function takes two arguments: the starting node and the target node.
3. Initialize an empty list called `answer`.
4. Iterate through the `query` list, and for each query, find the least common ancestor (LCA) of the `start` and `end` nodes using the `bfs` function.
5. Based on the result of the LCA, find which of the `start` or `end` nodes is closest to the given `node` using the `bfs` function again.
6. Add the result to the `answer` list.
7. Once all queries have been iterated, return the `answer` list.

## A solution in Python

```python
from collections import deque

def closest_nodes(n, edges, query):
    answer = []
    tree = [[] for _ in range(n)]

    for edge in edges:
        tree[edge[0]].append(edge[1])
        tree[edge[1]].append(edge[0])

    def bfs(start, end):
        queue = deque([start])
        visited = {start}

        while queue:
            current = queue.popleft()

            if current == end:
                return current

            for neighbor in tree[current]:
                if neighbor not in visited:
                    queue.append(neighbor)
                    visited.add(neighbor)

    for q in query:
        lca = bfs(q[0], q[1])
        node1 = bfs(lca, q[0])
        node2 = bfs(lca, q[1])
        answer.append(q[0] if node1 == q[2] else q[1])

    return answer
```
1. Create an adjacency list `tree` using the given `edges`.
2. Define a `bfs` function that performs a breadth-first search of the tree and returns the target node when it's found. The `bfs` function takes two arguments: the starting node and the target node.
3. Initialize an empty list called `answer`.
4. Iterate through the `query` list, and for each query, find the least common ancestor (LCA) of the `start` and `end` nodes using the `bfs` function.
5. Based on the result of the LCA, find which of the `start` or `end` nodes is closest to the given `node` using the `bfs` function again.
6. Add the result to the `answer` list.
7. Once all queries have been iterated, return the `answer` list.

## A solution in Javascript

```javascript
function closestNodes(n, edges, query) {
    const answer = [];
    const tree = Array.from({ length: n }, () => []);

    for (const edge of edges) {
        tree[edge[0]].push(edge[1]);
        tree[edge[1]].push(edge[0]);
    }

    function bfs(start, end) {
        const queue = [start];
        const visited = new Set([start]);

        while (queue.length > 0) {
            const current = queue.shift();

            if (current === end) {
                return current;
            }

            for (const neighbor of tree[current]) {
                if (!visited.has(neighbor)) {
                    queue.push(neighbor);
                    visited.add(neighbor);
                }
            }
        }
    }

    for (const q of query) {
        const lca = bfs(q[0], q[1]);
        const node1 = bfs(lca, q[0]);
        const node2 = bfs(lca, q[1]);
        answer.push(node1 === q[2] ? q[0] : q[1]);
    }

    return answer;
}
```
1. Create an adjacency list `tree` using the given `edges`.
2. Define a `bfs` function that performs a breadth-first search of the tree and returns the target node when it's found. The `bfs` function takes two arguments: the starting node and the target node.
3. Initialize an empty list called `answer`.
4. Iterate through the `query` list, and for each query, find the least common ancestor (LCA) of the `start` and `end` nodes using the `bfs` function.
5. Based on the result of the LCA, find which of the `start` or `end` nodes is closest to the given `node` using the `bfs` function again.
6. Add the result to the `answer` list.
7. Once all queries have been iterated, return the `answer` list.


# Percentage of Letter in String

- slug: percentage-of-letter-in-string
- difficulty: Easy

Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._

**Example 1:**

**Input:** s =  "foobar ", letter =  "o "
**Output:** 33
**Explanation:**
The percentage of characters in s that equal the letter 'o' is 2 / 6 \* 100% = 33% when rounded down, so we return 33.

**Example 2:**

**Input:** s =  "jjjj ", letter =  "k "
**Output:** 0
**Explanation:**
The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.

**Constraints:**

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

## A solution in Java

```java
public int[] threeConsecutiveIntegers(int num) {
    if (num % 3 == 0) {
        return new int[]{num / 3 - 1, num / 3, num / 3 + 1};
    } else if (num % 3 == 1) {
        return new int[]{(num - 2) / 3, (num + 1) / 3, (num + 4) / 3};
    } else {
        return new int[]{};
    }
}
```
The algorithm first checks if the number `num` is divisible by 3. If it is, the three consecutive integers must be `{num / 3 - 1, num / 3, num / 3 + 1}`. If `num` is one more than a multiple of 3 (i.e., `num % 3 == 1`), then the three consecutive integers are `{(num - 2) / 3, (num + 1) / 3, (num + 4) / 3}`. If `num` is neither divisible by 3 nor one more than a multiple of 3 (i.e., `num % 3 == 2`), it cannot be expressed as the sum of three consecutive integers, so the function returns an empty array.

## A solution in C++

```cpp
#include <vector>

std::vector<int> threeConsecutiveIntegers(int num) {
    if (num % 3 == 0) {
        return {num / 3 - 1, num / 3, num / 3 + 1};
    } else if (num % 3 == 1) {
        return {(num - 2) / 3, (num + 1) / 3, (num + 4) / 3};
    } else {
        return {};
    }
}
```
The algorithm first checks if the number `num` is divisible by 3. If it is, the three consecutive integers must be `{num / 3 - 1, num / 3, num / 3 + 1}`. If `num` is one more than a multiple of 3 (i.e., `num % 3 == 1`), then the three consecutive integers are `{(num - 2) / 3, (num + 1) / 3, (num + 4) / 3}`. If `num` is neither divisible by 3 nor one more than a multiple of 3 (i.e., `num % 3 == 2`), it cannot be expressed as the sum of three consecutive integers, so the function returns an empty array.

## A solution in Python

```python
def three_consecutive_integers(num):
    if num % 3 == 0:
        return [num // 3 - 1, num // 3, num // 3 + 1]
    elif num % 3 == 1:
        return [(num - 2) // 3, (num + 1) // 3, (num + 4) // 3]
    else:
        return []
```
The algorithm first checks if the number `num` is divisible by 3. If it is, the three consecutive integers must be `{num / 3 - 1, num / 3, num / 3 + 1}`. If `num` is one more than a multiple of 3 (i.e., `num % 3 == 1`), then the three consecutive integers are `{(num - 2) / 3, (num + 1) / 3, (num + 4) / 3}`. If `num` is neither divisible by 3 nor one more than a multiple of 3 (i.e., `num % 3 == 2`), it cannot be expressed as the sum of three consecutive integers, so the function returns an empty array.

## A solution in Javascript

```javascript
function threeConsecutiveIntegers(num) {
    if (num % 3 === 0) {
        return [num / 3 - 1, num / 3, num / 3 + 1];
    } else if (num % 3 === 1) {
        return [(num - 2) / 3, (num + 1) / 3, (num + 4) / 3];
    } else {
        return [];
    }
}
```
The algorithm first checks if the number `num` is divisible by 3. If it is, the three consecutive integers must be `{num / 3 - 1, num / 3, num / 3 + 1}`. If `num` is one more than a multiple of 3 (i.e., `num % 3 == 1`), then the three consecutive integers are `{(num - 2) / 3, (num + 1) / 3, (num + 4) / 3}`. If `num` is neither divisible by 3 nor one more than a multiple of 3 (i.e., `num % 3 == 2`), it cannot be expressed as the sum of three consecutive integers, so the function returns an empty array.


# Maximum Bags With Full Capacity of Rocks

- slug: maximum-bags-with-full-capacity-of-rocks
- difficulty: Medium

You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any** of the bags.

Return _the **maximum** number of bags that could have full capacity after placing the additional rocks in some bags._

**Example 1:**

**Input:** capacity = \[2,3,4,5\], rocks = \[1,2,4,4\], additionalRocks = 2
**Output:** 3
**Explanation:**
Place 1 rock in bag 0 and 1 rock in bag 1.
The number of rocks in each bag are now \[2,3,4,4\].
Bags 0, 1, and 2 have full capacity.
There are 3 bags at full capacity, so we return 3.
It can be shown that it is not possible to have more than 3 bags at full capacity.
Note that there may be other ways of placing the rocks that result in an answer of 3.

**Example 2:**

**Input:** capacity = \[10,2,2\], rocks = \[2,2,0\], additionalRocks = 100
**Output:** 3
**Explanation:**
Place 8 rocks in bag 0 and 2 rocks in bag 2.
The number of rocks in each bag are now \[10,2,2\].
Bags 0, 1, and 2 have full capacity.
There are 3 bags at full capacity, so we return 3.
It can be shown that it is not possible to have more than 3 bags at full capacity.
Note that we did not use all of the additional rocks.

**Constraints:**

*   `n == capacity.length == rocks.length`
*   `1 <= n <= 5 * 104`
*   `1 <= capacity[i] <= 109`
*   `0 <= rocks[i] <= capacity[i]`
*   `1 <= additionalRocks <= 109`

## A solution in Java

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

public List<Integer> maxUniqueEvenSum(int finalSum) {
    List<Integer> result = new ArrayList<>();
    int current = 2;
    while (finalSum > 0) {
        if (finalSum >= current) {
            result.add(current);
            finalSum -= current;
            current += 2;
        } else {
            break;
        }
    }
    return result;
}
```
1. Initialize an empty list to store the unique even integers that will form the final sum.
2. Initialize a variable `current` with the value 2. This will be the smallest even integer that can be part of the final sum.
3. Run a loop while the `finalSum` is greater than zero.
4. Check if the current `finalSum` is greater than or equal to the `current` value.
   - If yes, append the `current` value to the result list, subtract its value from `finalSum`, and increment `current` by 2.
   - If no, break out of the loop since we cannot accommodate more numbers in the sum.
5. Return the result list containing the unique even integers that form the given `finalSum`.

## A solution in C++

```cpp
#include <iostream>
#include <vector>

std::vector<int> maxUniqueEvenSum(int finalSum) {
    std::vector<int> result;
    int current = 2;
    while (finalSum > 0) {
        if (finalSum >= current) {
            result.push_back(current);
            finalSum -= current;
            current += 2;
        } else {
            break;
        }
    }
    return result;
}
```
1. Initialize an empty list to store the unique even integers that will form the final sum.
2. Initialize a variable `current` with the value 2. This will be the smallest even integer that can be part of the final sum.
3. Run a loop while the `finalSum` is greater than zero.
4. Check if the current `finalSum` is greater than or equal to the `current` value.
   - If yes, append the `current` value to the result list, subtract its value from `finalSum`, and increment `current` by 2.
   - If no, break out of the loop since we cannot accommodate more numbers in the sum.
5. Return the result list containing the unique even integers that form the given `finalSum`.

## A solution in Python

```python
def max_unique_even_sum(final_sum):
    result = []
    current = 2
    while final_sum > 0:
        if final_sum >= current:
            result.append(current)
            final_sum -= current
            current += 2
        else:
            break
    return result
```
1. Initialize an empty list to store the unique even integers that will form the final sum.
2. Initialize a variable `current` with the value 2. This will be the smallest even integer that can be part of the final sum.
3. Run a loop while the `finalSum` is greater than zero.
4. Check if the current `finalSum` is greater than or equal to the `current` value.
   - If yes, append the `current` value to the result list, subtract its value from `finalSum`, and increment `current` by 2.
   - If no, break out of the loop since we cannot accommodate more numbers in the sum.
5. Return the result list containing the unique even integers that form the given `finalSum`.

## A solution in Javascript

```javascript
function maxUniqueEvenSum(finalSum) {
    let result = [];
    let current = 2;
    while (finalSum > 0) {
        if (finalSum >= current) {
            result.push(current);
            finalSum -= current;
            current += 2;
        } else {
            break;
        }
    }
    return result;
}
```
1. Initialize an empty list to store the unique even integers that will form the final sum.
2. Initialize a variable `current` with the value 2. This will be the smallest even integer that can be part of the final sum.
3. Run a loop while the `finalSum` is greater than zero.
4. Check if the current `finalSum` is greater than or equal to the `current` value.
   - If yes, append the `current` value to the result list, subtract its value from `finalSum`, and increment `current` by 2.
   - If no, break out of the loop since we cannot accommodate more numbers in the sum.
5. Return the result list containing the unique even integers that form the given `finalSum`.


# Minimum Lines to Represent a Line Chart

- slug: minimum-lines-to-represent-a-line-chart
- difficulty: Medium

You are given a 2D integer array `stockPrices` where `stockPrices[i] = [dayi, pricei]` indicates the price of the stock on day `dayi` is `pricei`. A **line chart** is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below:

Return _the **minimum number of lines** needed to represent the line chart_.

**Example 1:**

**Input:** stockPrices = \[\[1,7\],\[2,6\],\[3,5\],\[4,4\],\[5,4\],\[6,3\],\[7,2\],\[8,1\]\]
**Output:** 3
**Explanation:**
The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.
The following 3 lines can be drawn to represent the line chart:
- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).
- Line 2 (in blue) from (4,4) to (5,4).
- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).
It can be shown that it is not possible to represent the line chart using less than 3 lines.

**Example 2:**

**Input:** stockPrices = \[\[3,4\],\[1,2\],\[7,8\],\[2,3\]\]
**Output:** 1
**Explanation:**
As shown in the diagram above, the line chart can be represented with a single line.

**Constraints:**

*   `1 <= stockPrices.length <= 105`
*   `stockPrices[i].length == 2`
*   `1 <= dayi, pricei <= 109`
*   All `dayi` are **distinct**.

## A solution in Java

```java
public int countGoodTriplets(int[] nums1, int[] nums2) {
    int n = nums1.length;
    int[] pos1 = new int[n];
    int[] pos2 = new int[n];
    for (int i = 0; i < n; i++) {
        pos1[nums1[i]] = i;
        pos2[nums2[i]] = i;
    }
    int count = 0;
    for (int x = 0; x < n; x++) {
        for (int y = x + 1; y < n; y++) {
            for (int z = y + 1; z < n; z++) {
                if (pos1[x] < pos1[y] && pos1[y] < pos1[z] && pos2[x] < pos2[y] && pos2[y] < pos2[z]) {
                    count++;
                }
            }
        }
    }
    return count;
}
```
1. Create two new arrays `pos1` and `pos2` of length n to store the positions of values in `nums1` and `nums2` respectively.
2. Iterate through both `nums1` and `nums2`, for each value v, store its position in the corresponding position array.
3. Initialize a count variable to store the count of good triplets.
4. Iterate through all possible triplets (x, y, z) using three nested loops.
5. Check if the current triplet (x, y, z) satisfies the condition pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. If it does, increment the count.
6. After the loops finish, return the count of good triplets.

## A solution in C++

```cpp
int countGoodTriplets(vector<int>& nums1, vector<int>& nums2) {
    int n = nums1.size();
    vector<int> pos1(n), pos2(n);
    for (int i = 0; i < n; ++i) {
        pos1[nums1[i]] = i;
        pos2[nums2[i]] = i;
    }
    int count = 0;
    for (int x = 0; x < n; ++x) {
        for (int y = x + 1; y < n; ++y) {
            for (int z = y + 1; z < n; ++z) {
                if (pos1[x] < pos1[y] && pos1[y] < pos1[z] && pos2[x] < pos2[y] && pos2[y] < pos2[z]) {
                    count++;
                }
            }
        }
    }
    return count;
}
```
1. Create two new arrays `pos1` and `pos2` of length n to store the positions of values in `nums1` and `nums2` respectively.
2. Iterate through both `nums1` and `nums2`, for each value v, store its position in the corresponding position array.
3. Initialize a count variable to store the count of good triplets.
4. Iterate through all possible triplets (x, y, z) using three nested loops.
5. Check if the current triplet (x, y, z) satisfies the condition pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. If it does, increment the count.
6. After the loops finish, return the count of good triplets.

## A solution in Python

```python
def count_good_triplets(nums1: list, nums2: list) -> int:
    n = len(nums1)
    pos1 = [0] * n
    pos2 = [0] * n
    for i in range(n):
        pos1[nums1[i]] = i
        pos2[nums2[i]] = i
    count = 0
    for x in range(n):
        for y in range(x + 1, n):
            for z in range(y + 1, n):
                if pos1[x] < pos1[y] < pos1[z] and pos2[x] < pos2[y] < pos2[z]:
                    count += 1
    return count
```
1. Create two new arrays `pos1` and `pos2` of length n to store the positions of values in `nums1` and `nums2` respectively.
2. Iterate through both `nums1` and `nums2`, for each value v, store its position in the corresponding position array.
3. Initialize a count variable to store the count of good triplets.
4. Iterate through all possible triplets (x, y, z) using three nested loops.
5. Check if the current triplet (x, y, z) satisfies the condition pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. If it does, increment the count.
6. After the loops finish, return the count of good triplets.

## A solution in Javascript

```javascript
function countGoodTriplets(nums1, nums2) {
    const n = nums1.length;
    const pos1 = new Array(n);
    const pos2 = new Array(n);
    for (let i = 0; i < n; i++) {
        pos1[nums1[i]] = i;
        pos2[nums2[i]] = i;
    }
    let count = 0;
    for (let x = 0; x < n; x++) {
        for (let y = x + 1; y < n; y++) {
            for (let z = y + 1; z < n; z++) {
                if (pos1[x] < pos1[y] && pos1[y] < pos1[z] && pos2[x] < pos2[y] && pos2[y] < pos2[z]) {
                    count++;
                }
            }
        }
    }
    return count;
}
```
1. Create two new arrays `pos1` and `pos2` of length n to store the positions of values in `nums1` and `nums2` respectively.
2. Iterate through both `nums1` and `nums2`, for each value v, store its position in the corresponding position array.
3. Initialize a count variable to store the count of good triplets.
4. Iterate through all possible triplets (x, y, z) using three nested loops.
5. Check if the current triplet (x, y, z) satisfies the condition pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. If it does, increment the count.
6. After the loops finish, return the count of good triplets.