# Construct Target Array With Multiple Sums

- slug: construct-target-array-with-multiple-sums
- difficulty: Hard

You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure :

*   let `x` be the sum of all elements currently in your array.
*   choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`.
*   You may repeat this procedure as many times as needed.

Return `true` _if it is possible to construct the_ `target` _array from_ `arr`_, otherwise, return_ `false`.

**Example 1:**

**Input:** target = \[9,3,5\]
**Output:** true
**Explanation:** Start with arr = \[1, 1, 1\]
\[1, 1, 1\], sum = 3 choose index 1
\[1, 3, 1\], sum = 5 choose index 2
\[1, 3, 5\], sum = 9 choose index 0
\[9, 3, 5\] Done

**Example 2:**

**Input:** target = \[1,1,1,2\]
**Output:** false
**Explanation:** Impossible to create target array from \[1,1,1,1\].

**Example 3:**

**Input:** target = \[8,5\]
**Output:** true

**Constraints:**

*   `n == target.length`
*   `1 <= n <= 5 * 104`
*   `1 <= target[i] <= 109`

## A solution in Java

```java
import java.util.*;

public List<List<Integer>> winnersAndLosers(int[][] matches) {
    TreeSet<Integer> winners = new TreeSet<>();
    TreeSet<Integer> losers = new TreeSet<>();
    for (int[] match : matches) {
        winners.add(match[0]);
        losers.add(match[1]);
    }
    return Arrays.asList(new ArrayList<>(winners), new ArrayList<>(losers));
}
```
The algorithm first initializes two sorted sets - one for winners and one for losers.

For each match in the input, we extract the winner and loser and insert them into their respective sorted sets. Sorted sets automatically maintain the ordering and uniqueness of elements.

Finally, we convert the sorted sets to arrays/lists in their respective languages and return an array/list containing two arrays/lists - the winners and the losers - each sorted in increasing order.

## A solution in C++

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

vector<vector<int>> winnersAndLosers(vector<vector<int>>& matches) {
    set<int> winners, losers;
    for (vector<int> &match : matches) {
        winners.insert(match[0]);
        losers.insert(match[1]);
    }
    return {vector<int>(winners.begin(), winners.end()), vector<int>(losers.begin(), losers.end())};
}
```
The algorithm first initializes two sorted sets - one for winners and one for losers.

For each match in the input, we extract the winner and loser and insert them into their respective sorted sets. Sorted sets automatically maintain the ordering and uniqueness of elements.

Finally, we convert the sorted sets to arrays/lists in their respective languages and return an array/list containing two arrays/lists - the winners and the losers - each sorted in increasing order.

## A solution in Python

```python
from sortedcontainers import SortedSet

def winners_and_losers(matches):
    winners, losers = SortedSet(), SortedSet()

    for winner, loser in matches:
        winners.add(winner)
        losers.add(loser)

    return [list(winners), list(losers)]
```
The algorithm first initializes two sorted sets - one for winners and one for losers.

For each match in the input, we extract the winner and loser and insert them into their respective sorted sets. Sorted sets automatically maintain the ordering and uniqueness of elements.

Finally, we convert the sorted sets to arrays/lists in their respective languages and return an array/list containing two arrays/lists - the winners and the losers - each sorted in increasing order.

## A solution in Javascript

```javascript
function winnersAndLosers(matches) {
    const winners = new Set();
    const losers = new Set();

    for (const match of matches) {
        winners.add(match[0]);
        losers.add(match[1]);
    }

    return [Array.from(winners).sort((a, b) => a - b), Array.from(losers).sort((a, b) => a - b)];
}
```
The algorithm first initializes two sorted sets - one for winners and one for losers.

For each match in the input, we extract the winner and loser and insert them into their respective sorted sets. Sorted sets automatically maintain the ordering and uniqueness of elements.

Finally, we convert the sorted sets to arrays/lists in their respective languages and return an array/list containing two arrays/lists - the winners and the losers - each sorted in increasing order.


# Sort Integers by The Number of 1 Bits

- slug: sort-integers-by-the-number-of-1-bits
- difficulty: Easy

You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order.

Return _the array after sorting it_.

**Example 1:**

**Input:** arr = \[0,1,2,3,4,5,6,7,8\]
**Output:** \[0,1,2,4,8,3,5,6,7\]
**Explantion:** \[0\] is the only integer with 0 bits.
\[1,2,4,8\] all have 1 bit.
\[3,5,6\] have 2 bits.
\[7\] has 3 bits.
The sorted array by bits is \[0,1,2,4,8,3,5,6,7\]

**Example 2:**

**Input:** arr = \[1024,512,256,128,64,32,16,8,4,2,1\]
**Output:** \[1,2,4,8,16,32,64,128,256,512,1024\]
**Explantion:** All integers have 1 bit in the binary representation, you should just sort them in ascending order.

**Constraints:**

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

## A solution in Java

```java
public int minMovesToPalindrome(String s) {
    char[] chars = s.toCharArray();
    int moves = 0;
    int left = 0, right = s.length() - 1;

    while (left < right) {
        if (chars[left] != chars[right]) {
            int temp_right = right;

            while (chars[left] != chars[temp_right]) {
                temp_right--;
            }
            char temp = chars[temp_right];
            System.arraycopy(chars, temp_right + 1, chars, temp_right, right - temp_right);
            chars[right] = temp;
            moves += right - temp_right;
        }
        left++;
        right--;
    }

    return moves;
}
```
1. Initialize variables `moves` to store the total number of moves, and `left` and `right` pointers for both ends of string s.
2. Iterate until the `left` pointer is less than `right`.
   a. If the characters at the left and right pointers are not equal, find the position of the left pointer character in the remaining right section of the string.
   b. Swap the characters found in the right section with the character at 'right' position.
   c. Increment the number of moves by the distance between the `right` and the swap position.
3. Increment the `left` pointer and decrement the `right` pointer after each iteration.
4. Finally, return the total number of moves.

## A solution in C++

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

int min_moves_to_palindrome(string s) {
    int moves = 0;
    int left = 0, right = s.length() - 1;

    while (left < right) {
        if (s[left] != s[right]) {
            int temp_right = right;

            while (s[left] != s[temp_right]) {
                temp_right--;
            }
            s.erase(s.begin() + temp_right);
            s.insert(s.begin() + right, s[left]);
            moves += right - temp_right;
        }
        left++;
        right--;
    }

    return moves;
}
```
1. Initialize variables `moves` to store the total number of moves, and `left` and `right` pointers for both ends of string s.
2. Iterate until the `left` pointer is less than `right`.
   a. If the characters at the left and right pointers are not equal, find the position of the left pointer character in the remaining right section of the string.
   b. Swap the characters found in the right section with the character at 'right' position.
   c. Increment the number of moves by the distance between the `right` and the swap position.
3. Increment the `left` pointer and decrement the `right` pointer after each iteration.
4. Finally, return the total number of moves.

## A solution in Python

```python
def min_moves_to_palindrome(s: str) -> int:
    moves = 0
    s = list(s)
    left, right = 0, len(s) - 1

    while left < right:
        if s[left] != s[right]:
            temp_right = right

            while s[left] != s[temp_right]:
                temp_right -= 1
            s.insert(right, s.pop(temp_right))
            moves += right - temp_right
        left += 1
        right -= 1

    return moves
```
1. Initialize variables `moves` to store the total number of moves, and `left` and `right` pointers for both ends of string s.
2. Iterate until the `left` pointer is less than `right`.
   a. If the characters at the left and right pointers are not equal, find the position of the left pointer character in the remaining right section of the string.
   b. Swap the characters found in the right section with the character at 'right' position.
   c. Increment the number of moves by the distance between the `right` and the swap position.
3. Increment the `left` pointer and decrement the `right` pointer after each iteration.
4. Finally, return the total number of moves.

## A solution in Javascript

```javascript
function minMovesToPalindrome(s) {
    let moves = 0;
    s = s.split('');
    let left = 0, right = s.length - 1;

    while (left < right) {
        if (s[left] !== s[right]) {
            let temp_right = right;

            while (s[left] !== s[temp_right]) {
                temp_right--;
            }
            s.splice(right, 0, s.splice(temp_right, 1)[0]);
            moves += right - temp_right;
        }
        left++;
        right--;
    }

    return moves;
}
```
1. Initialize variables `moves` to store the total number of moves, and `left` and `right` pointers for both ends of string s.
2. Iterate until the `left` pointer is less than `right`.
   a. If the characters at the left and right pointers are not equal, find the position of the left pointer character in the remaining right section of the string.
   b. Swap the characters found in the right section with the character at 'right' position.
   c. Increment the number of moves by the distance between the `right` and the swap position.
3. Increment the `left` pointer and decrement the `right` pointer after each iteration.
4. Finally, return the total number of moves.


# Apply Discount Every n Orders

- slug: apply-discount-every-n-orders
- difficulty: Medium

There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the `ith` product has an ID of `products[i]` and a price of `prices[i]`.

When a customer is paying, their bill is represented as two parallel integer arrays `product` and `amount`, where the `jth` product they purchased has an ID of `product[j]`, and `amount[j]` is how much of the product they bought. Their subtotal is calculated as the sum of each `amount[j] * (price of the jth product)`.

The supermarket decided to have a sale. Every `nth` customer paying for their groceries will be given a **percentage discount**. The discount amount is given by `discount`, where they will be given `discount` percent off their subtotal. More formally, if their subtotal is `bill`, then they would actually pay `bill * ((100 - discount) / 100)`.

Implement the `Cashier` class:

*   `Cashier(int n, int discount, int[] products, int[] prices)` Initializes the object with `n`, the `discount`, and the `products` and their `prices`.
*   `double getBill(int[] product, int[] amount)` Returns the final total of the bill with the discount applied (if any). Answers within `10-5` of the actual value will be accepted.

**Example 1:**

**Input**
\[ "Cashier ", "getBill ", "getBill ", "getBill ", "getBill ", "getBill ", "getBill ", "getBill "\]
\[\[3,50,\[1,2,3,4,5,6,7\],\[100,200,300,400,300,200,100\]\],\[\[1,2\],\[1,2\]\],\[\[3,7\],\[10,10\]\],\[\[1,2,3,4,5,6,7\],\[1,1,1,1,1,1,1\]\],\[\[4\],\[10\]\],\[\[7,3\],\[10,10\]\],\[\[7,5,3,1,6,4,2\],\[10,10,10,9,9,9,7\]\],\[\[2,3,5\],\[5,3,2\]\]\]
**Output**
\[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0\]
**Explanation**
Cashier cashier = new Cashier(3,50,\[1,2,3,4,5,6,7\],\[100,200,300,400,300,200,100\]);
cashier.getBill(\[1,2\],\[1,2\]);                        // return 500.0. 1st customer, no discount.
                                                     // bill = 1 \* 100 + 2 \* 200 = 500.
cashier.getBill(\[3,7\],\[10,10\]);                      // return 4000.0. 2nd customer, no discount.
                                                     // bill = 10 \* 300 + 10 \* 100 = 4000.
cashier.getBill(\[1,2,3,4,5,6,7\],\[1,1,1,1,1,1,1\]);    // return 800.0. 3rd customer, 50% discount.
                                                     // Original bill = 1600
                                                     // Actual bill = 1600 \* ((100 - 50) / 100) = 800.
cashier.getBill(\[4\],\[10\]);                           // return 4000.0. 4th customer, no discount.
cashier.getBill(\[7,3\],\[10,10\]);                      // return 4000.0. 5th customer, no discount.
cashier.getBill(\[7,5,3,1,6,4,2\],\[10,10,10,9,9,9,7\]); // return 7350.0. 6th customer, 50% discount.
                                                     // Original bill = 14700, but with
                                                     // Actual bill = 14700 \* ((100 - 50) / 100) = 7350.
cashier.getBill(\[2,3,5\],\[5,3,2\]);                    // return 2500.0.  6th customer, no discount.

**Constraints:**

*   `1 <= n <= 104`
*   `0 <= discount <= 100`
*   `1 <= products.length <= 200`
*   `prices.length == products.length`
*   `1 <= products[i] <= 200`
*   `1 <= prices[i] <= 1000`
*   The elements in `products` are **unique**.
*   `1 <= product.length <= products.length`
*   `amount.length == product.length`
*   `product[j]` exists in `products`.
*   `1 <= amount[j] <= 1000`
*   The elements of `product` are **unique**.
*   At most `1000` calls will be made to `getBill`.
*   Answers within `10-5` of the actual value will be accepted.

## A solution in Java

```java
import java.util.HashMap;

