# Furthest Building You Can Reach

- slug: furthest-building-you-can-reach
- difficulty: Medium

You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.

You start your journey from building `0` and move to the next building by possibly using bricks or ladders.

While moving from building `i` to building `i+1` (**0-indexed**),

*   If the current building's height is **greater than or equal** to the next building's height, you do **not** need a ladder or bricks.
*   If the current building's height is **less than** the next building's height, you can either use **one ladder** or `(h[i+1] - h[i])` **bricks**.

_Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally._

**Example 1:**

**Input:** heights = \[4,2,7,6,9,14,12\], bricks = 5, ladders = 1
**Output:** 4
**Explanation:** Starting at building 0, you can follow these steps:
- Go to building 1 without using ladders nor bricks since 4 >= 2.
- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.
- Go to building 3 without using ladders nor bricks since 7 >= 6.
- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.
It is impossible to go beyond building 4 because you do not have any more bricks or ladders.

**Example 2:**

**Input:** heights = \[4,12,2,7,3,18,20,3,19\], bricks = 10, ladders = 2
**Output:** 7

**Example 3:**

**Input:** heights = \[14,3,19,3\], bricks = 17, ladders = 0
**Output:** 3

**Constraints:**

*   `1 <= heights.length <= 105`
*   `1 <= heights[i] <= 106`
*   `0 <= bricks <= 109`
*   `0 <= ladders <= heights.length`

## A solution in Java

```java
public int maxWaterBottles(int numBottles, int numExchange) {
    int total = numBottles;
    while (numBottles >= numExchange) {
        int newBottles = numBottles / numExchange;
        total += newBottles;
        numBottles = newBottles + numBottles % numExchange;
    }
    return total;
}
```
The algorithm initializes the total number of bottles to `numBottles` (the initial number of filled bottles), then enters into a loop that continues until the number of bottles is less than the `numExchange` value. Inside the loop, we find how many new full bottles we can get by exchanging the empty bottles (`newBottles = numBottles / numExchange`), add the obtained `newBottles` to the total, and update the `numBottles` to reflect the number of new filled bottles plus the remaining empty bottles that we couldn't exchange. We repeat this process until we no longer have enough bottles to exchange. We return the `total` number of water bottles that were drank.

## A solution in C++

```cpp
int maxWaterBottles(int numBottles, int numExchange) {
    int total = numBottles;
    while (numBottles >= numExchange) {
        int newBottles = numBottles / numExchange;
        total += newBottles;
        numBottles = newBottles + numBottles % numExchange;
    }
    return total;
}
```
The algorithm initializes the total number of bottles to `numBottles` (the initial number of filled bottles), then enters into a loop that continues until the number of bottles is less than the `numExchange` value. Inside the loop, we find how many new full bottles we can get by exchanging the empty bottles (`newBottles = numBottles / numExchange`), add the obtained `newBottles` to the total, and update the `numBottles` to reflect the number of new filled bottles plus the remaining empty bottles that we couldn't exchange. We repeat this process until we no longer have enough bottles to exchange. We return the `total` number of water bottles that were drank.

## A solution in Python

```python
def maxWaterBottles(numBottles: int, numExchange: int) -> int:
    total = numBottles
    while numBottles >= numExchange:
        newBottles = numBottles // numExchange
        total += newBottles
        numBottles = newBottles + numBottles % numExchange
    return total
```
The algorithm initializes the total number of bottles to `numBottles` (the initial number of filled bottles), then enters into a loop that continues until the number of bottles is less than the `numExchange` value. Inside the loop, we find how many new full bottles we can get by exchanging the empty bottles (`newBottles = numBottles / numExchange`), add the obtained `newBottles` to the total, and update the `numBottles` to reflect the number of new filled bottles plus the remaining empty bottles that we couldn't exchange. We repeat this process until we no longer have enough bottles to exchange. We return the `total` number of water bottles that were drank.

## A solution in Javascript

```javascript
function maxWaterBottles(numBottles, numExchange) {
    let total = numBottles;
    while (numBottles >= numExchange) {
        const newBottles = Math.floor(numBottles / numExchange);
        total += newBottles;
        numBottles = newBottles + numBottles % numExchange;
    }
    return total;
}
```
The algorithm initializes the total number of bottles to `numBottles` (the initial number of filled bottles), then enters into a loop that continues until the number of bottles is less than the `numExchange` value. Inside the loop, we find how many new full bottles we can get by exchanging the empty bottles (`newBottles = numBottles / numExchange`), add the obtained `newBottles` to the total, and update the `numBottles` to reflect the number of new filled bottles plus the remaining empty bottles that we couldn't exchange. We repeat this process until we no longer have enough bottles to exchange. We return the `total` number of water bottles that were drank.


# Kth Smallest Instructions

- slug: kth-smallest-instructions
- difficulty: Hard

Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.

The **instructions** are represented as a string, where each character is either:

*   `'H'`, meaning move horizontally (go **right**), or
*   `'V'`, meaning move vertically (go **down**).

Multiple **instructions** will lead Bob to `destination`. For example, if `destination` is `(2, 3)`, both `"HHHVV "` and `"HVHVH "` are valid **instructions**.

However, Bob is very picky. Bob has a lucky number `k`, and he wants the `kth` **lexicographically smallest instructions** that will lead him to `destination`. `k` is **1-indexed**.

Given an integer array `destination` and an integer `k`, return _the_ `kth` _**lexicographically smallest instructions** that will take Bob to_ `destination`.

**Example 1:**

**Input:** destination = \[2,3\], k = 1
**Output:**  "HHHVV "
**Explanation:** All the instructions that reach (2, 3) in lexicographic order are as follows:
\[ "HHHVV ",  "HHVHV ",  "HHVVH ",  "HVHHV ",  "HVHVH ",  "HVVHH ",  "VHHHV ",  "VHHVH ",  "VHVHH ",  "VVHHH "\].

**Example 2:**

**Input:** destination = \[2,3\], k = 2
**Output:**  "HHVHV "

**Example 3:**

**Input:** destination = \[2,3\], k = 3
**Output:**  "HHVVH "

**Constraints:**

*   `destination.length == 2`
*   `1 <= row, column <= 15`
*   `1 <= k <= nCr(row + column, row)`, where `nCr(a, b)` denotes `a` choose `b`.

## A solution in Java

```java
import java.util.*;

public int[] countSubTrees(int n, int[][] edges, String labels) {
    ArrayList<ArrayList<Integer>> g = new ArrayList<>();
    for (int i = 0; i < n; ++i) g.add(new ArrayList<>());
    for (int[] edge : edges) g.get(edge[1]).add(edge[0]);
    int[] ans = new int[n];
    int[] count = new int[26];
    dfs(0, g, labels, ans, count);
    return ans;
}

private void dfs(int node, ArrayList<ArrayList<Integer>> g, String labels, int[] ans, int[] count) {
    int pre = count[labels.charAt(node) - 'a'];
    count[labels.charAt(node) - 'a']++;
    ans[node] = count[labels.charAt(node) - 'a'] - pre;
    for (int child : g.get(node)) dfs(child, g, labels, ans, count);
    count[labels.charAt(node) - 'a'] = pre;
}
```
The algorithm consists of performing a depth-first search (DFS) traversal on the given tree starting from the root node (i.e. node 0). While traversing the tree, maintain a count array to keep track of the labels of the visited nodes. When visiting a node, store the current count of the node's label and increment the count, then visit its child nodes. Calculate the answer for the current node by subtracting the previous count from the updated count. After visiting all the children of a node, restore the previous count of the node's label so that it has the correct count when visiting the siblings in the higher level of the tree traversal. Finally, return the answer vector containing the count of nodes with the same label for each node in their corresponding subtree.

## A solution in C++

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

using namespace std;

void dfs(int node, const vector<vector<int>>& g, const string& labels, vector<int>& ans, vector<int> &count) {
    int pre = count[labels[node] - 'a'];
    count[labels[node] - 'a']++;
    ans[node] = count[labels[node] - 'a'] - pre;

    for (auto child : g[node]) {
        dfs(child, g, labels, ans, count);
    }

    count[labels[node] - 'a'] = pre;
}

vector<int> countSubTrees(int n, vector<vector<int>>& edges, string labels) {
    vector<vector<int>> g(n);
    for (const auto& edge : edges) {
        g[edge[1]].push_back(edge[0]);
    }
    vector<int> ans(n);
    vector<int> count(26);
    dfs(0, g, labels, ans, count);

    return ans;
}
```
The algorithm consists of performing a depth-first search (DFS) traversal on the given tree starting from the root node (i.e. node 0). While traversing the tree, maintain a count array to keep track of the labels of the visited nodes. When visiting a node, store the current count of the node's label and increment the count, then visit its child nodes. Calculate the answer for the current node by subtracting the previous count from the updated count. After visiting all the children of a node, restore the previous count of the node's label so that it has the correct count when visiting the siblings in the higher level of the tree traversal. Finally, return the answer vector containing the count of nodes with the same label for each node in their corresponding subtree.

## A solution in Python

```python
from collections import defaultdict

def dfs(node, tree, labels, ans, count):
    prev_count = count[labels[node]]
    count[labels[node]] += 1
    ans[node] = count[labels[node]] - prev_count

    for child in tree[node]:
        dfs(child, tree, labels, ans, count)

    count[labels[node]] = prev_count

def countSubTrees(n, edges, labels):
    tree = defaultdict(list)
    for edge in edges:
        tree[edge[1]].append(edge[0])

    ans = [0] * n
    count = defaultdict(int)
    dfs(0, tree, labels, ans, count)

    return ans
```
The algorithm consists of performing a depth-first search (DFS) traversal on the given tree starting from the root node (i.e. node 0). While traversing the tree, maintain a count array to keep track of the labels of the visited nodes. When visiting a node, store the current count of the node's label and increment the count, then visit its child nodes. Calculate the answer for the current node by subtracting the previous count from the updated count. After visiting all the children of a node, restore the previous count of the node's label so that it has the correct count when visiting the siblings in the higher level of the tree traversal. Finally, return the answer vector containing the count of nodes with the same label for each node in their corresponding subtree.

## A solution in Javascript

```javascript
function dfs(node, tree, labels, ans, count) {
  const prevCount = count[labels[node]];
  count[labels[node]]++;
  ans[node] = count[labels[node]] - prevCount;

  for (const child of tree[node]) {
    dfs(child, tree, labels, ans, count);
  }

  count[labels[node]] = prevCount;
}

function countSubTrees(n, edges, labels) {
  const tree = new Array(n).fill(0).map(() => []);
  for (const edge of edges) {
    tree[edge[1]].push(edge[0]);
  }

  const ans = new Array(n).fill(0);
  const count = new Array(26).fill(0);
  dfs(0, tree, labels, ans, count);

  return ans;
}
```
The algorithm consists of performing a depth-first search (DFS) traversal on the given tree starting from the root node (i.e. node 0). While traversing the tree, maintain a count array to keep track of the labels of the visited nodes. When visiting a node, store the current count of the node's label and increment the count, then visit its child nodes. Calculate the answer for the current node by subtracting the previous count from the updated count. After visiting all the children of a node, restore the previous count of the node's label so that it has the correct count when visiting the siblings in the higher level of the tree traversal. Finally, return the answer vector containing the count of nodes with the same label for each node in their corresponding subtree.


# Lowest Common Ancestor of a Binary Tree II

- slug: lowest-common-ancestor-of-a-binary-tree-ii
- difficulty: Medium

Given the `root` of a binary tree, return _the lowest common ancestor (LCA) of two given nodes,_ `p` _and_ `q`. If either node `p` or `q` **does not exist** in the tree, return `null`. All values of the nodes in the tree are **unique**.

According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes `p` and `q` in a binary tree `T` is the lowest node that has both `p` and `q` as **descendants** (where we allow **a node to be a descendant of itself**) ". A **descendant** of a node `x` is a node `y` that is on the path from node `x` to some leaf node.

**Example 1:**

**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.

**Example 2:**

**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5. A node can be a descendant of itself according to the definition of LCA.

**Example 3:**

**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 10
**Output:** null
**Explanation:** Node 10 does not exist in the tree, so return null.

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 104]`.
*   `-109 <= Node.val <= 109`
*   All `Node.val` are **unique**.
*   `p != q`

**Follow up:** Can you find the LCA traversing the tree, without checking nodes existence?

## A solution in Java

```java
public List<String> maxNumOfSubstrings(String s) {
    int[] last = new int[26];
    Arrays.fill(last, -1);
    for (int i = 0; i < s.length(); ++i) {
        last[s.charAt(i) - 'a'] = i;
    }

    List<String> res = new ArrayList<>();
    int pre = -1, maxRight = -1;
    for (int i = 0; i < s.length(); ++i) {
        maxRight = Math.max(maxRight, last[s.charAt(i) - 'a']);
        if (maxRight == i) {
            res.add(s.substring(pre + 1, maxRight + 1));
            pre = i;
        }
    }

    return res;
}
```
1. We initialize an array `last` to store the last position of each character in string `s`.
2. We fill the array `last` by iterating over the string and updating the last index for each character.
3. We initialize an empty result array `res`, a variable `pre` to -1, and a variable `maxRight` to -1.
4. We iterate over the string, updating `maxRight` to the maximum of its current value and the last position of the current character in `s`.
5. If `maxRight` equals the current index, we add the substring from `pre + 1` to `maxRight + 1` to the result array and set `pre` to the current index.
6. After the iteration, the result array `res` contains the maximum number of non-empty substrings that meet the given conditions.

## A solution in C++

```cpp
std::vector<std::string> maxNumOfSubstrings(std::string s) {
    std::vector<int> last(26, -1);
    for (int i = 0; i < (int)s.size(); ++i) {
        last[s[i] - 'a'] = i;
    }

    std::vector<std::string> res;
    int pre = -1, maxRight = -1;
    for (int i = 0; i < (int)s.size(); ++i) {
        maxRight = std::max(maxRight, last[s[i] - 'a']);
        if (maxRight == i) {
            res.push_back(s.substr(pre + 1, maxRight - pre));
            pre = i;
        }
    }

    return res;
}
```
1. We initialize an array `last` to store the last position of each character in string `s`.
2. We fill the array `last` by iterating over the string and updating the last index for each character.
3. We initialize an empty result array `res`, a variable `pre` to -1, and a variable `maxRight` to -1.
4. We iterate over the string, updating `maxRight` to the maximum of its current value and the last position of the current character in `s`.
5. If `maxRight` equals the current index, we add the substring from `pre + 1` to `maxRight + 1` to the result array and set `pre` to the current index.
6. After the iteration, the result array `res` contains the maximum number of non-empty substrings that meet the given conditions.

## A solution in Python

```python
def max_num_of_substrings(s: str) -> List[str]:
    last = [-1] * 26
    for i, ch in enumerate(s):
        last[ord(ch) - ord('a')] = i

    res = []
    pre, max_right = -1, -1
    for i, ch in enumerate(s):
        max_right = max(max_right, last[ord(ch) - ord('a')])
        if max_right == i:
            res.append(s[pre + 1:max_right + 1])
            pre = i

    return res
```
1. We initialize an array `last` to store the last position of each character in string `s`.
2. We fill the array `last` by iterating over the string and updating the last index for each character.
3. We initialize an empty result array `res`, a variable `pre` to -1, and a variable `maxRight` to -1.
4. We iterate over the string, updating `maxRight` to the maximum of its current value and the last position of the current character in `s`.
5. If `maxRight` equals the current index, we add the substring from `pre + 1` to `maxRight + 1` to the result array and set `pre` to the current index.
6. After the iteration, the result array `res` contains the maximum number of non-empty substrings that meet the given conditions.

## A solution in Javascript

```javascript
function maxNumOfSubstrings(s) {
    const last = new Array(26).fill(-1);
    for (let i = 0; i < s.length; ++i) {
        last[s.charCodeAt(i) - 'a'.charCodeAt(0)] = i;
    }

    let res = [];
    let pre = -1;
    let maxRight = -1;
    for (let i = 0; i < s.length; ++i) {
        maxRight = Math.max(maxRight, last[s.charCodeAt(i) - 'a'.charCodeAt(0)]);
        if (maxRight === i) {
            res.push(s.substring(pre + 1, maxRight + 1));
            pre = i;
        }
    }

    return res;
}
```
1. We initialize an array `last` to store the last position of each character in string `s`.
2. We fill the array `last` by iterating over the string and updating the last index for each character.
3. We initialize an empty result array `res`, a variable `pre` to -1, and a variable `maxRight` to -1.
4. We iterate over the string, updating `maxRight` to the maximum of its current value and the last position of the current character in `s`.
5. If `maxRight` equals the current index, we add the substring from `pre + 1` to `maxRight + 1` to the result array and set `pre` to the current index.
6. After the iteration, the result array `res` contains the maximum number of non-empty substrings that meet the given conditions.


# Get Maximum in Generated Array

- slug: get-maximum-in-generated-array
- difficulty: Easy

You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way:

*   `nums[0] = 0`
*   `nums[1] = 1`
*   `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n`
*   `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n`

Return _the **maximum** integer in the array_ `nums`.

**Example 1:**

**Input:** n = 7
**Output:** 3
**Explanation:** According to the given rules:
  nums\[0\] = 0
  nums\[1\] = 1
  nums\[(1 \* 2) = 2\] = nums\[1\] = 1
  nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2
  nums\[(2 \* 2) = 4\] = nums\[2\] = 1
  nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3
  nums\[(3 \* 2) = 6\] = nums\[3\] = 2
  nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3
Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3.

**Example 2:**

**Input:** n = 2
**Output:** 1
**Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1.

**Example 3:**

**Input:** n = 3
**Output:** 2
**Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2.

**Constraints:**

*   `0 <= n <= 100`

## A solution in Java

```java
public int findKthPositive(int[] arr, int k) {
    int i = 0, num = 1;
    while (k > 0) {
        if (i < arr.length && arr[i] == num) {
            i++;
        } else {
            k--;
        }
        num++;
    }
    return num - 1;
}
```
1. Initialize two pointers `i` and `num`. `i` is used to iterate through the input array `arr`, and `num` is used to check if the integer is in the array.
2. Use a while loop that runs until `k` becomes 0. Inside the loop, we do the following:
   - Check if the current value of `num` is in the array (i.e., if `arr[i] == num`). If it is, increment `i`. This means the current value of `num` is not a missing number.
   - If the current value of `num` is not in the array, decrement `k`. This means we found one missing number.
   - Increment `num`.
3. When the loop ends, `k` becomes 0, meaning we found the kth missing number. The value of `num - 1` is the kth missing positive integer. Return this value.

## A solution in C++

```cpp
int findKthPositive(vector<int>& arr, int k) {
    int i = 0, num = 1;
    while (k > 0) {
        if (i < arr.size() && arr[i] == num) {
            i++;
        } else {
            k--;
        }
        num++;
    }
    return num - 1;
}
```
1. Initialize two pointers `i` and `num`. `i` is used to iterate through the input array `arr`, and `num` is used to check if the integer is in the array.
2. Use a while loop that runs until `k` becomes 0. Inside the loop, we do the following:
   - Check if the current value of `num` is in the array (i.e., if `arr[i] == num`). If it is, increment `i`. This means the current value of `num` is not a missing number.
   - If the current value of `num` is not in the array, decrement `k`. This means we found one missing number.
   - Increment `num`.
3. When the loop ends, `k` becomes 0, meaning we found the kth missing number. The value of `num - 1` is the kth missing positive integer. Return this value.

## A solution in Python

```python
def findKthPositive(arr, k):
    i, num = 0, 1
    while k > 0:
        if i < len(arr) and arr[i] == num:
            i += 1
        else:
            k -= 1
        num += 1
    return num - 1
```
1. Initialize two pointers `i` and `num`. `i` is used to iterate through the input array `arr`, and `num` is used to check if the integer is in the array.
2. Use a while loop that runs until `k` becomes 0. Inside the loop, we do the following:
   - Check if the current value of `num` is in the array (i.e., if `arr[i] == num`). If it is, increment `i`. This means the current value of `num` is not a missing number.
   - If the current value of `num` is not in the array, decrement `k`. This means we found one missing number.
   - Increment `num`.
3. When the loop ends, `k` becomes 0, meaning we found the kth missing number. The value of `num - 1` is the kth missing positive integer. Return this value.

## A solution in Javascript

```javascript
function findKthPositive(arr, k) {
    let i = 0, num = 1;
    while (k > 0) {
        if (i < arr.length && arr[i] === num) {
            i++;
        } else {
            k--;
        }
        num++;
    }
    return num - 1;
}
```
1. Initialize two pointers `i` and `num`. `i` is used to iterate through the input array `arr`, and `num` is used to check if the integer is in the array.
2. Use a while loop that runs until `k` becomes 0. Inside the loop, we do the following:
   - Check if the current value of `num` is in the array (i.e., if `arr[i] == num`). If it is, increment `i`. This means the current value of `num` is not a missing number.
   - If the current value of `num` is not in the array, decrement `k`. This means we found one missing number.
   - Increment `num`.