class Cashier {
    private int n;
    private int discount;
    private int customerCount;
    private HashMap<Integer, Integer> pricesMap;

    public Cashier(int n, int discount, int[] products, int[] prices) {
        this.n = n;
        this.discount = discount;
        customerCount = 0;
        pricesMap = new HashMap<>();
        for (int i = 0; i < products.length; i++) {
            pricesMap.put(products[i], prices[i]);
        }
    }

    public double getBill(int[] product, int[] amount) {
        customerCount++;
        double total = 0;
        for (int i = 0; i < product.length; i++) {
            total += pricesMap.get(product[i]) * amount[i];
        }
        if (customerCount % n == 0) {
            total *= (100 - discount) / 100.0;
        }
        return total;
    }
}
```
Our algorithm maintains a customer counter which increments by 1 on each call to getBill. Since we can return the total cost only containing products and amount, we only need to maintain a map where we can look up prices of products by their id. This map can be built at the initialization of the class using the given products and prices arrays.

To calculate the total cost, traverse the given product array and multiply its price with the corresponding amount in the amount array. If the current customer is an nth customer `(customer_count % n == 0)`, we apply the discount by multiplying the total cost with `(100 - discount) / 100`. Finally, the total cost is returned.

## A solution in C++

```cpp
class Cashier {
    int n;
    int discount;
    int customer_count;
    map<int, int> prices_map;

public:
    Cashier(int n, int discount, vector<int>& products, vector<int>& prices) {
        this->n = n;
        this->discount = discount;
        customer_count = 0;
        for (int i = 0; i < products.size(); ++i) {
            prices_map[products[i]] = prices[i];
        }
    }

    double getBill(vector<int> product, vector<int> amount) {
        customer_count++;
        double total = 0;
        for (int i = 0; i < product.size(); ++i) {
            total += prices_map[product[i]] * amount[i];
        }
        if (customer_count % n == 0) {
            total *= (100 - discount) / 100.0;
        }
        return total;
    }
};
```
Our algorithm maintains a customer counter which increments by 1 on each call to getBill. Since we can return the total cost only containing products and amount, we only need to maintain a map where we can look up prices of products by their id. This map can be built at the initialization of the class using the given products and prices arrays.

To calculate the total cost, traverse the given product array and multiply its price with the corresponding amount in the amount array. If the current customer is an nth customer `(customer_count % n == 0)`, we apply the discount by multiplying the total cost with `(100 - discount) / 100`. Finally, the total cost is returned.

## A solution in Python

```python
class Cashier:

    def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
        self.n = n
        self.discount = discount
        self.customer_count = 0
        self.prices_map = {products[i]: prices[i] for i in range(len(products))}

    def getBill(self, product: List[int], amount: List[int]) -> float:
        self.customer_count += 1
        total = sum(self.prices_map[product[i]] * amount[i] for i in range(len(product)))
        if self.customer_count % self.n == 0:
            total *= (100 - self.discount) / 100
        return total
```
Our algorithm maintains a customer counter which increments by 1 on each call to getBill. Since we can return the total cost only containing products and amount, we only need to maintain a map where we can look up prices of products by their id. This map can be built at the initialization of the class using the given products and prices arrays.

To calculate the total cost, traverse the given product array and multiply its price with the corresponding amount in the amount array. If the current customer is an nth customer `(customer_count % n == 0)`, we apply the discount by multiplying the total cost with `(100 - discount) / 100`. Finally, the total cost is returned.

## A solution in Javascript

```javascript
class Cashier {
    constructor(n, discount, products, prices) {
        this.n = n;
        this.discount = discount;
        this.customerCount = 0;
        this.pricesMap = {};
        for (let i = 0; i < products.length; i++) {
            this.pricesMap[products[i]] = prices[i];
        }
    }

    getBill(product, amount) {
        this.customerCount++;
        let total = 0;
        for (let i = 0; i < product.length; i++) {
            total += this.pricesMap[product[i]] * amount[i];
        }
        if (this.customerCount % this.n === 0) {
            total *= (100 - this.discount) / 100;
        }
        return total;
    }
}
```
Our algorithm maintains a customer counter which increments by 1 on each call to getBill. Since we can return the total cost only containing products and amount, we only need to maintain a map where we can look up prices of products by their id. This map can be built at the initialization of the class using the given products and prices arrays.

To calculate the total cost, traverse the given product array and multiply its price with the corresponding amount in the amount array. If the current customer is an nth customer `(customer_count % n == 0)`, we apply the discount by multiplying the total cost with `(100 - discount) / 100`. Finally, the total cost is returned.


# Number of Substrings Containing All Three Characters

- slug: number-of-substrings-containing-all-three-characters
- difficulty: Medium

Given a string `s` consisting only of characters _a_, _b_ and _c_.

Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.

**Example 1:**

**Input:** s =  "abcabc "
**Output:** 10
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are  "_abc _",  "_abca _",  "_abcab _",  "_abcabc _",  "_bca _",  "_bcab _",  "_bcabc _",  "_cab _",  "_cabc _"_ and  _"_abc _"_ (**again**)_._

**Example 2:**

**Input:** s =  "aaacb "
**Output:** 3
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are  "_aaacb _",  "_aacb _"_ and  _"_acb _"._

**Example 3:**

**Input:** s =  "abc "
**Output:** 1

**Constraints:**

*   `3 <= s.length <= 5 x 10^4`
*   `s` only consists of _a_, _b_ or _c_ characters.

## A solution in Java

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

public List<SimpleEntry<Integer, Integer>> findPairs(int z) {
    List<SimpleEntry<Integer, Integer>> pairs = new ArrayList<>();

    int f(int x, int y) {
        return x + y;
    }

    for (int x = 1; x <= z; x++) {
        for (int y = 1; y <= z; y++) {
            if (f(x, y) == z) {
                pairs.add(new SimpleEntry<>(x, y));
            }
        }
    }
    return pairs;
}
```
The algorithm iterates through all pairs of positive integers x and y in the range (1, z), and checks whether their result when passed through the callable function f(x, y) is equal to the given value z. If the result is equal to z, the pair (x, y) is added to the list of pairs. The function returns the list of pairs that satisfy the given condition. As mentioned earlier, the actual formula for the function f(x, y) is not provided, so a simple addition formula is included for demonstration purposes. Make sure to replace it with the correct formula.

## A solution in C++

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

std::vector<std::pair<int, int>> find_pairs(int z) {
    std::vector<std::pair<int, int>> pairs;

    int f(int x, int y) {
        return x + y;
    }

    for (int x = 1; x <= z; x++) {
        for (int y = 1; y <= z; y++) {
            if (f(x, y) == z) {
                pairs.push_back(std::make_pair(x, y));
            }
        }
    }
    return pairs;
}
```
The algorithm iterates through all pairs of positive integers x and y in the range (1, z), and checks whether their result when passed through the callable function f(x, y) is equal to the given value z. If the result is equal to z, the pair (x, y) is added to the list of pairs. The function returns the list of pairs that satisfy the given condition. As mentioned earlier, the actual formula for the function f(x, y) is not provided, so a simple addition formula is included for demonstration purposes. Make sure to replace it with the correct formula.

## A solution in Python

```python
def find_pairs(z):
    pairs = []

    def f(x, y):
        return x + y

    for x in range(1, z+1):
        for y in range(1, z+1):
            if f(x, y) == z:
                pairs.append((x, y))
    return pairs