3. When the loop ends, `k` becomes 0, meaning we found the kth missing number. The value of `num - 1` is the kth missing positive integer. Return this value.


# Minimum Deletions to Make Character Frequencies Unique

- slug: minimum-deletions-to-make-character-frequencies-unique
- difficulty: Medium

A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.

Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._

The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`.

**Example 1:**

**Input:** s =  "aab "
**Output:** 0
**Explanation:** `s` is already good.

**Example 2:**

**Input:** s =  "aaabbbcc "
**Output:** 2
**Explanation:** You can delete two 'b's resulting in the good string  "aaabcc ".
Another way it to delete one 'b' and one 'c' resulting in the good string  "aaabbc ".

**Example 3:**

**Input:** s =  "ceabaacb "
**Output:** 2
**Explanation:** You can delete both 'c's resulting in the good string  "eabaab ".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).

**Constraints:**

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

## A solution in Java

```java
public boolean canConvert(String s, String t, int k) {
    int diff = 0;
    for (int i = 0; i < s.length(); i++) {
        int curr_diff = (t.charAt(i) - s.charAt(i) + 26) % 26;
        if (curr_diff > 0) {
            diff += curr_diff;
            k -= curr_diff;
        }
    }
    return k >= 0 && k >= diff - s.length() && k % 26 == 0;
}
```
For each character in string `s`, we calculate the difference with the corresponding character in string `t`. We then add that difference to the total `diff` and subtract it from `k`. If the current difference is greater than 0, it means that character has been shifted.

After every character has been checked, we need to check the following conditions:
1. `k` should be greater than or equals to 0, which means we didn't exceed the total number of moves allowed.
2. `k` should be greater than or equals to `diff` - `s.length()` to ensure that all possible shifts have been performed.
3. `k % 26` should be equal to 0, as any multiple of 26 would bring the character back to the original position, making the shifts redundant.

If all the conditions are satisfied, it's possible to convert `s` into `t` in no more than `k` moves, otherwise it's not possible.

## A solution in C++

```cpp
#include <cmath>

bool canConvert(std::string s, std::string t, int k) {
    int diff = 0;
    for (int i = 0; i < s.length(); i++) {
        int curr_diff = (t[i] - s[i] + 26) % 26;
        if (curr_diff > 0) {
            diff += curr_diff;
            k -= curr_diff;
        }
    }
    return k >= 0 && k >= diff - s.length() && k % 26 == 0;
}
```
For each character in string `s`, we calculate the difference with the corresponding character in string `t`. We then add that difference to the total `diff` and subtract it from `k`. If the current difference is greater than 0, it means that character has been shifted.

After every character has been checked, we need to check the following conditions:
1. `k` should be greater than or equals to 0, which means we didn't exceed the total number of moves allowed.
2. `k` should be greater than or equals to `diff` - `s.length()` to ensure that all possible shifts have been performed.
3. `k % 26` should be equal to 0, as any multiple of 26 would bring the character back to the original position, making the shifts redundant.

If all the conditions are satisfied, it's possible to convert `s` into `t` in no more than `k` moves, otherwise it's not possible.

## A solution in Python

```python
def can_convert(s, t, k):
    diff = 0
    for i in range(len(s)):
        curr_diff = (ord(t[i]) - ord(s[i]) + 26) % 26
        if curr_diff > 0:
            diff += curr_diff
            k -= curr_diff
    return k >= 0 and k >= diff - len(s) and k % 26 == 0
```
For each character in string `s`, we calculate the difference with the corresponding character in string `t`. We then add that difference to the total `diff` and subtract it from `k`. If the current difference is greater than 0, it means that character has been shifted.

After every character has been checked, we need to check the following conditions:
1. `k` should be greater than or equals to 0, which means we didn't exceed the total number of moves allowed.
2. `k` should be greater than or equals to `diff` - `s.length()` to ensure that all possible shifts have been performed.
3. `k % 26` should be equal to 0, as any multiple of 26 would bring the character back to the original position, making the shifts redundant.

If all the conditions are satisfied, it's possible to convert `s` into `t` in no more than `k` moves, otherwise it's not possible.

## A solution in Javascript

```javascript
function canConvert(s, t, k) {
    let diff = 0;
    for (let i = 0; i < s.length; i++) {
        let curr_diff = (t.charCodeAt(i) - s.charCodeAt(i) + 26) % 26;
        if (curr_diff > 0) {
            diff += curr_diff;
            k -= curr_diff;
        }
    }
    return k >= 0 && k >= diff - s.length && k % 26 === 0;
}
```
For each character in string `s`, we calculate the difference with the corresponding character in string `t`. We then add that difference to the total `diff` and subtract it from `k`. If the current difference is greater than 0, it means that character has been shifted.

After every character has been checked, we need to check the following conditions:
1. `k` should be greater than or equals to 0, which means we didn't exceed the total number of moves allowed.
2. `k` should be greater than or equals to `diff` - `s.length()` to ensure that all possible shifts have been performed.
3. `k % 26` should be equal to 0, as any multiple of 26 would bring the character back to the original position, making the shifts redundant.

If all the conditions are satisfied, it's possible to convert `s` into `t` in no more than `k` moves, otherwise it's not possible.


# Sell Diminishing-Valued Colored Balls

- slug: sell-diminishing-valued-colored-balls
- difficulty: Medium

You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.

The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the customer would pay `6` for the first yellow ball. After the transaction, there are only `5` yellow balls left, so the next yellow ball is then valued at `5` (i.e., the value of the balls decreases as you sell more to the customer).

You are given an integer array, `inventory`, where `inventory[i]` represents the number of balls of the `ith` color that you initially own. You are also given an integer `orders`, which represents the total number of balls that the customer wants. You can sell the balls **in any order**.

Return _the **maximum** total value that you can attain after selling_ `orders` _colored balls_. As the answer may be too large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** inventory = \[2,5\], orders = 4
**Output:** 14
**Explanation:** Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
The maximum total value is 2 + 5 + 4 + 3 = 14.

**Example 2:**

**Input:** inventory = \[3,5\], orders = 6
**Output:** 19
**Explanation:** Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.

**Constraints:**

*   `1 <= inventory.length <= 105`
*   `1 <= inventory[i] <= 109`
*   `1 <= orders <= min(sum(inventory[i]), 109)`

## A solution in Java

```java
public int minInsertions(String s) {
    int ans = 0, depth = 0;
    for (int i = 0; i < s.length(); ++i) {
        if (s.charAt(i) == '(') {
            depth += 2;
        } else {
            if (s.charAt(i - 1) == '(') {
                --depth;
            } else {
                depth -= 2;
            }
            if (depth < 0) {
                ans -= depth;
                depth = 0;
            }
        }
    }
    return ans + depth;
}
```
For this problem, the algorithm iterates through the string, keeping track of the required depth, which is initialized to 0. We use depth as an indicator of how balanced the parentheses are at each step.

When encountering an opening parenthesis '(', the depth is increased by 2. This is because, in order to balance a single '(', we need 2 closing parentheses '))'.

When encountering a closing parenthesis ')', if the previous character is an opening parenthesis '(', decrease depth by 1, because this represents a partially balanced pair. However, if the previous character is another closing parenthesis ')', we decrease depth by 2, as we have a closed pair '))'.

If at any point the depth becomes negative, we adjust the answer and depth back to 0. At the end, we return the resultant answer updated with the remaining depth.

Overall, the algorithm has a time complexity of O(n), where n is the length of the input string.

## A solution in C++

```cpp
int minInsertions(string s) {
    int ans = 0, depth = 0;
    for (int i = 0; i < s.size(); ++i) {
        if (s[i] == '(') {
            depth += 2;
        } else {
            if (s[i-1] == '(') {
                --depth;
            } else {
                depth -= 2;
            }
            if (depth < 0) {
                ans -= depth;
                depth = 0;
            }
        }
    }
    return ans + depth;
}
```
For this problem, the algorithm iterates through the string, keeping track of the required depth, which is initialized to 0. We use depth as an indicator of how balanced the parentheses are at each step.

When encountering an opening parenthesis '(', the depth is increased by 2. This is because, in order to balance a single '(', we need 2 closing parentheses '))'.

When encountering a closing parenthesis ')', if the previous character is an opening parenthesis '(', decrease depth by 1, because this represents a partially balanced pair. However, if the previous character is another closing parenthesis ')', we decrease depth by 2, as we have a closed pair '))'.

If at any point the depth becomes negative, we adjust the answer and depth back to 0. At the end, we return the resultant answer updated with the remaining depth.

Overall, the algorithm has a time complexity of O(n), where n is the length of the input string.

## A solution in Python

```python
def minInsertions(s: str) -> int:
    ans, depth = 0, 0
    for i in range(len(s)):
        if s[i] == '(':
            depth += 2
        else:
            if s[i - 1] == '(':
                depth -= 1
            else:
                depth -= 2
            if depth < 0:
                ans -= depth
                depth = 0
    return ans + depth
```
For this problem, the algorithm iterates through the string, keeping track of the required depth, which is initialized to 0. We use depth as an indicator of how balanced the parentheses are at each step.

When encountering an opening parenthesis '(', the depth is increased by 2. This is because, in order to balance a single '(', we need 2 closing parentheses '))'.

When encountering a closing parenthesis ')', if the previous character is an opening parenthesis '(', decrease depth by 1, because this represents a partially balanced pair. However, if the previous character is another closing parenthesis ')', we decrease depth by 2, as we have a closed pair '))'.

If at any point the depth becomes negative, we adjust the answer and depth back to 0. At the end, we return the resultant answer updated with the remaining depth.

Overall, the algorithm has a time complexity of O(n), where n is the length of the input string.

## A solution in Javascript

```javascript
function minInsertions(s) {
    let ans = 0, depth = 0;
    for (let i = 0; i < s.length; ++i) {
        if (s[i] === '(') {
            depth += 2;
        } else {
            if (s[i - 1] === '(') {
                --depth;
            } else {
                depth -= 2;
            }
            if (depth < 0) {
                ans -= depth;
                depth = 0;
            }
        }
    }
    return ans + depth;
}
```
For this problem, the algorithm iterates through the string, keeping track of the required depth, which is initialized to 0. We use depth as an indicator of how balanced the parentheses are at each step.

When encountering an opening parenthesis '(', the depth is increased by 2. This is because, in order to balance a single '(', we need 2 closing parentheses '))'.

When encountering a closing parenthesis ')', if the previous character is an opening parenthesis '(', decrease depth by 1, because this represents a partially balanced pair. However, if the previous character is another closing parenthesis ')', we decrease depth by 2, as we have a closed pair '))'.

If at any point the depth becomes negative, we adjust the answer and depth back to 0. At the end, we return the resultant answer updated with the remaining depth.

Overall, the algorithm has a time complexity of O(n), where n is the length of the input string.


# Create Sorted Array through Instructions

- slug: create-sorted-array-through-instructions
- difficulty: Hard

Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:

*   The number of elements currently in `nums` that are **strictly less than** `instructions[i]`.
*   The number of elements currently in `nums` that are **strictly greater than** `instructions[i]`.

For example, if inserting element `3` into `nums = [1,2,3,5]`, the **cost** of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`.