```
The algorithm iterates through all pairs of positive integers x and y in the range (1, z), and checks whether their result when passed through the callable function f(x, y) is equal to the given value z. If the result is equal to z, the pair (x, y) is added to the list of pairs. The function returns the list of pairs that satisfy the given condition. As mentioned earlier, the actual formula for the function f(x, y) is not provided, so a simple addition formula is included for demonstration purposes. Make sure to replace it with the correct formula.

## A solution in Javascript

```javascript
function findPairs(z) {
    let pairs = [];

    function f(x, y) {
        return x + y;
    }

    for (let x = 1; x <= z; x++) {
        for (let y = 1; y <= z; y++) {
            if (f(x, y) === z) {
                pairs.push([x, y]);
            }
        }
    }
    return pairs;
}
```
The algorithm iterates through all pairs of positive integers x and y in the range (1, z), and checks whether their result when passed through the callable function f(x, y) is equal to the given value z. If the result is equal to z, the pair (x, y) is added to the list of pairs. The function returns the list of pairs that satisfy the given condition. As mentioned earlier, the actual formula for the function f(x, y) is not provided, so a simple addition formula is included for demonstration purposes. Make sure to replace it with the correct formula.


# Count All Valid Pickup and Delivery Options

- slug: count-all-valid-pickup-and-delivery-options
- difficulty: Hard

Given `n` orders, each order consist in pickup and delivery services.

Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).

Since the answer may be too large, return it modulo 10^9 + 7.

**Example 1:**

**Input:** n = 1
**Output:** 1
**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1.

**Example 2:**

**Input:** n = 2
**Output:** 6
**Explanation:** All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.

**Example 3:**

**Input:** n = 3
**Output:** 90

**Constraints:**

*   `1 <= n <= 500`

Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1.

## A solution in Java

```java
import java.util.ArrayList;

public static ArrayList<Integer> circularPermutation(int n, int start) {
    ArrayList<Integer> result = new ArrayList<>(1 << n);
    for (int i = 0; i < (1 << n); ++i) {
        result.add(start ^ (i ^ (i >> 1)));
    }
    return result;
}
```
The algorithm is based on the Gray Code sequence generation, which guarantees only one bit difference between consecutive elements.

1. Initialize a list or an array called result with the size of 2^n.
2. Iterate through the range 0 to 2^n - 1.
3. For each i in the range, calculate the Gray Code with the formula `i ^ (i >> 1)`.
4. XOR the Gray Code with the given start value and store it in the result array.
5. Return the result array.

This algorithm generates a sequence that fulfills the given requirements of having a one-bit difference between consecutive elements and it starts with the provided start value.

## A solution in C++

```cpp
#include <vector>

std::vector<int> circularPermutation(int n, int start) {
    std::vector<int> result(1 << n);
    for (int i = 0; i < (1 << n); ++i) {
        result[i] = start ^ (i ^ (i >> 1));
    }
    return result;
}
```
The algorithm is based on the Gray Code sequence generation, which guarantees only one bit difference between consecutive elements.

1. Initialize a list or an array called result with the size of 2^n.
2. Iterate through the range 0 to 2^n - 1.
3. For each i in the range, calculate the Gray Code with the formula `i ^ (i >> 1)`.
4. XOR the Gray Code with the given start value and store it in the result array.
5. Return the result array.

This algorithm generates a sequence that fulfills the given requirements of having a one-bit difference between consecutive elements and it starts with the provided start value.

## A solution in Python

```python
def circular_permutation(n, start):
    result = [start ^ (i ^ (i >> 1)) for i in range(1 << n)]
    return result
```
The algorithm is based on the Gray Code sequence generation, which guarantees only one bit difference between consecutive elements.

1. Initialize a list or an array called result with the size of 2^n.
2. Iterate through the range 0 to 2^n - 1.
3. For each i in the range, calculate the Gray Code with the formula `i ^ (i >> 1)`.
4. XOR the Gray Code with the given start value and store it in the result array.
5. Return the result array.

This algorithm generates a sequence that fulfills the given requirements of having a one-bit difference between consecutive elements and it starts with the provided start value.

## A solution in Javascript

```javascript
function circularPermutation(n, start) {
    let result = new Array(1 << n);
    for (let i = 0; i < (1 << n); ++i) {
        result[i] = start ^ (i ^ (i >> 1));
    }
    return result;
}
```
The algorithm is based on the Gray Code sequence generation, which guarantees only one bit difference between consecutive elements.

1. Initialize a list or an array called result with the size of 2^n.
2. Iterate through the range 0 to 2^n - 1.
3. For each i in the range, calculate the Gray Code with the formula `i ^ (i >> 1)`.
4. XOR the Gray Code with the given start value and store it in the result array.
5. Return the result array.

This algorithm generates a sequence that fulfills the given requirements of having a one-bit difference between consecutive elements and it starts with the provided start value.


# Number of Days Between Two Dates

- slug: number-of-days-between-two-dates
- difficulty: Easy

Write a program to count the number of days between two dates.

The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples.

**Example 1:**

**Input:** date1 = "2019-06-29", date2 = "2019-06-30"
**Output:** 1

**Example 2:**

**Input:** date1 = "2020-01-15", date2 = "2019-12-31"
**Output:** 15

**Constraints:**

*   The given dates are valid dates between the years `1971` and `2100`.

## A solution in Java

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

public int maxLength(List<String> arr) {
    List<String> dp = new ArrayList<>();
    dp.add("");
    int maxLen = 0;
    for (String s : arr) {
        if (new HashSet<Character>(s.chars().mapToObj(c -> (char) c).collect(Collectors.toSet())).size() < s.length()) continue;
        for (int i = dp.size() - 1; i >= 0; --i) {
            String tmp = dp.get(i) + s;
            if (tmp.chars().distinct().count() == tmp.length()) {
                dp.add(tmp);
                maxLen = Math.max(maxLen, tmp.length());
            }
        }
    }
    return maxLen;
}
```
The algorithm initializes a list called 'dp' containing an empty string. Then, for each string s in the input array 'arr', it checks whether the string has unique characters by comparing its length with the length of a set that contains its individual characters.

If the string has unique characters, it iterates through the dp list in reverse order, forming a new string by concatenating the current string from the dp list and s. The algorithm checks if this new concatenated string has unique characters. If it does, it appends the concatenated string to the dp list and updates the maximum length of unique characters seen so far.

By the end of this process, the algorithm returns the maximum length of unique characters in a concatenated string from the subsequence of arr.

## A solution in C++

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

int maxLength(std::vector<std::string>& arr) {
    std::vector<std::string> dp = {""};

    int maxLen = 0;
    for (std::string s : arr) {
        if (std::unordered_set<char>(s.begin(), s.end()).size() < s.size()) continue;
        for (int i = dp.size() - 1; i >= 0; --i) {
            std::string tmp = dp[i] + s;
            if (std::unordered_set<char>(tmp.begin(), tmp.end()).size() == tmp.size()) {
                dp.push_back(tmp);
                maxLen = std::max(maxLen, (int)tmp.size());
            }
        }
    }

    return maxLen;
}
```
The algorithm initializes a list called 'dp' containing an empty string. Then, for each string s in the input array 'arr', it checks whether the string has unique characters by comparing its length with the length of a set that contains its individual characters.

If the string has unique characters, it iterates through the dp list in reverse order, forming a new string by concatenating the current string from the dp list and s. The algorithm checks if this new concatenated string has unique characters. If it does, it appends the concatenated string to the dp list and updates the maximum length of unique characters seen so far.

By the end of this process, the algorithm returns the maximum length of unique characters in a concatenated string from the subsequence of arr.

## A solution in Python

```python
def maxLength(arr):
    dp = ['']
    maxLen = 0

    for s in arr:
        if len(set(s)) < len(s): continue
        for i in range(len(dp) - 1, -1, -1):
            tmp = dp[i] + s
            if len(set(tmp)) == len(tmp):
                dp.append(tmp)
                maxLen = max(maxLen, len(tmp))

    return maxLen
```
The algorithm initializes a list called 'dp' containing an empty string. Then, for each string s in the input array 'arr', it checks whether the string has unique characters by comparing its length with the length of a set that contains its individual characters.

If the string has unique characters, it iterates through the dp list in reverse order, forming a new string by concatenating the current string from the dp list and s. The algorithm checks if this new concatenated string has unique characters. If it does, it appends the concatenated string to the dp list and updates the maximum length of unique characters seen so far.

By the end of this process, the algorithm returns the maximum length of unique characters in a concatenated string from the subsequence of arr.

## A solution in Javascript

```javascript
function maxLength(arr) {
    let dp = [''];
    let maxLen = 0;

    arr.forEach(s => {
        if (new Set(s).size < s.length) return;
        for (let i = dp.length - 1; i >= 0; --i) {
            let tmp = dp[i] + s;
            if (new Set(tmp).size === tmp.length) {
                dp.push(tmp);
                maxLen = Math.max(maxLen, tmp.length);
            }
        }
    });

    return maxLen;
}
```
The algorithm initializes a list called 'dp' containing an empty string. Then, for each string s in the input array 'arr', it checks whether the string has unique characters by comparing its length with the length of a set that contains its individual characters.

If the string has unique characters, it iterates through the dp list in reverse order, forming a new string by concatenating the current string from the dp list and s. The algorithm checks if this new concatenated string has unique characters. If it does, it appends the concatenated string to the dp list and updates the maximum length of unique characters seen so far.

By the end of this process, the algorithm returns the maximum length of unique characters in a concatenated string from the subsequence of arr.


# Validate Binary Tree Nodes

- slug: validate-binary-tree-nodes
- difficulty: Medium

You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.

If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child.

Note that the nodes have no values and that we only use the node numbers in this problem.

**Example 1:**

**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\]
**Output:** true

**Example 2:**

**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\]
**Output:** false

**Example 3:**

**Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\]
**Output:** false

**Constraints:**

*   `n == leftChild.length == rightChild.length`
*   `1 <= n <= 104`
*   `-1 <= leftChild[i], rightChild[i] <= n - 1`

## A solution in Java

```java
public int tilingRectangle(int n, int m) {
    if (n > m) {
        int temp = n;
        n = m;
        m = temp;
    }
    if (n == 1) return m;
    if (n == m) return 1;

    int res = Integer.MAX_VALUE;
    for (int a = 1; a <= n / 2; a++) {
        res = Math.min(res, tilingRectangle(a, m) + tilingRectangle(n - a, m));
    }
    for (int b = 1; b <= m / 2; b++) {
        res = Math.min(res, tilingRectangle(n, b) + tilingRectangle(n, m - b));
    }
    return res;
}
```
The algorithm takes a recursive approach. First, it swaps the dimensions if `n > m`, to make sure that `n` is always the smaller side. Then, it checks for base cases: if `n == 1`, return `m`, and if `n == m`, return `1`.

The next step is to find the minimum number of squares by splitting the rectangle either horizontally or vertically. The algorithm iterates over possible splits along the `n` dimension and the `m` dimension, recursively calling the same function for the newly created sub-rectangles.

Finally, the algorithm returns the minimum number of squares found by comparing these recursive results.

## A solution in C++

```cpp
int tilingRectangle(int n, int m) {
    if (n > m) std::swap(n, m);
    if (n == 1) return m;
    if (n == m) return 1;

    int res = INT_MAX;
    for (int a = 1; a <= n/2; ++a) {
        res = std::min(res, tilingRectangle(a, m) + tilingRectangle(n - a, m));
    }
    for (int b = 1; b <= m/2; ++b) {
        res = std::min(res, tilingRectangle(n, b) + tilingRectangle(n, m - b));
    }
    return res;
}
```
The algorithm takes a recursive approach. First, it swaps the dimensions if `n > m`, to make sure that `n` is always the smaller side. Then, it checks for base cases: if `n == 1`, return `m`, and if `n == m`, return `1`.

The next step is to find the minimum number of squares by splitting the rectangle either horizontally or vertically. The algorithm iterates over possible splits along the `n` dimension and the `m` dimension, recursively calling the same function for the newly created sub-rectangles.

Finally, the algorithm returns the minimum number of squares found by comparing these recursive results.

## A solution in Python

```python
def tilingRectangle(n, m):
    if n > m:
        n, m = m, n
    if n == 1:
        return m
    if n == m:
        return 1

    res = float('inf')
    for a in range(1, n // 2 + 1):
        res = min(res, tilingRectangle(a, m) + tilingRectangle(n - a, m))

    for b in range(1, m // 2 + 1):
        res = min(res, tilingRectangle(n, b) + tilingRectangle(n, m - b))

    return res
```
The algorithm takes a recursive approach. First, it swaps the dimensions if `n > m`, to make sure that `n` is always the smaller side. Then, it checks for base cases: if `n == 1`, return `m`, and if `n == m`, return `1`.

The next step is to find the minimum number of squares by splitting the rectangle either horizontally or vertically. The algorithm iterates over possible splits along the `n` dimension and the `m` dimension, recursively calling the same function for the newly created sub-rectangles.

Finally, the algorithm returns the minimum number of squares found by comparing these recursive results.

## A solution in Javascript

```javascript
function tilingRectangle(n, m) {
    if (n > m) [n, m] = [m, n];
    if (n === 1) return m;
    if (n === m) return 1;

    let res = Infinity;
    for (let a = 1; a <= Math.floor(n/2); a++) {
        res = Math.min(res, tilingRectangle(a, m) + tilingRectangle(n - a, m));
    }
    for (let b = 1; b <= Math.floor(m/2); b++) {
        res = Math.min(res, tilingRectangle(n, b) + tilingRectangle(n, m - b));
    }
    return res;
}
```
The algorithm takes a recursive approach. First, it swaps the dimensions if `n > m`, to make sure that `n` is always the smaller side. Then, it checks for base cases: if `n == 1`, return `m`, and if `n == m`, return `1`.

The next step is to find the minimum number of squares by splitting the rectangle either horizontally or vertically. The algorithm iterates over possible splits along the `n` dimension and the `m` dimension, recursively calling the same function for the newly created sub-rectangles.

Finally, the algorithm returns the minimum number of squares found by comparing these recursive results.


# Closest Divisors

- slug: closest-divisors
- difficulty: Medium

Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`.

Return the two integers in any order.

**Example 1:**

**Input:** num = 8
**Output:** \[3,3\]
**Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.

**Example 2:**

**Input:** num = 123
**Output:** \[5,25\]

**Example 3:**

**Input:** num = 999
**Output:** \[40,25\]

**Constraints:**

*   `1 <= num <= 10^9`

## A solution in Java

```java
public int[] findClosestDivisors(int num) {
    for (int i = (int)Math.sqrt(num + 2); i >= 1; i--) {
        if ((num + 1) % i == 0) return new int[]{i, (num + 1) / i};
        if ((num + 2) % i == 0) return new int[]{i, (num + 2) / i};
    }
    return new int[0];
}
```
Start by iterating through the numbers from the square root of `num+2` and checking if the current number is a divisor for `num + 1` or `num + 2`. If any divisor is found, return it along with the corresponding quotient. Starting from the square root ensures that the absolute difference is minimized.

## A solution in C++

```cpp
#include <vector>
#include <cmath>
std::vector<int> findClosestDivisors(int num) {
    for (int i = int(std::sqrt(num + 2)); i >= 1; i--) {
        if ((num + 1) % i == 0) return {i, (num + 1) / i};
        if ((num + 2) % i == 0) return {i, (num + 2) / i};
    }
    return {};
}
```
Start by iterating through the numbers from the square root of `num+2` and checking if the current number is a divisor for `num + 1` or `num + 2`. If any divisor is found, return it along with the corresponding quotient. Starting from the square root ensures that the absolute difference is minimized.

## A solution in Python

```python
def findClosestDivisors(num):
    for i in range(int((num + 2) ** 0.5), 0, -1):
        if (num + 1) % i == 0:
            return [i, (num + 1) // i]
        if (num + 2) % i == 0:
            return [i, (num + 2) // i]
    return []
```
Start by iterating through the numbers from the square root of `num+2` and checking if the current number is a divisor for `num + 1` or `num + 2`. If any divisor is found, return it along with the corresponding quotient. Starting from the square root ensures that the absolute difference is minimized.

## A solution in Javascript

```javascript
function findClosestDivisors(num) {
    for (let i = Math.floor(Math.sqrt(num + 2)); i >= 1; i--) {
        if ((num + 1) % i === 0) return [i, (num + 1) / i];
        if ((num + 2) % i === 0) return [i, (num + 2) / i];
    }
    return [];
}
```
Start by iterating through the numbers from the square root of `num+2` and checking if the current number is a divisor for `num + 1` or `num + 2`. If any divisor is found, return it along with the corresponding quotient. Starting from the square root ensures that the absolute difference is minimized.


# Largest Multiple of Three

- slug: largest-multiple-of-three
- difficulty: Hard

Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string.

Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.

**Example 1:**

**Input:** digits = \[8,1,9\]
**Output:**  "981 "

**Example 2:**

**Input:** digits = \[8,6,7,1,0\]
**Output:**  "8760 "

**Example 3:**

**Input:** digits = \[1\]
**Output:**  " "

**Constraints:**

*   `1 <= digits.length <= 104`
*   `0 <= digits[i] <= 9`

## A solution in Java

```java
import java.util.*;

public String largestMultipleOfThree(int[] digits) {
    Arrays.sort(digits);
    int sum = 0;
    for (int digit : digits) {
        sum += digit;
    }

    if (sum % 3 == 0) {
        if (digits[0] == 0) return "0";
        StringBuilder result = new StringBuilder();
        for (int i = digits.length - 1; i >= 0; --i) {
            result.append(digits[i]);
        }
        return result.toString();
    }

    List<Integer>[] mod = new List[3];
    for (int i = 0; i < 3; ++i) {
        mod[i] = new ArrayList<Integer>();
    }
    for (int digit : digits) {
        mod[digit % 3].add(digit);
    }

    if (sum % 3 == 1) {
        if (!mod[1].isEmpty()) {
            mod[1].remove(mod[1].size() - 1);
        } else {
            mod[2].remove(mod[2].size() - 1);
            mod[2].remove(mod[2].size() - 1);
        }
    } else {
        if (!mod[2].isEmpty()) {
            mod[2].remove(mod[2].size() - 1);
        } else {
            mod[1].remove(mod[1].size() - 1);
            mod[1].remove(mod[1].size() - 1);
        }
    }

    StringBuilder result = new StringBuilder();
    for (int i = 0; i < 3; ++i) {
        for (int digit : mod[i]) {
            result.append(digit);
        }
    }

    result.reverse();
    if (result.length() == 0 || result.charAt(0) == '0') {
        return "0";
    }

    return result.toString();
}
```
1. Sort the input array in descending order.
2. Calculate the sum of all digits.
3. If the sum is divisible by 3, return the joined digits as a string (or "0" if the last digit is 0).
4. Create a mod array where mod[i] contains digits with the remainder i when divided by 3.
5. If the remainder of the sum is 1:
    - Remove the smallest digit from mod[1], if not empty.
    - Otherwise, remove the two smallest digits from mod[2].
6. If the remainder of the sum is 2:
    - Remove the smallest digit from mod[2], if not empty.
    - Otherwise, remove the two smallest digits from mod[1].
7. Flatten the mod array and join its digits into a string. Sort the string in descending order.
8. Return the sorted string (or "0" if empty or starting with "0").

## A solution in C++

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

std::string largestMultipleOfThree(std::vector<int>& digits) {
    std::sort(digits.rbegin(), digits.rend());
    int sum = 0;
    for (int digit : digits) {
        sum += digit;
    }

    if (sum % 3 == 0) {
        if (digits.back() == 0) return "0";
        std::string result(digits.begin(), digits.end());
        return result;
    }

    std::vector<int> mod[3];
    for (int digit : digits) {
        mod[digit % 3].push_back(digit);
    }

    if (sum % 3 == 1) {
        if (!mod[1].empty()) {
            mod[1].pop_back();
        } else {
            mod[2].pop_back();
            mod[2].pop_back();
        }
    } else {
        if (!mod[2].empty()) {
            mod[2].pop_back();
        } else {
            mod[1].pop_back();
            mod[1].pop_back();
        }
    }

    std::string result;
    for (int i = 0; i < 3; ++i) {
        for (int digit : mod[i]) {
            result += std::to_string(digit);
        }
    }

    std::sort(result.rbegin(), result.rend());
    if (result.empty() || result[0] == '0') {
        return "0";
    }

    return result;
}
```
1. Sort the input array in descending order.
2. Calculate the sum of all digits.
3. If the sum is divisible by 3, return the joined digits as a string (or "0" if the last digit is 0).
4. Create a mod array where mod[i] contains digits with the remainder i when divided by 3.
5. If the remainder of the sum is 1:
    - Remove the smallest digit from mod[1], if not empty.
    - Otherwise, remove the two smallest digits from mod[2].
6. If the remainder of the sum is 2:
    - Remove the smallest digit from mod[2], if not empty.
    - Otherwise, remove the two smallest digits from mod[1].
7. Flatten the mod array and join its digits into a string. Sort the string in descending order.
8. Return the sorted string (or "0" if empty or starting with "0").

## A solution in Python

```python
from collections import defaultdict

def largest_multiple_of_three(digits):
    digits.sort(reverse=True)
    sum_digits = sum(digits)

    if sum_digits % 3 == 0:
        return '0' if digits[-1] == 0 else ''.join(map(str, digits))

    mod = defaultdict(list)
    for digit in digits:
        mod[digit % 3].append(digit)

    if sum_digits % 3 == 1:
        if mod[1]:
            mod[1].pop()
        else:
            mod[2].pop(), mod[2].pop()
    else:
        if mod[2]:
            mod[2].pop()
        else:
            mod[1].pop(), mod[1].pop()

    result = "".join(str(digit) for value in mod.values() for digit in value)
    result = "".join(sorted(result, reverse=True))

    return '0' if not result or result[0] == '0' else result
```
1. Sort the input array in descending order.
2. Calculate the sum of all digits.
3. If the sum is divisible by 3, return the joined digits as a string (or "0" if the last digit is 0).
4. Create a mod array where mod[i] contains digits with the remainder i when divided by 3.
5. If the remainder of the sum is 1:
    - Remove the smallest digit from mod[1], if not empty.
    - Otherwise, remove the two smallest digits from mod[2].
6. If the remainder of the sum is 2:
    - Remove the smallest digit from mod[2], if not empty.
    - Otherwise, remove the two smallest digits from mod[1].
7. Flatten the mod array and join its digits into a string. Sort the string in descending order.
8. Return the sorted string (or "0" if empty or starting with "0").

## A solution in Javascript

```javascript
function largestMultipleOfThree(digits) {
    digits.sort((a, b) => b - a);
    const sum = digits.reduce((a, b) => a + b, 0);

    if (sum % 3 === 0) {
        if (digits[digits.length - 1] === 0) return "0";
        return digits.join("");
    }

    let mod = new Array(3).fill(null).map(() => []);
    for (let digit of digits) {
        mod[digit % 3].push(digit);
    }

    if (sum % 3 === 1) {
        if (mod[1].length > 0) {
            mod[1].pop();
        } else {
            mod[2].pop(), mod[2].pop();
        }
    } else {
        if (mod[2].length > 0) {
            mod[2].pop();
        } else {
            mod[1].pop(), mod[1].pop();
        }
    }

    let result = mod.flat().join("");
    result = Array.from(result).sort((a, b) => b - a).join("");

    if (!result || result[0] === "0") {
        return "0";
    }

    return result;
}
```
1. Sort the input array in descending order.
2. Calculate the sum of all digits.
3. If the sum is divisible by 3, return the joined digits as a string (or "0" if the last digit is 0).
4. Create a mod array where mod[i] contains digits with the remainder i when divided by 3.
5. If the remainder of the sum is 1:
    - Remove the smallest digit from mod[1], if not empty.
    - Otherwise, remove the two smallest digits from mod[2].
6. If the remainder of the sum is 2:
    - Remove the smallest digit from mod[2], if not empty.
    - Otherwise, remove the two smallest digits from mod[1].
7. Flatten the mod array and join its digits into a string. Sort the string in descending order.
8. Return the sorted string (or "0" if empty or starting with "0").


# How Many Numbers Are Smaller Than the Current Number

- slug: how-many-numbers-are-smaller-than-the-current-number
- difficulty: Easy

Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`.

Return the answer in an array.

**Example 1:**

**Input:** nums = \[8,1,2,2,3\]
**Output:** \[4,0,1,1,3\]
**Explanation:**
For nums\[0\]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums\[1\]=1 does not exist any smaller number than it.
For nums\[2\]=2 there exist one smaller number than it (1).
For nums\[3\]=2 there exist one smaller number than it (1).
For nums\[4\]=3 there exist three smaller numbers than it (1, 2 and 2).

**Example 2:**

**Input:** nums = \[6,5,4,8\]
**Output:** \[2,1,0,3\]

**Example 3:**

**Input:** nums = \[7,7,7,7\]
**Output:** \[0,0,0,0\]

**Constraints:**

*   `2 <= nums.length <= 500`
*   `0 <= nums[i] <= 100`

## A solution in Java

```java
public int[] smallerNumbersThanCurrent(int[] nums) {
    int[] result = new int[nums.length];
    for (int i = 0; i < nums.length; i++) {
        int count = 0;
        for (int j = 0; j < nums.length; j++) {
            if (i != j && nums[j] < nums[i]) {
                count++;
            }
        }
        result[i] = count;
    }
    return result;
}
```
The algorithm implements a simple nested loop. For each element `nums[i]` in the input array `nums`, compare it to all other elements in the array. If any element `nums[j]` is smaller than `nums[i]` and `j` is not equal to `i`, increment a counter. After iterating through all elements, store the value of the counter in the result array at the same index as the current element `nums[i]`. Finally, return the result array.

## A solution in C++

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

vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
    vector<int> result(nums.size());
    for (int i = 0; i < nums.size(); i++) {
        int count = 0;
        for (int j = 0; j < nums.size(); j++) {
            if (i != j && nums[j] < nums[i]) {
                count++;
            }
        }
        result[i] = count;
    }
    return result;
}
```
The algorithm implements a simple nested loop. For each element `nums[i]` in the input array `nums`, compare it to all other elements in the array. If any element `nums[j]` is smaller than `nums[i]` and `j` is not equal to `i`, increment a counter. After iterating through all elements, store the value of the counter in the result array at the same index as the current element `nums[i]`. Finally, return the result array.

## A solution in Python

```python
def smallerNumbersThanCurrent(nums):
    result = []
    for i in range(len(nums)):
        count = 0
        for j in range(len(nums)):
            if i != j and nums[j] < nums[i]:
                count += 1
        result.append(count)
    return result
```
The algorithm implements a simple nested loop. For each element `nums[i]` in the input array `nums`, compare it to all other elements in the array. If any element `nums[j]` is smaller than `nums[i]` and `j` is not equal to `i`, increment a counter. After iterating through all elements, store the value of the counter in the result array at the same index as the current element `nums[i]`. Finally, return the result array.

## A solution in Javascript

```javascript
function smallerNumbersThanCurrent(nums) {
    let result = [];
    for (let i = 0; i < nums.length; i++) {
        let count = 0;
        for (let j = 0; j < nums.length; j++) {
            if (i !== j && nums[j] < nums[i]) {
                count++;
            }
        }
        result.push(count);
    }
    return result;
}
```
The algorithm implements a simple nested loop. For each element `nums[i]` in the input array `nums`, compare it to all other elements in the array. If any element `nums[j]` is smaller than `nums[i]` and `j` is not equal to `i`, increment a counter. After iterating through all elements, store the value of the counter in the result array at the same index as the current element `nums[i]`. Finally, return the result array.


# Rank Teams by Votes

- slug: rank-teams-by-votes
- difficulty: Medium

In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.

The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.

You are given an array of strings `votes` which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.

Return _a string of all teams **sorted** by the ranking system_.

**Example 1:**

**Input:** votes = \[ "ABC ", "ACB ", "ABC ", "ACB ", "ACB "\]
**Output:**  "ACB "
**Explanation:**
Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.
Team B was ranked second by 2 voters and ranked third by 3 voters.
Team C was ranked second by 3 voters and ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team, and team B is the third.

**Example 2:**

**Input:** votes = \[ "WXYZ ", "XYZW "\]
**Output:**  "XWYZ "
**Explanation:**
X is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position.

**Example 3:**

**Input:** votes = \[ "ZMNAGUEDSJYLBOPHRQICWFXTVK "\]
**Output:**  "ZMNAGUEDSJYLBOPHRQICWFXTVK "
**Explanation:** Only one voter, so their votes are used for the ranking.

**Constraints:**

*   `1 <= votes.length <= 1000`
*   `1 <= votes[i].length <= 26`
*   `votes[i].length == votes[j].length` for `0 <= i, j < votes.length`.
*   `votes[i][j]` is an English **uppercase** letter.
*   All characters of `votes[i]` are unique.
*   All the characters that occur in `votes[0]` **also occur** in `votes[j]` where `1 <= j < votes.length`.

## A solution in Java

```java
import java.util.*;

class Solution {
    public String rankTeams(String[] votes) {
        int n = votes.length, m = votes[0].length();
        int[][] count = new int[26][m];
        String res = votes[0];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                count[votes[i].charAt(j) - 'A'][j]++;
            }
        }

        Character[] chars = new Character[m];
        for (int i = 0; i < m; i++) {
            chars[i] = res.charAt(i);
        }
        Arrays.sort(chars, (a, b) -> {
            for (int i = 0; i < m; i++) {
                if (count[a - 'A'][i] != count[b - 'A'][i]) {
                    return count[b - 'A'][i] - count[a - 'A'][i];
                }
            }
            return a - b;
        });

        StringBuilder sb = new StringBuilder();
        for(char c : chars) {
            sb.append(c);
        }
        return sb.toString();
    }
}
```
1. Initialize count matrix that keeps track of the frequency of each team's position in the ranking (26 x number of teams).
2. Fill the count matrix with the frequency of each team's position in the ranking.
3. Define a comparison function that sorts teams first by frequency of their position in the ranking (in reverse order) and then, if frequency is the same, by alphabetical order.
4. Sort the first vote using the previously defined comparison function.
5. Return the sorted vote as a string.

## A solution in C++

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

std::string rankTeams(std::vector<std::string>& votes) {
    int n = votes.size(), m = votes[0].size();
    std::vector<std::vector<int>> count(26, std::vector<int>(m, 0));
    std::string res = votes[0];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            count[votes[i][j] - 'A'][j]++;
        }
    }
    std::sort(res.begin(), res.end(), [&](char a, char b) {
        for (int i = 0; i < m; i++) {
            if (count[a - 'A'][i] != count[b - 'A'][i]) {
                return count[a - 'A'][i] > count[b - 'A'][i];
            }
        }
        return a < b;
    });

    return res;
}
```
1. Initialize count matrix that keeps track of the frequency of each team's position in the ranking (26 x number of teams).
2. Fill the count matrix with the frequency of each team's position in the ranking.
3. Define a comparison function that sorts teams first by frequency of their position in the ranking (in reverse order) and then, if frequency is the same, by alphabetical order.
4. Sort the first vote using the previously defined comparison function.
5. Return the sorted vote as a string.