Return _the **total cost** to insert all elements from_ `instructions` _into_ `nums`. Since the answer may be large, return it **modulo** `109 + 7`

**Example 1:**

**Input:** instructions = \[1,5,6,2\]
**Output:** 1
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 5 with cost min(1, 0) = 0, now nums = \[1,5\].
Insert 6 with cost min(2, 0) = 0, now nums = \[1,5,6\].
Insert 2 with cost min(1, 2) = 1, now nums = \[1,2,5,6\].
The total cost is 0 + 0 + 0 + 1 = 1.

**Example 2:**

**Input:** instructions = \[1,2,3,6,5,4\]
**Output:** 3
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 2 with cost min(1, 0) = 0, now nums = \[1,2\].
Insert 3 with cost min(2, 0) = 0, now nums = \[1,2,3\].
Insert 6 with cost min(3, 0) = 0, now nums = \[1,2,3,6\].
Insert 5 with cost min(3, 1) = 1, now nums = \[1,2,3,5,6\].
Insert 4 with cost min(3, 2) = 2, now nums = \[1,2,3,4,5,6\].
The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.

**Example 3:**

**Input:** instructions = \[1,3,3,3,2,4,2,1,2\]
**Output:** 4
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3,3\].
Insert 2 with cost min(1, 3) = 1, now nums = \[1,2,3,3,3\].
Insert 4 with cost min(5, 0) = 0, now nums = \[1,2,3,3,3,4\].
Insert 2 with cost min(1, 4) = 1, now nums = \[1,2,2,3,3,3,4\].
Insert 1 with cost min(0, 6) = 0, now nums = \[1,1,2,2,3,3,3,4\].
Insert 2 with cost min(2, 4) = 2, now nums = \[1,1,2,2,2,3,3,3,4\].
The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.

**Constraints:**

*   `1 <= instructions.length <= 105`
*   `1 <= instructions[i] <= 105`

## A solution in Java

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

public int maxNonOverlapping(int[] nums, int target) {
    int sum = 0, count = 0;
    Map<Integer, Integer> map = new HashMap<>();
    map.put(0, 1);
    for (int num : nums) {
        sum += num;
        if (map.containsKey(sum - target)) {
            count++;
            map.clear();
            map.put(0, 1);
            sum = 0;
        } else {
            map.put(sum, map.getOrDefault(sum, 0) + 1);
        }
    }
    return count;
}
```
The algorithm uses a hashMap to store the prefix_sum values that have been seen so far.
1. Initialize a hashMap with key-value pair {0: 1} since there is always an empty subarray whose sum is 0.
2. Iterate through the nums array, for each element, update the sum_so_far value by adding the current element.
3. At each step, check if the hashMap contains any key which is equal to the (sum_so_far - target). If yes, we have found a non-overlapping subarray with the sum equal to the target, so increment the count and reset the hashMap by retaining the initial key-value pair {0: 1}.
4. If there is no such key available in the hashMap, add the current sum in hashMap with key equal to the current sum_so_far and add 1 to its value.
5. Return the count at the end of iteration.

## A solution in C++

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

int maxNonOverlapping(std::vector<int>& nums, int target) {
    int sum = 0, count = 0;
    std::unordered_map<int, int> umap;
    umap[0] = 1;
    for (int num : nums) {
        sum += num;
        if (umap[sum - target]) {
            count++;
            umap.clear();
            umap[0] = 1;
            sum = 0;
        } else {
            umap[sum]++;
        }
    }
    return count;
}
```
The algorithm uses a hashMap to store the prefix_sum values that have been seen so far.
1. Initialize a hashMap with key-value pair {0: 1} since there is always an empty subarray whose sum is 0.
2. Iterate through the nums array, for each element, update the sum_so_far value by adding the current element.
3. At each step, check if the hashMap contains any key which is equal to the (sum_so_far - target). If yes, we have found a non-overlapping subarray with the sum equal to the target, so increment the count and reset the hashMap by retaining the initial key-value pair {0: 1}.
4. If there is no such key available in the hashMap, add the current sum in hashMap with key equal to the current sum_so_far and add 1 to its value.
5. Return the count at the end of iteration.

## A solution in Python

```python
def maxNonOverlapping(nums, target):
    prefix_sum = {0: 1}
    sum_so_far = count = 0
    for num in nums:
        sum_so_far += num
        if sum_so_far - target in prefix_sum:
            count += 1
            prefix_sum.clear()
            prefix_sum[0] = 1
            sum_so_far = 0
        else:
            prefix_sum[sum_so_far] = prefix_sum.get(sum_so_far, 0) + 1
    return count
```
The algorithm uses a hashMap to store the prefix_sum values that have been seen so far.
1. Initialize a hashMap with key-value pair {0: 1} since there is always an empty subarray whose sum is 0.
2. Iterate through the nums array, for each element, update the sum_so_far value by adding the current element.
3. At each step, check if the hashMap contains any key which is equal to the (sum_so_far - target). If yes, we have found a non-overlapping subarray with the sum equal to the target, so increment the count and reset the hashMap by retaining the initial key-value pair {0: 1}.
4. If there is no such key available in the hashMap, add the current sum in hashMap with key equal to the current sum_so_far and add 1 to its value.
5. Return the count at the end of iteration.

## A solution in Javascript

```javascript
function maxNonOverlapping(nums, target) {
    let prefixSum = {};
    let sumSoFar = 0;
    let count = 0;
    prefixSum[0] = 1;
    for (const num of nums) {
        sumSoFar += num;
        if (prefixSum.hasOwnProperty(sumSoFar - target)) {
            count++;
            prefixSum = {};
            prefixSum[0] = 1;
            sumSoFar = 0;
        } else {
            if (!prefixSum.hasOwnProperty(sumSoFar)) {
                prefixSum[sumSoFar] = 0;
            }
            prefixSum[sumSoFar]++;
        }
    }
    return count;
}
```
The algorithm uses a hashMap to store the prefix_sum values that have been seen so far.
1. Initialize a hashMap with key-value pair {0: 1} since there is always an empty subarray whose sum is 0.
2. Iterate through the nums array, for each element, update the sum_so_far value by adding the current element.
3. At each step, check if the hashMap contains any key which is equal to the (sum_so_far - target). If yes, we have found a non-overlapping subarray with the sum equal to the target, so increment the count and reset the hashMap by retaining the initial key-value pair {0: 1}.
4. If there is no such key available in the hashMap, add the current sum in hashMap with key equal to the current sum_so_far and add 1 to its value.
5. Return the count at the end of iteration.


# Lowest Common Ancestor of a Binary Tree III

- slug: lowest-common-ancestor-of-a-binary-tree-iii
- difficulty: Medium

Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_.

Each node will have a reference to its parent node. The definition for `Node` is below:

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
}

According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow **a node to be a descendant of itself**). "

**Example 1:**

**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.

**Example 2:**

**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition.

**Example 3:**

**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1

**Constraints:**

*   The number of nodes in the tree is in the range `[2, 105]`.
*   `-109 <= Node.val <= 109`
*   All `Node.val` are **unique**.
*   `p != q`
*   `p` and `q` exist in the tree.

## A solution in Java

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

public Node lowestCommonAncestor(Node p, Node q) {
    Node a = p;
    Node b = q;
    while (a != b) {
        a = a.parent != null ? a.parent : q;
        b = b.parent != null ? b.parent : p;
    }
    return a;
}
```
We initialize two pointers, `a` and `b`, to be the input nodes `p` and `q`. Then, we run a while loop which terminates when `a` and `b` meet. In each iteration, we move `a` to its parent if it exists, otherwise we move it to node `q`. Similarly, we move `b` to its parent if it exists, otherwise we move it to node `p`.

Since we are traversing each node's ancestors and switching to the other node's ancestors, eventually `a` and `b` will meet at the lowest common ancestor of the two input nodes. This method ensures that we cover nodes up the tree and helps find the LCA in O(h) time, where h is the height of the tree.

## A solution in C++

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

Node* lowestCommonAncestor(Node* p, Node* q) {
    Node* a = p;
    Node* b = q;
    while (a != b) {
        a = a->parent ? a->parent : q;
        b = b->parent ? b->parent : p;
    }
    return a;
}
```
We initialize two pointers, `a` and `b`, to be the input nodes `p` and `q`. Then, we run a while loop which terminates when `a` and `b` meet. In each iteration, we move `a` to its parent if it exists, otherwise we move it to node `q`. Similarly, we move `b` to its parent if it exists, otherwise we move it to node `p`.

Since we are traversing each node's ancestors and switching to the other node's ancestors, eventually `a` and `b` will meet at the lowest common ancestor of the two input nodes. This method ensures that we cover nodes up the tree and helps find the LCA in O(h) time, where h is the height of the tree.

## A solution in Python

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

def lowest_common_ancestor(p, q):
    a, b = p, q
    while a != b:
        a = a.parent if a.parent else q
        b = b.parent if b.parent else p
    return a
```
We initialize two pointers, `a` and `b`, to be the input nodes `p` and `q`. Then, we run a while loop which terminates when `a` and `b` meet. In each iteration, we move `a` to its parent if it exists, otherwise we move it to node `q`. Similarly, we move `b` to its parent if it exists, otherwise we move it to node `p`.

Since we are traversing each node's ancestors and switching to the other node's ancestors, eventually `a` and `b` will meet at the lowest common ancestor of the two input nodes. This method ensures that we cover nodes up the tree and helps find the LCA in O(h) time, where h is the height of the tree.

## A solution in Javascript

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

function lowestCommonAncestor(p, q) {
    let a = p;
    let b = q;
    while (a !== b) {
        a = a.parent ? a.parent : q;
        b = b.parent ? b.parent : p;
    }
    return a;
}
```
We initialize two pointers, `a` and `b`, to be the input nodes `p` and `q`. Then, we run a while loop which terminates when `a` and `b` meet. In each iteration, we move `a` to its parent if it exists, otherwise we move it to node `q`. Similarly, we move `b` to its parent if it exists, otherwise we move it to node `p`.

Since we are traversing each node's ancestors and switching to the other node's ancestors, eventually `a` and `b` will meet at the lowest common ancestor of the two input nodes. This method ensures that we cover nodes up the tree and helps find the LCA in O(h) time, where h is the height of the tree.


# Defuse the Bomb

- slug: defuse-the-bomb
- difficulty: Easy

You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.

To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.

*   If `k > 0`, replace the `ith` number with the sum of the **next** `k` numbers.
*   If `k < 0`, replace the `ith` number with the sum of the **previous** `k` numbers.
*   If `k == 0`, replace the `ith` number with `0`.

As `code` is circular, the next element of `code[n-1]` is `code[0]`, and the previous element of `code[0]` is `code[n-1]`.

Given the **circular** array `code` and an integer key `k`, return _the decrypted code to defuse the bomb_!

**Example 1:**

**Input:** code = \[5,7,1,4\], k = 3
**Output:** \[12,10,16,13\]
**Explanation:** Each number is replaced by the sum of the next 3 numbers. The decrypted code is \[7+1+4, 1+4+5, 4+5+7, 5+7+1\]. Notice that the numbers wrap around.

**Example 2:**

**Input:** code = \[1,2,3,4\], k = 0
**Output:** \[0,0,0,0\]
**Explanation:** When k is zero, the numbers are replaced by 0.

**Example 3:**

**Input:** code = \[2,4,9,3\], k = -2
**Output:** \[12,5,6,13\]
**Explanation:** The decrypted code is \[3+9, 2+3, 4+2, 9+4\]. Notice that the numbers wrap around again. If k is negative, the sum is of the **previous** numbers.

**Constraints:**

*   `n == code.length`
*   `1 <= n <= 100`
*   `1 <= code[i] <= 100`
*   `-(n - 1) <= k <= n - 1`

## A solution in Java

```java
public int minOperations(String target) {
    int operations = 0;
    char current_bit = '0';
    for (char bit : target.toCharArray()) {
        if (bit != current_bit) {
            operations++;
            current_bit = bit;
        }
    }
    return operations;
}
```
The algorithm iterates through the target binary string, keeping track of the current bit. Whenever it encounters a bit in the target string that is different from the current one, it increments the operation counter and updates the current bit. By following this approach, we ensure that we only need to flip bits when necessary, resulting in the minimum number of operations.

## A solution in C++

```cpp
int minOperations(string target) {
    int operations = 0;
    char current_bit = '0';
    for (char bit : target) {
        if (bit != current_bit) {
            operations++;
            current_bit = bit;
        }
    }
    return operations;
}
```
The algorithm iterates through the target binary string, keeping track of the current bit. Whenever it encounters a bit in the target string that is different from the current one, it increments the operation counter and updates the current bit. By following this approach, we ensure that we only need to flip bits when necessary, resulting in the minimum number of operations.

## A solution in Python

```python
def minOperations(target: str) -> int:
    operations = 0
    current_bit = '0'
    for bit in target:
        if bit != current_bit:
            operations += 1
            current_bit = bit
    return operations
```
The algorithm iterates through the target binary string, keeping track of the current bit. Whenever it encounters a bit in the target string that is different from the current one, it increments the operation counter and updates the current bit. By following this approach, we ensure that we only need to flip bits when necessary, resulting in the minimum number of operations.

## A solution in Javascript

```javascript
function minOperations(target) {
    let operations = 0;
    let current_bit = '0';
    for (let bit of target) {
        if (bit !== current_bit) {
            operations++;
            current_bit = bit;
        }
    }
    return operations;
}
```
The algorithm iterates through the target binary string, keeping track of the current bit. Whenever it encounters a bit in the target string that is different from the current one, it increments the operation counter and updates the current bit. By following this approach, we ensure that we only need to flip bits when necessary, resulting in the minimum number of operations.


# Minimum Deletions to Make String Balanced

- slug: minimum-deletions-to-make-string-balanced
- difficulty: Medium

You are given a string `s` consisting only of characters `'a'` and `'b'`.

You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.

Return _the **minimum** number of deletions needed to make_ `s` _**balanced**_.

**Example 1:**

**Input:** s =  "aababbab "
**Output:** 2
**Explanation:** You can either:
Delete the characters at 0-indexed positions 2 and 6 ( "aababbab " ->  "aaabbb "), or
Delete the characters at 0-indexed positions 3 and 6 ( "aababbab " ->  "aabbbb ").

**Example 2:**

**Input:** s =  "bbaaaaabb "
**Output:** 2
**Explanation:** The only solution is to delete the first two characters.

**Constraints:**

*   `1 <= s.length <= 105`
*   `s[i]` is `'a'` or `'b'`.

## A solution in Java

```java
public int dfs(TreeNode root, int distance, List<Integer> depths) {
    if (root == null) return 0;
    if (root.left == null && root.right == null) {
        depths.add(0);
        return 1;
    }
    List<Integer> left = new ArrayList<>(), right = new ArrayList<>();
    int count = dfs(root.left, distance, left) + dfs(root.right, distance, right);
    for (int l : left) {
        for (int r : right) {
            if (l + r + 2 <= distance) count++;
        }
    }
    for (int l : left) depths.add(l + 1);
    for (int r : right) depths.add(r + 1);
    return count;
}

public int countPairs(TreeNode root, int distance) {
    List<Integer> depths = new ArrayList<>();
    return dfs(root, distance, depths);
}
```
We use a Depth First Search (DFS) based algorithm to calculate the number of good leaf node pairs in the binary tree. Start by defining the DFS helper function that takes the root, distance, and depths (list to store depths).

1. If the root does not exist, return 0.
2. If both the left and right children of the root do not exist, then it is a leaf node. Append 0 to the depths list and return 1.
3. Create left and right lists for storing depths from left and right subtrees respectively.
4. Calculate count by recursively calling the dfs() function for left and right subtrees.
5. Now, iterate through each of the left and right lists to calculate the number of good leaf node pairs.
6. If the sum of two values (l and r) from the depths list plus 2 is less than or equal to the distance, increment the count.
7. Update the depths list by increasing the depth of left and right lists elements by 1.
8. Return the total count.
9. In the main function (countPairs), initialize an empty depths list and call the dfs() function. Return the number of good leaf node pairs.

## A solution in C++

```cpp
int dfs(TreeNode* root, int distance, vector<int>& depths) {
    if (!root) return 0;
    if (!root->left && !root->right) {
        depths.push_back(0);
        return 1;
    }
    vector<int> left, right;
    int count = dfs(root->left, distance, left) + dfs(root->right, distance, right);
    for (int l : left) {
        for (int r : right) {
            if (l + r + 2 <= distance) count++;
        }
    }
    for (int l : left) depths.push_back(l + 1);
    for (int r : right) depths.push_back(r + 1);
    return count;
}

int countPairs(TreeNode* root, int distance) {
    vector<int> depths;
    return dfs(root, distance, depths);
}
```
We use a Depth First Search (DFS) based algorithm to calculate the number of good leaf node pairs in the binary tree. Start by defining the DFS helper function that takes the root, distance, and depths (list to store depths).

1. If the root does not exist, return 0.
2. If both the left and right children of the root do not exist, then it is a leaf node. Append 0 to the depths list and return 1.
3. Create left and right lists for storing depths from left and right subtrees respectively.
4. Calculate count by recursively calling the dfs() function for left and right subtrees.
5. Now, iterate through each of the left and right lists to calculate the number of good leaf node pairs.
6. If the sum of two values (l and r) from the depths list plus 2 is less than or equal to the distance, increment the count.
7. Update the depths list by increasing the depth of left and right lists elements by 1.
8. Return the total count.
9. In the main function (countPairs), initialize an empty depths list and call the dfs() function. Return the number of good leaf node pairs.

## A solution in Python

```python
def dfs(root, distance, depths):
    if not root:
        return 0
    if not root.left and not root.right:
        depths.append(0)
        return 1
    left, right = [], []
    count = dfs(root.left, distance, left) + dfs(root.right, distance, right)
    for l in left:
        for r in right:
            if l + r + 2 <= distance:
                count += 1
    depths.extend(l + 1 for l in left)
    depths.extend(r + 1 for r in right)
    return count

def countPairs(root, distance):
    depths = []
    return dfs(root, distance, depths)
```
We use a Depth First Search (DFS) based algorithm to calculate the number of good leaf node pairs in the binary tree. Start by defining the DFS helper function that takes the root, distance, and depths (list to store depths).

1. If the root does not exist, return 0.
2. If both the left and right children of the root do not exist, then it is a leaf node. Append 0 to the depths list and return 1.
3. Create left and right lists for storing depths from left and right subtrees respectively.
4. Calculate count by recursively calling the dfs() function for left and right subtrees.
5. Now, iterate through each of the left and right lists to calculate the number of good leaf node pairs.
6. If the sum of two values (l and r) from the depths list plus 2 is less than or equal to the distance, increment the count.
7. Update the depths list by increasing the depth of left and right lists elements by 1.
8. Return the total count.
9. In the main function (countPairs), initialize an empty depths list and call the dfs() function. Return the number of good leaf node pairs.

## A solution in Javascript

```javascript
function dfs(root, distance, depths) {
    if (!root) return 0;
    if (!root.left && !root.right) {
        depths.push(0);
        return 1;
    }
    let left = [], right = [];
    let count = dfs(root.left, distance, left) + dfs(root.right, distance, right);
    for (let l of left) {
        for (let r of right) {
            if (l + r + 2 <= distance) count++;
        }
    }
    depths.push(...left.map(l => l + 1), ...right.map(r => r + 1));
    return count;
}

function countPairs(root, distance) {
    let depths = [];
    return dfs(root, distance, depths);
}
```
We use a Depth First Search (DFS) based algorithm to calculate the number of good leaf node pairs in the binary tree. Start by defining the DFS helper function that takes the root, distance, and depths (list to store depths).

1. If the root does not exist, return 0.
2. If both the left and right children of the root do not exist, then it is a leaf node. Append 0 to the depths list and return 1.
3. Create left and right lists for storing depths from left and right subtrees respectively.
4. Calculate count by recursively calling the dfs() function for left and right subtrees.
5. Now, iterate through each of the left and right lists to calculate the number of good leaf node pairs.
6. If the sum of two values (l and r) from the depths list plus 2 is less than or equal to the distance, increment the count.
7. Update the depths list by increasing the depth of left and right lists elements by 1.
8. Return the total count.
9. In the main function (countPairs), initialize an empty depths list and call the dfs() function. Return the number of good leaf node pairs.