## A solution in Python

```python
def rankTeams(votes):
    n, m = len(votes), len(votes[0])
    count = [[0] * m for _ in range(26)]
    res = votes[0]

    for vote in votes:
        for j, team in enumerate(vote):
            count[ord(team) - ord('A')][j] += 1

    return ''.join(sorted(res, key=lambda x: (-count[ord(x) - ord('A')][:m], x)))
```
1. Initialize count matrix that keeps track of the frequency of each team's position in the ranking (26 x number of teams).
2. Fill the count matrix with the frequency of each team's position in the ranking.
3. Define a comparison function that sorts teams first by frequency of their position in the ranking (in reverse order) and then, if frequency is the same, by alphabetical order.
4. Sort the first vote using the previously defined comparison function.
5. Return the sorted vote as a string.

## A solution in Javascript

```javascript
function rankTeams(votes) {
    const n = votes.length;
    const m = votes[0].length;
    const count = Array.from({ length: 26 }, () => Array(m).fill(0));
    let res = votes[0];

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            count[votes[i].charCodeAt(j) - 'A'.charCodeAt(0)][j]++;
        }
    }

    res = res.split('').sort((a, b) => {
        for (let i = 0; i < m; i++) {
            if (count[a.charCodeAt(0) - 'A'.charCodeAt(0)][i]
                !== count[b.charCodeAt(0) - 'A'.charCodeAt(0)][i]) {
                return count[b.charCodeAt(0) - 'A'.charCodeAt(0)][i]
                    - count[a.charCodeAt(0) - 'A'.charCodeAt(0)][i];
            }
        }
        return a < b ? -1 : 1;
    });

    return res.join('');
}
```
1. Initialize count matrix that keeps track of the frequency of each team's position in the ranking (26 x number of teams).
2. Fill the count matrix with the frequency of each team's position in the ranking.
3. Define a comparison function that sorts teams first by frequency of their position in the ranking (in reverse order) and then, if frequency is the same, by alphabetical order.
4. Sort the first vote using the previously defined comparison function.
5. Return the sorted vote as a string.