# Minimum Jumps to Reach Home

- slug: minimum-jumps-to-reach-home
- difficulty: Medium

A certain bug's home is on the x-axis at position `x`. Help them get there from position `0`.

The bug jumps according to the following rules:

*   It can jump exactly `a` positions **forward** (to the right).
*   It can jump exactly `b` positions **backward** (to the left).
*   It cannot jump backward twice in a row.
*   It cannot jump to any `forbidden` positions.

The bug may jump forward **beyond** its home, but it **cannot jump** to positions numbered with **negative** integers.

Given an array of integers `forbidden`, where `forbidden[i]` means that the bug cannot jump to the position `forbidden[i]`, and integers `a`, `b`, and `x`, return _the minimum number of jumps needed for the bug to reach its home_. If there is no possible sequence of jumps that lands the bug on position `x`, return `-1.`

**Example 1:**

**Input:** forbidden = \[14,4,18,1,15\], a = 3, b = 15, x = 9
**Output:** 3
**Explanation:** 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.

**Example 2:**

**Input:** forbidden = \[8,3,16,6,12,20\], a = 15, b = 13, x = 11
**Output:** -1

**Example 3:**

**Input:** forbidden = \[1,6,2,14,5,17,4\], a = 16, b = 9, x = 7
**Output:** 2
**Explanation:** One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.

**Constraints:**

*   `1 <= forbidden.length <= 1000`
*   `1 <= a, b, forbidden[i] <= 2000`
*   `0 <= x <= 2000`
*   All the elements in `forbidden` are distinct.
*   Position `x` is not forbidden.

## A solution in Java

```java
import java.util.*;

public int minimumJumps(int[] forbidden, int a, int b, int x) {
    Set<Integer> forbidden_positions = new HashSet<>();
    for (int f : forbidden) {
        forbidden_positions.add(f);
    }
    Queue<int[]> q = new LinkedList<>();
    q.add(new int[]{0, 0, 0});
    Set<String> visited = new HashSet<>();
    visited.add("0,0");
    while (!q.isEmpty()) {
        int[] curr = q.poll();
        int pos = curr[0];
        int steps = curr[1];
        int backward = curr[2];
        if (pos == x) return steps;
        int forward_pos = pos + a;
        int backward_pos = pos - b;
        if (forward_pos <= 6000 && !forbidden_positions.contains(forward_pos) && !visited.contains(forward_pos + ",0")) {
            visited.add(forward_pos + ",0");
            q.add(new int[]{forward_pos, steps + 1, 0});
        }
        if (backward == 0 && backward_pos > 0 && !forbidden_positions.contains(backward_pos) && !visited.contains(backward_pos + ",1")) {
            visited.add(backward_pos + ",1");
            q.add(new int[]{backward_pos, steps + 1, 1});
        }
    }
    return -1;
}
```
The algorithm uses a BFS approach to find the minimum number of jumps needed for the bug to reach its home. We start with position 0 and initialize a queue with that position, steps taken, and the backward status. We then perform BFS while maintaining visited positions with their backward status (either 0 or 1) to avoid revisiting the same position.

At each step, we calculate the next forward and backward positions if they aren't forbidden or out of range (<= 6000 for forward and > 0 for backward). We update the visited set and add the new positions to the queue with the updated step count and backward status.

The bug needs to follow the rules of not jumping backwards twice in a row and not jumping to forbidden positions. By checking if the current backward status is 0 before adding the backward position, we ensure we don't jump backwards twice in a row. The forbidden set ensures we don't jump to any forbidden positions.

If a position is reached where it equals `x`, return the number of steps taken to reach that position. If the queue becomes empty, it means there are no valid moves that land the bug on position `x`, so return -1.

## A solution in C++

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

int minimumJumps(std::vector<int>& forbidden, int a, int b, int x) {
    std::set<std::pair<int, int>> visited;
    std::set<int> forbidden_positions(forbidden.begin(), forbidden.end());
    std::queue<std::pair<int, std::pair<int, int>>> q;
    q.push({0, {0, 0}});
    visited.insert({0, 0});
    while (!q.empty()) {
        auto [pos, step_status] = q.front(); q.pop();
        int steps = step_status.first;
        int backward = step_status.second;
        if (pos == x) return steps;
        int forward_pos = pos + a;
        int backward_pos = pos - b;
        if (forward_pos <= 6000 && !forbidden_positions.count(forward_pos) && !visited.count({forward_pos, 0})) {
            visited.insert({forward_pos, 0});
            q.push({forward_pos, {steps + 1, 0}});
        }
        if (backward == 0 && backward_pos > 0 && !forbidden_positions.count(backward_pos) && !visited.count({backward_pos, 1})) {
            visited.insert({backward_pos, 1});
            q.push({backward_pos, {steps + 1, 1}});
        }
    }
    return -1;
}
```
The algorithm uses a BFS approach to find the minimum number of jumps needed for the bug to reach its home. We start with position 0 and initialize a queue with that position, steps taken, and the backward status. We then perform BFS while maintaining visited positions with their backward status (either 0 or 1) to avoid revisiting the same position.

At each step, we calculate the next forward and backward positions if they aren't forbidden or out of range (<= 6000 for forward and > 0 for backward). We update the visited set and add the new positions to the queue with the updated step count and backward status.

The bug needs to follow the rules of not jumping backwards twice in a row and not jumping to forbidden positions. By checking if the current backward status is 0 before adding the backward position, we ensure we don't jump backwards twice in a row. The forbidden set ensures we don't jump to any forbidden positions.

If a position is reached where it equals `x`, return the number of steps taken to reach that position. If the queue becomes empty, it means there are no valid moves that land the bug on position `x`, so return -1.

## A solution in Python

```python
from collections import deque

def minimumJumps(forbidden, a, b, x):
    forbidden_positions = set(forbidden)
    q = deque([(0, 0, 0)])
    visited = {(0, 0)}
    while q:
        pos, steps, backward = q.popleft()
        if pos == x:
            return steps
        forward_pos = pos + a
        backward_pos = pos - b
        if forward_pos <= 6000 and forward_pos not in forbidden_positions and (forward_pos, 0) not in visited:
            visited.add((forward_pos, 0))
            q.append((forward_pos, steps + 1, 0))
        if backward == 0 and backward_pos > 0 and backward_pos not in forbidden_positions and (backward_pos, 1) not in visited:
            visited.add((backward_pos, 1))
            q.append((backward_pos, steps + 1, 1))
    return -1
```
The algorithm uses a BFS approach to find the minimum number of jumps needed for the bug to reach its home. We start with position 0 and initialize a queue with that position, steps taken, and the backward status. We then perform BFS while maintaining visited positions with their backward status (either 0 or 1) to avoid revisiting the same position.

At each step, we calculate the next forward and backward positions if they aren't forbidden or out of range (<= 6000 for forward and > 0 for backward). We update the visited set and add the new positions to the queue with the updated step count and backward status.

The bug needs to follow the rules of not jumping backwards twice in a row and not jumping to forbidden positions. By checking if the current backward status is 0 before adding the backward position, we ensure we don't jump backwards twice in a row. The forbidden set ensures we don't jump to any forbidden positions.

If a position is reached where it equals `x`, return the number of steps taken to reach that position. If the queue becomes empty, it means there are no valid moves that land the bug on position `x`, so return -1.

## A solution in Javascript

```javascript
function minimumJumps(forbidden, a, b, x) {
    const forbidden_positions = new Set(forbidden);
    const q = [[0, 0, 0]];
    const visited = new Set(['0,0']);
    while (q.length) {
        const [pos, steps, backward] = q.shift();
        if (pos === x) return steps;
        const forward_pos = pos + a;
        const backward_pos = pos - b;
        if (forward_pos <= 6000 && !forbidden_positions.has(forward_pos) && !visited.has(`${forward_pos},0`)) {
            visited.add(`${forward_pos},0`);
            q.push([forward_pos, steps + 1, 0]);
        }
        if (backward === 0 && backward_pos > 0 && !forbidden_positions.has(backward_pos) && !visited.has(`${backward_pos},1`)) {
            visited.add(`${backward_pos},1`);
            q.push([backward_pos, steps + 1, 1]);
        }
    }
    return -1;
}
```
The algorithm uses a BFS approach to find the minimum number of jumps needed for the bug to reach its home. We start with position 0 and initialize a queue with that position, steps taken, and the backward status. We then perform BFS while maintaining visited positions with their backward status (either 0 or 1) to avoid revisiting the same position.

At each step, we calculate the next forward and backward positions if they aren't forbidden or out of range (<= 6000 for forward and > 0 for backward). We update the visited set and add the new positions to the queue with the updated step count and backward status.

The bug needs to follow the rules of not jumping backwards twice in a row and not jumping to forbidden positions. By checking if the current backward status is 0 before adding the backward position, we ensure we don't jump backwards twice in a row. The forbidden set ensures we don't jump to any forbidden positions.

If a position is reached where it equals `x`, return the number of steps taken to reach that position. If the queue becomes empty, it means there are no valid moves that land the bug on position `x`, so return -1.


# Distribute Repeating Integers

- slug: distribute-repeating-integers
- difficulty: Hard

You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:

*   The `ith` customer gets **exactly** `quantity[i]` integers,
*   The integers the `ith` customer gets are **all equal**, and
*   Every customer is satisfied.

Return `true` _if it is possible to distribute_ `nums` _according to the above conditions_.

**Example 1:**

**Input:** nums = \[1,2,3,4\], quantity = \[2\]
**Output:** false
**Explanation:** The 0th customer cannot be given two different integers.

**Example 2:**

**Input:** nums = \[1,2,3,3\], quantity = \[2\]
**Output:** true
**Explanation:** The 0th customer is given \[3,3\]. The integers \[1,2\] are not used.

**Example 3:**

**Input:** nums = \[1,1,2,2\], quantity = \[2,2\]
**Output:** true
**Explanation:** The 0th customer is given \[1,1\], and the 1st customer is given \[2,2\].

**Constraints:**

*   `n == nums.length`
*   `1 <= n <= 105`
*   `1 <= nums[i] <= 1000`
*   `m == quantity.length`
*   `1 <= m <= 10`
*   `1 <= quantity[i] <= 105`
*   There are at most `50` unique values in `nums`.

## A solution in Java

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

public boolean canDistribute(int[] nums, int[] quantity) {
    Map<Integer, Integer> counts = new HashMap<>();
    for (int num : nums) {
        counts.put(num, counts.getOrDefault(num, 0) + 1);
    }

    List<Integer> values = new ArrayList<>(counts.values());
    Integer[] quantityArray = new Integer[quantity.length];
    for (int i = 0; i < quantity.length; i++) {
        quantityArray[i] = quantity[i];
    }
    Arrays.sort(quantityArray, Collections.reverseOrder());

    return dfs(0, values, quantityArray);
}

private boolean dfs(int index, List<Integer> values, Integer[] quantityArray) {
    if (index == quantityArray.length) {
        return true;
    }
    for (int i = 0; i < values.size(); i++) {
        if (values.get(i) >= quantityArray[index]) {
            values.set(i, values.get(i) - quantityArray[index]);
            if (dfs(index + 1, values, quantityArray)) return true;
            values.set(i, values.get(i) + quantityArray[index]);
        }
    }
    return false;
}
```
The algorithm first calculates the frequency count of each unique number in the input `nums` and store the counts in a list/array `values`. Then it sorts the `quantity` in decreasing order so that we try to satisfy the customers with the largest order first.

The main part of the algorithm is the `dfs` function. It performs a depth first search on the counts (in `values`), trying to satisfy each customer in order as given in the `quantity` array. It backtracks when it is not possible to satisfy a customer with the remaining counts. The base case is when all the customers have been satisfied. In this case, the function returns `true`. If we cannot satisfy any customer, the function returns `false`.

Finally, the main function `canDistribute` returns the result of the `dfs` function starting from the first customer.

The algorithm works for any of the four languages: C++, Java, Python, or JavaScript.

## A solution in C++

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

bool canDistribute(std::vector<int>& nums, std::vector<int>& quantity) {
    std::unordered_map<int, int> counts;
    for (int num : nums) {
        counts[num]++;
    }

    std::vector<int> values;
    for (auto& p : counts) {
        values.push_back(p.second);
    }

    std::sort(quantity.begin(), quantity.end(), std::greater<int>());

    function<bool(int, vector<int>&)> dfs = [&](int index, vector<int>& values) {
        if (index == quantity.size()) {
            return true;
        }
        for (int i = 0; i < values.size(); ++i) {
            if (values[i] >= quantity[index]) {
                values[i] -= quantity[index];
                if (dfs(index + 1, values)) return true;
                values[i] += quantity[index];
            }
        }
        return false;
    };

    return dfs(0, values);
}
```
The algorithm first calculates the frequency count of each unique number in the input `nums` and store the counts in a list/array `values`. Then it sorts the `quantity` in decreasing order so that we try to satisfy the customers with the largest order first.

The main part of the algorithm is the `dfs` function. It performs a depth first search on the counts (in `values`), trying to satisfy each customer in order as given in the `quantity` array. It backtracks when it is not possible to satisfy a customer with the remaining counts. The base case is when all the customers have been satisfied. In this case, the function returns `true`. If we cannot satisfy any customer, the function returns `false`.

Finally, the main function `canDistribute` returns the result of the `dfs` function starting from the first customer.

The algorithm works for any of the four languages: C++, Java, Python, or JavaScript.

## A solution in Python

```python
from collections import Counter

def canDistribute(nums, quantity):
    counts = Counter(nums)
    values = list(counts.values())
    quantity.sort(reverse=True)

    def dfs(index, values):
        if index == len(quantity):
            return True
        for i in range(len(values)):
            if values[i] >= quantity[index]:
                values[i] -= quantity[index]
                if dfs(index + 1, values):
                    return True
                values[i] += quantity[index]
        return False

    return dfs(0, values)
```
The algorithm first calculates the frequency count of each unique number in the input `nums` and store the counts in a list/array `values`. Then it sorts the `quantity` in decreasing order so that we try to satisfy the customers with the largest order first.

The main part of the algorithm is the `dfs` function. It performs a depth first search on the counts (in `values`), trying to satisfy each customer in order as given in the `quantity` array. It backtracks when it is not possible to satisfy a customer with the remaining counts. The base case is when all the customers have been satisfied. In this case, the function returns `true`. If we cannot satisfy any customer, the function returns `false`.

Finally, the main function `canDistribute` returns the result of the `dfs` function starting from the first customer.

The algorithm works for any of the four languages: C++, Java, Python, or JavaScript.

## A solution in Javascript

```javascript
function canDistribute(nums, quantity) {
    const counts = new Map();
    for (const num of nums) {
        counts.set(num, (counts.get(num) || 0) + 1);
    }

    const values = Array.from(counts.values());
    quantity.sort((a, b) => b - a);

    function dfs(index, values) {
        if (index === quantity.length) {
            return true;
        }
        for (let i = 0; i < values.length; i++) {
            if (values[i] >= quantity[index]) {
                values[i] -= quantity[index];
                if (dfs(index + 1, values)) return true;
                values[i] += quantity[index];
            }
        }
        return false;
    }

    return dfs(0, values);
}
```
The algorithm first calculates the frequency count of each unique number in the input `nums` and store the counts in a list/array `values`. Then it sorts the `quantity` in decreasing order so that we try to satisfy the customers with the largest order first.

The main part of the algorithm is the `dfs` function. It performs a depth first search on the counts (in `values`), trying to satisfy each customer in order as given in the `quantity` array. It backtracks when it is not possible to satisfy a customer with the remaining counts. The base case is when all the customers have been satisfied. In this case, the function returns `true`. If we cannot satisfy any customer, the function returns `false`.

Finally, the main function `canDistribute` returns the result of the `dfs` function starting from the first customer.

The algorithm works for any of the four languages: C++, Java, Python, or JavaScript.


# Design an Ordered Stream

- slug: design-an-ordered-stream
- difficulty: Easy

There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.

Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each insertion. The concatenation of all the **chunks** should result in a list of the sorted values.

Implement the `OrderedStream` class:

*   `OrderedStream(int n)` Constructs the stream to take `n` values.
*   `String[] insert(int idKey, String value)` Inserts the pair `(idKey, value)` into the stream, then returns the **largest possible chunk** of currently inserted values that appear next in the order.

**Example:**

**Input**
\[ "OrderedStream ",  "insert ",  "insert ",  "insert ",  "insert ",  "insert "\]
\[\[5\], \[3,  "ccccc "\], \[1,  "aaaaa "\], \[2,  "bbbbb "\], \[5,  "eeeee "\], \[4,  "ddddd "\]\]
**Output**
\[null, \[\], \[ "aaaaa "\], \[ "bbbbb ",  "ccccc "\], \[\], \[ "ddddd ",  "eeeee "\]\]

**Explanation**
// Note that the values ordered by ID is \[ "aaaaa ",  "bbbbb ",  "ccccc ",  "ddddd ",  "eeeee "\].
OrderedStream os = new OrderedStream(5);
os.insert(3,  "ccccc "); // Inserts (3,  "ccccc "), returns \[\].
os.insert(1,  "aaaaa "); // Inserts (1,  "aaaaa "), returns \[ "aaaaa "\].
os.insert(2,  "bbbbb "); // Inserts (2,  "bbbbb "), returns \[ "bbbbb ",  "ccccc "\].
os.insert(5,  "eeeee "); // Inserts (5,  "eeeee "), returns \[\].
os.insert(4,  "ddddd "); // Inserts (4,  "ddddd "), returns \[ "ddddd ",  "eeeee "\].
// Concatentating all the chunks returned:
// \[\] + \[ "aaaaa "\] + \[ "bbbbb ",  "ccccc "\] + \[\] + \[ "ddddd ",  "eeeee "\] = \[ "aaaaa ",  "bbbbb ",  "ccccc ",  "ddddd ",  "eeeee "\]
// The resulting order is the same as the order above.

**Constraints:**

*   `1 <= n <= 1000`
*   `1 <= id <= n`
*   `value.length == 5`
*   `value` consists only of lowercase letters.
*   Each call to `insert` will have a unique `id.`
*   Exactly `n` calls will be made to `insert`.

## A solution in Java

```java
int countGoodTriplets(int[] arr, int a, int b, int c) {
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            if (Math.abs(arr[i] - arr[j]) <= a) {
                for (int k = j + 1; k < arr.length; k++) {
                    if (Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) {
                        count++;
                    }
                }
            }
        }
    }
    return count;
}
```
The algorithm iterates through the array with three nested loops. The outer loop iterates through all the elements in the array with index i. The second loop starts from i+1 and goes till the last element in the array with index j. The third loop starts from j+1 and iterates till the last element in the array with index k.

Inside the innermost loop, we check if the absolute difference between arr[i] and arr[j] is less than or equal to a. If it is, proceed to calculate the absolute difference between arr[j] and arr[k] and check if it is less than or equal to b, as well as the absolute difference between arr[i] and arr[k] to check if it is less than or equal to c. If all three conditions are true, increment the count by 1.

Return the count after all nested loops are completed.

## A solution in C++

```cpp
int countGoodTriplets(vector<int>& arr, int a, int b, int c) {
    int count = 0;
    for (int i = 0; i < arr.size(); i++) {
        for (int j = i + 1; j < arr.size(); j++) {
            if (abs(arr[i] - arr[j]) <= a) {
                for (int k = j + 1; k < arr.size(); k++) {
                    if (abs(arr[j] - arr[k]) <= b && abs(arr[i] - arr[k]) <= c) {
                        count++;
                    }
                }
            }
        }
    }
    return count;
}
```
The algorithm iterates through the array with three nested loops. The outer loop iterates through all the elements in the array with index i. The second loop starts from i+1 and goes till the last element in the array with index j. The third loop starts from j+1 and iterates till the last element in the array with index k.

Inside the innermost loop, we check if the absolute difference between arr[i] and arr[j] is less than or equal to a. If it is, proceed to calculate the absolute difference between arr[j] and arr[k] and check if it is less than or equal to b, as well as the absolute difference between arr[i] and arr[k] to check if it is less than or equal to c. If all three conditions are true, increment the count by 1.

Return the count after all nested loops are completed.

## A solution in Python

```python
def count_good_triplets(arr, a, b, c):
    count = 0
    for i in range(len(arr)):
        for j in range(i+1, len(arr)):
            if abs(arr[i] - arr[j]) <= a:
                for k in range(j+1, len(arr)):
                    if abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
                        count += 1
    return count