# Linked List in Binary Tree

- slug: linked-list-in-binary-tree
- difficulty: Medium

Given a binary tree `root` and a linked list with `head` as the first node.

Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False.

In this context downward path means a path that starts at some node and goes downwards.

**Example 1:**

**Input:** head = \[4,2,8\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\]
**Output:** true
**Explanation:** Nodes in blue form a subpath in the binary Tree.

**Example 2:**

**Input:** head = \[1,4,2,6\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\]
**Output:** true

**Example 3:**

**Input:** head = \[1,4,2,6,8\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\]
**Output:** false
**Explanation:** There is no path in the binary tree that contains all the elements of the linked list from `head`.

**Constraints:**

*   The number of nodes in the tree will be in the range `[1, 2500]`.
*   The number of nodes in the list will be in the range `[1, 100]`.
*   `1 <= Node.val <= 100` for each node in the linked list and binary tree.

## A solution in Java

```java
import java.util.Arrays;

public int maxHeight(int[][] cuboids) {
    for (int[] cuboid : cuboids) {
        Arrays.sort(cuboid);
    }
    Arrays.sort(cuboids, (a, b) -> a[0] - b[0]);

    int n = cuboids.length;
    int[] dp = new int[n];
    int ans = 0;

    for (int i = 0; i < n; i++) {
        dp[i] = cuboids[i][2];
        for (int j = 0; j < i; j++) {
            if (cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) {
                dp[i] = Math.max(dp[i], dp[j] + cuboids[i][2]);
            }
        }
        ans = Math.max(ans, dp[i]);
    }
    return ans;
}
```
1. Sort each cuboid in non-decreasing order of its dimensions.
2. Sort the cuboids array based on width (the first dimension).
3. Use dynamic programming to calculate the maximum height at each index i, by finding the maximum height that can be achieved by placing the i-th cuboid on top of previous cuboids that can be placed at positions from 0 to i-1.
4. Update the answer by comparing the maximum height at each step with the previously computed maximum height.
5. Return the maximum height after processing all cuboids.

## A solution in C++

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

int maxHeight(std::vector<std::vector<int>>& cuboids) {
    for (auto& cuboid : cuboids)
        std::sort(cuboid.begin(), cuboid.end());

    std::sort(cuboids.begin(), cuboids.end());

    int n = cuboids.size();
    std::vector<int> dp(n);
    int ans = 0;

    for (int i = 0; i < n; i++) {
        dp[i] = cuboids[i][2];
        for (int j = 0; j < i; j++) {
            if (cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) {
                dp[i] = std::max(dp[i], dp[j] + cuboids[i][2]);
            }
        }
        ans = std::max(ans, dp[i]);
    }
    return ans;
}
```
1. Sort each cuboid in non-decreasing order of its dimensions.
2. Sort the cuboids array based on width (the first dimension).
3. Use dynamic programming to calculate the maximum height at each index i, by finding the maximum height that can be achieved by placing the i-th cuboid on top of previous cuboids that can be placed at positions from 0 to i-1.
4. Update the answer by comparing the maximum height at each step with the previously computed maximum height.
5. Return the maximum height after processing all cuboids.

## A solution in Python

```python
def maxHeight(cuboids):
    cuboids = [sorted(cuboid) for cuboid in cuboids]
    cuboids.sort()

    n = len(cuboids)
    dp = [0] * n
    ans = 0

    for i, cuboid in enumerate(cuboids):
        dp[i] = cuboid[2]
        for j in range(i):
            if all(cuboids[j][k] <= cuboid[k] for k in range(3)):
                dp[i] = max(dp[i], dp[j] + cuboid[2])

        ans = max(ans, dp[i])

    return ans
```
1. Sort each cuboid in non-decreasing order of its dimensions.
2. Sort the cuboids array based on width (the first dimension).
3. Use dynamic programming to calculate the maximum height at each index i, by finding the maximum height that can be achieved by placing the i-th cuboid on top of previous cuboids that can be placed at positions from 0 to i-1.
4. Update the answer by comparing the maximum height at each step with the previously computed maximum height.
5. Return the maximum height after processing all cuboids.

## A solution in Javascript

```javascript
function maxHeight(cuboids) {
    cuboids.forEach(cuboid => cuboid.sort((a, b) => a - b));
    cuboids.sort((a, b) => a[0] - b[0]);

    const n = cuboids.length;
    const dp = new Array(n).fill(0);
    let ans = 0;

    for (let i = 0; i < n; i++) {
        dp[i] = cuboids[i][2];
        for (let j = 0; j < i; j++) {
            if (cuboids[j][0] <= cuboids[i][0] && cuboids[j][1] <= cuboids[i][1] && cuboids[j][2] <= cuboids[i][2]) {
                dp[i] = Math.max(dp[i], dp[j] + cuboids[i][2]);
            }
        }
        ans = Math.max(ans, dp[i]);
    }
    return ans;
}
```
1. Sort each cuboid in non-decreasing order of its dimensions.
2. Sort the cuboids array based on width (the first dimension).
3. Use dynamic programming to calculate the maximum height at each index i, by finding the maximum height that can be achieved by placing the i-th cuboid on top of previous cuboids that can be placed at positions from 0 to i-1.
4. Update the answer by comparing the maximum height at each step with the previously computed maximum height.
5. Return the maximum height after processing all cuboids.


# Minimum Cost to Make at Least One Valid Path in a Grid

- slug: minimum-cost-to-make-at-least-one-valid-path-in-a-grid
- difficulty: Hard

Given an `m x n` grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be:

*   `1` which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`)
*   `2` which means go to the cell to the left. (i.e go from `grid[i][j]` to `grid[i][j - 1]`)
*   `3` which means go to the lower cell. (i.e go from `grid[i][j]` to `grid[i + 1][j]`)
*   `4` which means go to the upper cell. (i.e go from `grid[i][j]` to `grid[i - 1][j]`)

Notice that there could be some signs on the cells of the grid that point outside the grid.

You will initially start at the upper left cell `(0, 0)`. A valid path in the grid is a path that starts from the upper left cell `(0, 0)` and ends at the bottom-right cell `(m - 1, n - 1)` following the signs on the grid. The valid path does not have to be the shortest.

You can modify the sign on a cell with `cost = 1`. You can modify the sign on a cell **one time only**.

Return _the minimum cost to make the grid have at least one valid path_.

**Example 1:**

**Input:** grid = \[\[1,1,1,1\],\[2,2,2,2\],\[1,1,1,1\],\[2,2,2,2\]\]
**Output:** 3
**Explanation:** You will start at point (0, 0).
The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
The total cost = 3.

**Example 2:**

**Input:** grid = \[\[1,1,3\],\[3,2,2\],\[1,1,4\]\]
**Output:** 0
**Explanation:** You can follow the path from (0, 0) to (2, 2).

**Example 3:**

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

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 100`
*   `1 <= grid[i][j] <= 4`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int minCost(int[][] grid) {
        int m = grid.length, n = grid[0].length, cost = 0;

        int[][] visited = new int[m][n];
        for (int[] row : visited) {
            Arrays.fill(row, 1000000);
        }
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[]{0, 0});
        visited[0][0] = 0;

        while (!q.isEmpty()) {
            int[] curr = q.poll();
            int y = curr[0], x = curr[1];
            if (y == m - 1 && x == n - 1) {
                cost = visited[y][x];
                break;
            }

            int[] dx = {1, 0, -1, 0};
            int[] dy = {0, 1, 0, -1};

            for (int dir = 0; dir < 4; ++dir) {
                int newY = y + dy[dir], newX = x + dx[dir];
                if (0 <= newY && newY < m && 0 <= newX && newX < n) {
                    int newCost = visited[y][x] + (dir + 1 != grid[y][x] ? 1 : 0);
                    if (newCost < visited[newY][newX]) {
                        visited[newY][newX] = newCost;
                        q.offer(new int[]{newY, newX});
                    }
                }
            }
        }
        return cost;
    }
}
```
The algorithm performs a breadth-first search traversal based on the current grid directions. For each cell visited (starting at the upper left cell), it checks all four neighboring cells in the grid and calculates the new cost based on the direction.
If the direction required to reach the neighboring cell matches the direction in the grid, the cost remains the same, otherwise it increments by 1 (indicating that we have to modify the sign in one cell).

At each step, the BFS traversal keeps track of visited cells and their corresponding costs. When the bottom-right cell is reached, the function returns the cost of reaching it.

By using BFS, the traversal ensures that the first time the bottom-right cell is reached is with the minimum cost possible. Since it visits cells in layers, once it reaches the final cell, all cells at the same or lower cost must have already been visited, ensuring the validity of the path.

## A solution in C++

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

using namespace std;

int minCost(vector<vector<int>>& grid) {
    int m = grid.size(), n = grid[0].size(), cost = 0;

    vector<vector<int>> visited(m, vector<int>(n, 1000000));
    queue<pair<int, int>> q;
    q.push({0, 0});
    visited[0][0] = 0;

    while (!q.empty()) {
        pair<int, int> curr = q.front();
        q.pop();
        int y = curr.first, x = curr.second;
        if (y == m - 1 && x == n - 1) {
            cost = visited[y][x];
            break;
        }

        int dx[4] = {1, 0, -1, 0};
        int dy[4] = {0, 1, 0, -1};

        for (int dir = 0; dir < 4; ++dir) {
            int newY = y + dy[dir], newX = x + dx[dir];
            if (0 <= newY && newY < m && 0 <= newX && newX < n) {
                int newCost = visited[y][x] + (dir + 1 != grid[y][x]);
                if (newCost < visited[newY][newX]) {
                    visited[newY][newX] = newCost;
                    q.push({newY, newX});
                }
            }
        }
    }
    return cost;
}
```
The algorithm performs a breadth-first search traversal based on the current grid directions. For each cell visited (starting at the upper left cell), it checks all four neighboring cells in the grid and calculates the new cost based on the direction.
If the direction required to reach the neighboring cell matches the direction in the grid, the cost remains the same, otherwise it increments by 1 (indicating that we have to modify the sign in one cell).

At each step, the BFS traversal keeps track of visited cells and their corresponding costs. When the bottom-right cell is reached, the function returns the cost of reaching it.

By using BFS, the traversal ensures that the first time the bottom-right cell is reached is with the minimum cost possible. Since it visits cells in layers, once it reaches the final cell, all cells at the same or lower cost must have already been visited, ensuring the validity of the path.

## A solution in Python

```python
from collections import deque

def minCost(grid):
    m, n = len(grid), len(grid[0])
    cost = 0

    visited = [[1000000] * n for _ in range(m)]
    q = deque([(0, 0)])
    visited[0][0] = 0

    while q:
        y, x = q.popleft()
        if y == m - 1 and x == n - 1:
            cost = visited[y][x]
            break

        dx = [1, 0, -1, 0]
        dy = [0, 1, 0, -1]

        for dir in range(4):
            newY, newX = y + dy[dir], x + dx[dir]
            if 0 <= newY < m and 0 <= newX < n:
                newCost = visited[y][x] + (1 if dir + 1 != grid[y][x] else 0)
                if newCost < visited[newY][newX]:
                    visited[newY][newX] = newCost
                    q.append((newY, newX))

    return cost
```
The algorithm performs a breadth-first search traversal based on the current grid directions. For each cell visited (starting at the upper left cell), it checks all four neighboring cells in the grid and calculates the new cost based on the direction.
If the direction required to reach the neighboring cell matches the direction in the grid, the cost remains the same, otherwise it increments by 1 (indicating that we have to modify the sign in one cell).

At each step, the BFS traversal keeps track of visited cells and their corresponding costs. When the bottom-right cell is reached, the function returns the cost of reaching it.

By using BFS, the traversal ensures that the first time the bottom-right cell is reached is with the minimum cost possible. Since it visits cells in layers, once it reaches the final cell, all cells at the same or lower cost must have already been visited, ensuring the validity of the path.

## A solution in Javascript

```javascript
var minCost = function(grid) {
    let m = grid.length, n = grid[0].length, cost = 0;

    let visited = new Array(m).fill(null).map(() => new Array(n).fill(1000000));
    let q = [{i: 0, j: 0}];
    visited[0][0] = 0;

    while (q.length !== 0) {
        let {i, j} = q.shift();
        if (i === m - 1 && j === n - 1) {
            cost = visited[i][j];
            break;
        }

        let dx = [1, 0, -1, 0];
        let dy = [0, 1, 0, -1];

        for (let dir = 0; dir < 4; ++dir) {
            let newI = i + dx[dir], newJ = j + dy[dir];
            if (0 <= newI && newI < m && 0 <= newJ && newJ < n) {
                let newCost = visited[i][j] + ((dir + 1 !== grid[i][j]) ? 1 : 0);
                if (newCost < visited[newI][newJ]) {
                    visited[newI][newJ] = newCost;
                    q.push({i: newI, j: newJ});
                }
            }
        }
    }
    return cost;
};
```
The algorithm performs a breadth-first search traversal based on the current grid directions. For each cell visited (starting at the upper left cell), it checks all four neighboring cells in the grid and calculates the new cost based on the direction.
If the direction required to reach the neighboring cell matches the direction in the grid, the cost remains the same, otherwise it increments by 1 (indicating that we have to modify the sign in one cell).

At each step, the BFS traversal keeps track of visited cells and their corresponding costs. When the bottom-right cell is reached, the function returns the cost of reaching it.

By using BFS, the traversal ensures that the first time the bottom-right cell is reached is with the minimum cost possible. Since it visits cells in layers, once it reaches the final cell, all cells at the same or lower cost must have already been visited, ensuring the validity of the path.


# Increasing Decreasing String

- slug: increasing-decreasing-string
- difficulty: Easy

You are given a string `s`. Reorder the string using the following algorithm:

1.  Pick the **smallest** character from `s` and **append** it to the result.
2.  Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3.  Repeat step 2 until you cannot pick more characters.
4.  Pick the **largest** character from `s` and **append** it to the result.
5.  Pick the **largest** character from `s` which is smaller than the last appended character to the result and **append** it.
6.  Repeat step 5 until you cannot pick more characters.
7.  Repeat the steps from 1 to 6 until you pick all characters from `s`.

In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.

Return _the result string after sorting_ `s` _with this algorithm_.

**Example 1:**

**Input:** s =  "aaaabbbbcccc "
**Output:**  "abccbaabccba "
**Explanation:** After steps 1, 2 and 3 of the first iteration, result =  "abc "
After steps 4, 5 and 6 of the first iteration, result =  "abccba "
First iteration is done. Now s =  "aabbcc " and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result =  "abccbaabc "
After steps 4, 5 and 6 of the second iteration, result =  "abccbaabccba "

**Example 2:**

**Input:** s =  "rat "
**Output:**  "art "
**Explanation:** The word  "rat " becomes  "art " after re-ordering it with the mentioned algorithm.

**Constraints:**

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

## A solution in Java

```java
public int numberOfSubarrays(int[] nums, int k) {
    int n = nums.length, result = 0, count = 0;
    int[] oddCount = new int[n + 1];

    oddCount[0] = 1;
    for (int i = 0; i < n; i++) {
        count += nums[i] % 2;
        if (count >= k) result += oddCount[count - k];
        oddCount[count]++;
    }

    return result;
}
```
1. Initialize array `oddCount` with a size of `n+1` and set `oddCount[0]` to 1.
2. Initialize `count` and `result` to 0.
3. Iterate through the input array `nums`.
4. For each element, increment `count` by the value of the element modulo 2 (if the element is odd, it increments by 1, otherwise by 0).
5. If `count` is greater than or equal to `k`, increment `result` by the value of `oddCount[count - k]`.
6. Increment `oddCount[count]`.
7. After iteration, return `result` as the number of nice sub-arrays.

This algorithm works by tracking the number of odd elements within a subarray and storing the cumulative sums in the `oddCount` array. By iterating through the input array and incrementing the count, the algorithm determines whether a subarray is nice by checking if the count is greater than or equal to `k` and updating the result accordingly.

## A solution in C++

```cpp
int numberOfSubarrays(vector<int>& nums, int k) {
    int n = nums.size(), result = 0, count = 0;
    vector<int> oddCount(n + 1, 0);

    oddCount[0] = 1;
    for (int i = 0; i < n; i++) {
        count += nums[i] % 2;
        if (count >= k) result += oddCount[count - k];
        oddCount[count]++;
    }

    return result;
}
```
1. Initialize array `oddCount` with a size of `n+1` and set `oddCount[0]` to 1.
2. Initialize `count` and `result` to 0.
3. Iterate through the input array `nums`.
4. For each element, increment `count` by the value of the element modulo 2 (if the element is odd, it increments by 1, otherwise by 0).
5. If `count` is greater than or equal to `k`, increment `result` by the value of `oddCount[count - k]`.
6. Increment `oddCount[count]`.
7. After iteration, return `result` as the number of nice sub-arrays.

This algorithm works by tracking the number of odd elements within a subarray and storing the cumulative sums in the `oddCount` array. By iterating through the input array and incrementing the count, the algorithm determines whether a subarray is nice by checking if the count is greater than or equal to `k` and updating the result accordingly.

## A solution in Python

```python
def numberOfSubarrays(nums, k):
    n = len(nums)
    result = count = 0
    odd_count = [0] * (n + 1)

    odd_count[0] = 1
    for num in nums:
        count += num % 2
        if count >= k:
            result += odd_count[count - k]
        odd_count[count] += 1

    return result