```
The algorithm iterates through the array with three nested loops. The outer loop iterates through all the elements in the array with index i. The second loop starts from i+1 and goes till the last element in the array with index j. The third loop starts from j+1 and iterates till the last element in the array with index k.

Inside the innermost loop, we check if the absolute difference between arr[i] and arr[j] is less than or equal to a. If it is, proceed to calculate the absolute difference between arr[j] and arr[k] and check if it is less than or equal to b, as well as the absolute difference between arr[i] and arr[k] to check if it is less than or equal to c. If all three conditions are true, increment the count by 1.

Return the count after all nested loops are completed.

## A solution in Javascript

```javascript
function countGoodTriplets(arr, a, b, c) {
    let count = 0;
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (Math.abs(arr[i] - arr[j]) <= a) {
                for (let k = j + 1; k < arr.length; k++) {
                    if (Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) {
                        count++;
                    }
                }
            }
        }
    }
    return count;
}
```
The algorithm iterates through the array with three nested loops. The outer loop iterates through all the elements in the array with index i. The second loop starts from i+1 and goes till the last element in the array with index j. The third loop starts from j+1 and iterates till the last element in the array with index k.

Inside the innermost loop, we check if the absolute difference between arr[i] and arr[j] is less than or equal to a. If it is, proceed to calculate the absolute difference between arr[j] and arr[k] and check if it is less than or equal to b, as well as the absolute difference between arr[i] and arr[k] to check if it is less than or equal to c. If all three conditions are true, increment the count by 1.

Return the count after all nested loops are completed.


# Determine if Two Strings Are Close

- slug: determine-if-two-strings-are-close
- difficulty: Medium

Two strings are considered **close** if you can attain one from the other using the following operations:

*   Operation 1: Swap any two **existing** characters.
    *   For example, `abcde -> aecdb`
*   Operation 2: Transform **every** occurrence of one **existing** character into another **existing** character, and do the same with the other character.
    *   For example, `aacabb -> bbcbaa` (all `a`'s turn into `b`'s, and all `b`'s turn into `a`'s)

You can use the operations on either string as many times as necessary.

Given two strings, `word1` and `word2`, return `true` _if_ `word1` _and_ `word2` _are **close**, and_ `false` _otherwise._

**Example 1:**

**Input:** word1 =  "abc ", word2 =  "bca "
**Output:** true
**Explanation:** You can attain word2 from word1 in 2 operations.
Apply Operation 1:  "abc " ->  "acb "
Apply Operation 1:  "acb " ->  "bca "

**Example 2:**

**Input:** word1 =  "a ", word2 =  "aa "
**Output:** false
**Explanation:** It is impossible to attain word2 from word1, or vice versa, in any number of operations.

**Example 3:**

**Input:** word1 =  "cabbba ", word2 =  "abbccc "
**Output:** true
**Explanation:** You can attain word2 from word1 in 3 operations.
Apply Operation 1:  "cabbba " ->  "caabbb "
`Apply Operation 2:  "`caabbb " ->  "baaccc "
Apply Operation 2:  "baaccc " ->  "abbccc "

**Constraints:**

*   `1 <= word1.length, word2.length <= 105`
*   `word1` and `word2` contain only lowercase English letters.

## A solution in Java

```java
public int getWinner(int[] arr, int k) {
    int winner = arr[0];
    int consecutiveWins = 0;

    for (int i = 1; i < arr.length; i++) {
        if (arr[i] > winner) {
            winner = arr[i];
            consecutiveWins = 0;
        }
        if (++consecutiveWins == k) {
            break;
        }
    }
    return winner;
}
```
1. Initialize the winner variable with the first element of the array and set consecutive wins to zero.
2. Iterate through the array starting from the second element.
3. Compare the current element with the winner. If the current element is larger, update the winner and reset consecutive wins to zero.
4. Increment consecutive wins. If consecutive wins is equal to k, break the loop.
5. Return the winner.

## A solution in C++

```cpp
int getWinner(vector<int>& arr, int k) {
    int winner = arr[0];
    int consecutive_wins = 0;

    for (int i = 1; i < arr.size(); ++i) {
        if (arr[i] > winner) {
            winner = arr[i];
            consecutive_wins = 0;
        }
        if (++consecutive_wins == k) {
            break;
        }
    }
    return winner;
}
```
1. Initialize the winner variable with the first element of the array and set consecutive wins to zero.
2. Iterate through the array starting from the second element.
3. Compare the current element with the winner. If the current element is larger, update the winner and reset consecutive wins to zero.
4. Increment consecutive wins. If consecutive wins is equal to k, break the loop.
5. Return the winner.

## A solution in Python

```python
def get_winner(arr, k):
    winner = arr[0]
    consecutive_wins = 0

    for i in range(1, len(arr)):
        if arr[i] > winner:
            winner = arr[i];
            consecutive_wins = 0

        consecutive_wins += 1
        if consecutive_wins == k:
            break

    return winner
```
1. Initialize the winner variable with the first element of the array and set consecutive wins to zero.
2. Iterate through the array starting from the second element.
3. Compare the current element with the winner. If the current element is larger, update the winner and reset consecutive wins to zero.
4. Increment consecutive wins. If consecutive wins is equal to k, break the loop.
5. Return the winner.

## A solution in Javascript

```javascript
function getWinner(arr, k) {
    let winner = arr[0];
    let consecutiveWins = 0;

    for (let i = 1; i < arr.length; i++) {
        if (arr[i] > winner) {
            winner = arr[i];
            consecutiveWins = 0;
        }
        if (++consecutiveWins === k) {
            break;
        }
    }
    return winner;
}
```
1. Initialize the winner variable with the first element of the array and set consecutive wins to zero.
2. Iterate through the array starting from the second element.
3. Compare the current element with the winner. If the current element is larger, update the winner and reset consecutive wins to zero.
4. Increment consecutive wins. If consecutive wins is equal to k, break the loop.
5. Return the winner.


# Minimum Operations to Reduce X to Zero

- slug: minimum-operations-to-reduce-x-to-zero
- difficulty: Medium

You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations.

Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`.

**Example 1:**

**Input:** nums = \[1,1,4,2,3\], x = 5
**Output:** 2
**Explanation:** The optimal solution is to remove the last two elements to reduce x to zero.

**Example 2:**

**Input:** nums = \[5,6,7,8,9\], x = 4
**Output:** -1

**Example 3:**

**Input:** nums = \[3,2,20,1,1,3\], x = 10
**Output:** 5
**Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `1 <= nums[i] <= 104`
*   `1 <= x <= 109`

## A solution in Java

```java
public int minSwaps(int[][] grid) {
    int n = grid.length;
    int[] row_zeros = new int[n];

    for (int i = 0; i < n; i++) {
        for (int j = n - 1; j >= 0; j--) {
            if (grid[i][j] == 0) {
                row_zeros[i]++;
            } else {
                break;
            }
        }
    }

    int steps = 0;
    for (int i = 0; i < n; i++) {
        int target = n - i - 1;
        int current_row = i;
        while (current_row < n && row_zeros[current_row] < target) {
            current_row++;
        }
        if (current_row == n) {
            return -1;
        }
        steps += current_row - i;
        int temp = row_zeros[current_row];
        System.arraycopy(row_zeros, i, row_zeros, i + 1, current_row - i);
        row_zeros[i] = temp;
    }

    return steps;
}
```
1. Iterate each row and count the number of trailing zeros (zeros from right to left) in each row.
2. Initialize the steps count to 0.
3. For each required zero count starting from `n-1` to 1, try to find a row in the remaining rows with at least the required number of zeros.
   - If found, increment the steps with the distance of that row from the target position and swap the row with the target position.
   - If not found, it's impossible to form a valid grid, so return -1.
4. Return the total steps.

## A solution in C++

```cpp
int minSwaps(std::vector<std::vector<int>>& grid) {
    int n = grid.size();
    std::vector<int> row_zeros(n, 0);

    for (int i = 0; i < n; ++i) {
        for (int j = n - 1; j >= 0; --j) {
            if (grid[i][j] == 0) {
                row_zeros[i]++;
            } else {
                break;
            }
        }
    }

    int steps = 0;
    for (int i = 0; i < n; ++i) {
        int target = n - i - 1;
        int current_row = i;
        while (current_row < n && row_zeros[current_row] < target) {
            current_row++;
        }
        if (current_row == n) {
            return -1;
        }
        steps += current_row - i;
        row_zeros.erase(row_zeros.begin() + current_row);
        row_zeros.insert(row_zeros.begin() + i, target);
    }
    return steps;
}
```
1. Iterate each row and count the number of trailing zeros (zeros from right to left) in each row.
2. Initialize the steps count to 0.
3. For each required zero count starting from `n-1` to 1, try to find a row in the remaining rows with at least the required number of zeros.
   - If found, increment the steps with the distance of that row from the target position and swap the row with the target position.
   - If not found, it's impossible to form a valid grid, so return -1.
4. Return the total steps.

## A solution in Python

```python
def min_swaps(grid):
    n = len(grid)
    row_zeros = [0] * n

    for i in range(n):
        for j in range(n - 1, -1, -1):
            if grid[i][j] == 0:
                row_zeros[i] += 1
            else:
                break

    steps = 0
    for i in range(n):
        target = n - i - 1
        current_row = i
        while current_row < n and row_zeros[current_row] < target:
            current_row += 1
        if current_row == n:
            return -1
        steps += current_row - i
        row_zeros.pop(current_row)
        row_zeros.insert(i, target)

    return steps
```
1. Iterate each row and count the number of trailing zeros (zeros from right to left) in each row.
2. Initialize the steps count to 0.
3. For each required zero count starting from `n-1` to 1, try to find a row in the remaining rows with at least the required number of zeros.
   - If found, increment the steps with the distance of that row from the target position and swap the row with the target position.
   - If not found, it's impossible to form a valid grid, so return -1.
4. Return the total steps.

## A solution in Javascript

```javascript
function minSwaps(grid) {
    const n = grid.length;
    const row_zeros = new Array(n).fill(0);

    for (let i = 0; i < n; i++) {
        for (let j = n - 1; j >= 0; j--) {
            if (grid[i][j] === 0) {
                row_zeros[i]++;
            } else {
                break;
            }
        }
    }

    let steps = 0;
    for (let i = 0; i < n; i++) {
        const target = n - i - 1;
        let current_row = i;
        while (current_row < n && row_zeros[current_row] < target) {
            current_row++;
        }
        if (current_row === n) {
            return -1;
        }
        steps += current_row - i;
        row_zeros.splice(current_row, 1);
        row_zeros.splice(i, 0, target);
    }

    return steps;
}
```
1. Iterate each row and count the number of trailing zeros (zeros from right to left) in each row.
2. Initialize the steps count to 0.
3. For each required zero count starting from `n-1` to 1, try to find a row in the remaining rows with at least the required number of zeros.
   - If found, increment the steps with the distance of that row from the target position and swap the row with the target position.
   - If not found, it's impossible to form a valid grid, so return -1.
4. Return the total steps.