```
1. Initialize array `oddCount` with a size of `n+1` and set `oddCount[0]` to 1.
2. Initialize `count` and `result` to 0.
3. Iterate through the input array `nums`.
4. For each element, increment `count` by the value of the element modulo 2 (if the element is odd, it increments by 1, otherwise by 0).
5. If `count` is greater than or equal to `k`, increment `result` by the value of `oddCount[count - k]`.
6. Increment `oddCount[count]`.
7. After iteration, return `result` as the number of nice sub-arrays.

This algorithm works by tracking the number of odd elements within a subarray and storing the cumulative sums in the `oddCount` array. By iterating through the input array and incrementing the count, the algorithm determines whether a subarray is nice by checking if the count is greater than or equal to `k` and updating the result accordingly.

## A solution in Javascript

```javascript
function numberOfSubarrays(nums, k) {
    let n = nums.length, result = 0, count = 0;
    let oddCount = new Array(n + 1).fill(0);

    oddCount[0] = 1;
    for (let i = 0; i < n; i++) {
        count += nums[i] % 2;
        if (count >= k) result += oddCount[count - k];
        oddCount[count]++;
    }

    return result;
}
```
1. Initialize array `oddCount` with a size of `n+1` and set `oddCount[0]` to 1.
2. Initialize `count` and `result` to 0.
3. Iterate through the input array `nums`.
4. For each element, increment `count` by the value of the element modulo 2 (if the element is odd, it increments by 1, otherwise by 0).
5. If `count` is greater than or equal to `k`, increment `result` by the value of `oddCount[count - k]`.
6. Increment `oddCount[count]`.
7. After iteration, return `result` as the number of nice sub-arrays.

This algorithm works by tracking the number of odd elements within a subarray and storing the cumulative sums in the `oddCount` array. By iterating through the input array and incrementing the count, the algorithm determines whether a subarray is nice by checking if the count is greater than or equal to `k` and updating the result accordingly.


# Find the Longest Substring Containing Vowels in Even Counts

- slug: find-the-longest-substring-containing-vowels-in-even-counts
- difficulty: Medium

Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.

**Example 1:**

**Input:** s =  "eleetminicoworoep "
**Output:** 13
**Explanation:** The longest substring is  "leetminicowor " which contains two each of the vowels: **e**, **i** and **o** and zero of the vowels: **a** and **u**.

**Example 2:**

**Input:** s =  "leetcodeisgreat "
**Output:** 5
**Explanation:** The longest substring is  "leetc " which contains two e's.

**Example 3:**

**Input:** s =  "bcbcbc "
**Output:** 6
**Explanation:** In this case, the given string  "bcbcbc " is the longest because all vowels: **a**, **e**, **i**, **o** and **u** appear zero times.

**Constraints:**

*   `1 <= s.length <= 5 x 10^5`
*   `s` contains only lowercase English letters.

It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.

## A solution in Java

```java
import java.util.Stack;

public String minRemoveToMakeValid(String s) {
    Stack<Integer> stk = new Stack<>();
    char[] result = s.toCharArray();

    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '(') {
            stk.push(i);
        } else if (s.charAt(i) == ')') {
            if (!stk.empty()) {
                stk.pop();
            } else {
                result[i] = '-';
            }
        }
    }

    while (!stk.empty()) {
        result[stk.pop()] = '-';
    }

    return new String(result).replace("-", "");
}
```
The algorithm uses a stack to keep track of the indexes of open parentheses. When it encounters a close parenthesis, it checks if the stack is empty or not. If it's not empty, it pops the index of the open parenthesis. If the stack is empty, it means there is no matching open parenthesis and marks the close parenthesis for removal with either an empty string (for Python and JavaScript) or a '-' character (for C++ and Java).

After iterating over the entire string, the algorithm marks any leftover open parentheses for removal by iterating over the stack. In the end, the unnecessary '-' characters or empty strings are removed or replaced to create the valid string, which is then returned.

## A solution in C++

```cpp
#include <string>
#include <stack>

std::string minRemoveToMakeValid(const std::string &s) {
    std::stack<int> stk;
    std::string result = s;

    for (int i = 0; i < s.size(); i++) {
        if (s[i] == '(') {
            stk.push(i);
        } else if (s[i] == ')') {
            if (!stk.empty()) {
                stk.pop();
            } else {
                result[i] = '-';
            }
        }
    }

    while (!stk.empty()) {
        result[stk.top()] = '-';
        stk.pop();
    }

    result.erase(std::remove(result.begin(), result.end(), '-'), result.end());
    return result;
}
```
The algorithm uses a stack to keep track of the indexes of open parentheses. When it encounters a close parenthesis, it checks if the stack is empty or not. If it's not empty, it pops the index of the open parenthesis. If the stack is empty, it means there is no matching open parenthesis and marks the close parenthesis for removal with either an empty string (for Python and JavaScript) or a '-' character (for C++ and Java).

After iterating over the entire string, the algorithm marks any leftover open parentheses for removal by iterating over the stack. In the end, the unnecessary '-' characters or empty strings are removed or replaced to create the valid string, which is then returned.

## A solution in Python

```python
def min_remove_to_make_valid(s: str) -> str:
    stk = []
    result = list(s)

    for i, ch in enumerate(s):
        if ch == '(':
            stk.append(i)
        elif ch == ')':
            if stk:
                stk.pop()
            else:
                result[i] = ''

    for i in stk:
        result[i] = ''

    return ''.join(result)
```
The algorithm uses a stack to keep track of the indexes of open parentheses. When it encounters a close parenthesis, it checks if the stack is empty or not. If it's not empty, it pops the index of the open parenthesis. If the stack is empty, it means there is no matching open parenthesis and marks the close parenthesis for removal with either an empty string (for Python and JavaScript) or a '-' character (for C++ and Java).

After iterating over the entire string, the algorithm marks any leftover open parentheses for removal by iterating over the stack. In the end, the unnecessary '-' characters or empty strings are removed or replaced to create the valid string, which is then returned.

## A solution in Javascript

```javascript
function minRemoveToMakeValid(s) {
    const stk = [];
    const result = s.split('');

    for (let i = 0; i < s.length; i++) {
        if (s[i] == '(') {
            stk.push(i);
        } else if (s[i] == ')') {
            if (stk.length > 0) {
                stk.pop();
            } else {
                result[i] = '';
            }
        }
    }

    while (stk.length > 0) {
        result[stk.pop()] = '';
    }

    return result.join('');
}
```
The algorithm uses a stack to keep track of the indexes of open parentheses. When it encounters a close parenthesis, it checks if the stack is empty or not. If it's not empty, it pops the index of the open parenthesis. If the stack is empty, it means there is no matching open parenthesis and marks the close parenthesis for removal with either an empty string (for Python and JavaScript) or a '-' character (for C++ and Java).

After iterating over the entire string, the algorithm marks any leftover open parentheses for removal by iterating over the stack. In the end, the unnecessary '-' characters or empty strings are removed or replaced to create the valid string, which is then returned.


# Longest ZigZag Path in a Binary Tree

- slug: longest-zigzag-path-in-a-binary-tree
- difficulty: Medium

You are given the `root` of a binary tree.

A ZigZag path for a binary tree is defined as follow:

*   Choose **any** node in the binary tree and a direction (right or left).
*   If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
*   Change the direction from right to left or from left to right.
*   Repeat the second and third steps until you can't move in the tree.

Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).

Return _the longest **ZigZag** path contained in that tree_.

**Example 1:**

**Input:** root = \[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1\]
**Output:** 3
**Explanation:** Longest ZigZag path in blue nodes (right -> left -> right).

**Example 2:**

**Input:** root = \[1,1,1,null,1,null,null,1,1,null,1\]
**Output:** 4
**Explanation:** Longest ZigZag path in blue nodes (left -> right -> left -> right).

**Example 3:**

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

**Constraints:**

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

## A solution in Java

```java
public class Main {
    public boolean isGoodArray(int[] nums) {
        int gcd = nums[0];
        for (int num : nums) {
            gcd = gcd(gcd, num);
            if (gcd == 1) {
                return true;
            }
        }
        return gcd == 1;
    }
    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}
```
The algorithm checks if it is possible to get a sum of 1 from the given array by using any possible subset and multiplicand. It can be achieved by finding out the greatest common divisor (GCD) among the array elements. If the GCD is 1, it means the array is good, and we return true; otherwise, we return false. For efficiency, we use __gcd() function and std namespace in C++, reduce() and gcd() function in Python, and user-defined gcd() function (recursive) in Java and JavaScript. The algorithm's complexity is O(n), where n is the number of elements in the given array.

## A solution in C++

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

bool isGoodArray(vector<int>& nums) {
    int gcd = nums[0];
    for (int num : nums) {
        gcd = __gcd(gcd, num);
        if (gcd == 1) {
            return true;
        }
    }
    return gcd == 1;
}
```
The algorithm checks if it is possible to get a sum of 1 from the given array by using any possible subset and multiplicand. It can be achieved by finding out the greatest common divisor (GCD) among the array elements. If the GCD is 1, it means the array is good, and we return true; otherwise, we return false. For efficiency, we use __gcd() function and std namespace in C++, reduce() and gcd() function in Python, and user-defined gcd() function (recursive) in Java and JavaScript. The algorithm's complexity is O(n), where n is the number of elements in the given array.

## A solution in Python

```python
from math import gcd
from functools import reduce

def is_good_array(nums):
    gcd_value = reduce(gcd, nums)
    return gcd_value == 1
```
The algorithm checks if it is possible to get a sum of 1 from the given array by using any possible subset and multiplicand. It can be achieved by finding out the greatest common divisor (GCD) among the array elements. If the GCD is 1, it means the array is good, and we return true; otherwise, we return false. For efficiency, we use __gcd() function and std namespace in C++, reduce() and gcd() function in Python, and user-defined gcd() function (recursive) in Java and JavaScript. The algorithm's complexity is O(n), where n is the number of elements in the given array.

## A solution in Javascript

```javascript
function isGoodArray(nums) {
    let gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
    let gcdValue = nums.reduce((a, b) => gcd(a, b));
    return gcdValue === 1;
}
```
The algorithm checks if it is possible to get a sum of 1 from the given array by using any possible subset and multiplicand. It can be achieved by finding out the greatest common divisor (GCD) among the array elements. If the GCD is 1, it means the array is good, and we return true; otherwise, we return false. For efficiency, we use __gcd() function and std namespace in C++, reduce() and gcd() function in Python, and user-defined gcd() function (recursive) in Java and JavaScript. The algorithm's complexity is O(n), where n is the number of elements in the given array.