# Number of Good Ways to Split a String

- slug: number-of-good-ways-to-split-a-string
- difficulty: Medium

You are given a string `s`.

A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.

Return _the number of **good splits** you can make in `s`_.

**Example 1:**

**Input:** s =  "aacaba "
**Output:** 2
**Explanation:** There are 5 ways to split ` "aacaba "` and 2 of them are good.
( "a ",  "acaba ") Left string and right string contains 1 and 3 different letters respectively.
( "aa ",  "caba ") Left string and right string contains 1 and 3 different letters respectively.
( "aac ",  "aba ") Left string and right string contains 2 and 2 different letters respectively (good split).
( "aaca ",  "ba ") Left string and right string contains 2 and 2 different letters respectively (good split).
( "aacab ",  "a ") Left string and right string contains 3 and 1 different letters respectively.

**Example 2:**

**Input:** s =  "abcd "
**Output:** 1
**Explanation:** Split the string as follows ( "ab ",  "cd ").

**Constraints:**

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

## A solution in Java

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

public List<Integer> processQueries(int[] queries, int m) {
    List<Integer> nums = new ArrayList<>();
    List<Integer> result = new ArrayList<>();
    for (int i = 0; i < m; i++) {
        nums.add(i + 1);
    }
    for (int q : queries) {
        int pos = nums.indexOf(q);
        result.add(pos);
        nums.remove(pos);
        nums.add(0, q);
    }
    return result;
}
```
The algorithm starts by initializing a list `nums` of values from 1 to `m` and an empty result list.

For each query `q` in the queries list:
1. Find the position `pos` of `q` in the `nums` list.
2. Add `pos` to the result list.
3. Remove `q` from its current position in the `nums` list.
4. Insert `q` at the beginning of the `nums` list.

Finally, return the result list.

## A solution in C++

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

std::vector<int> processQueries(std::vector<int> &queries, int m) {
    std::vector<int> nums(m), result;
    for (int i = 0; i < m; ++i) {
        nums[i] = i + 1;
    }
    for (int q : queries) {
        int pos = std::find(nums.begin(), nums.end(), q) - nums.begin();
        result.push_back(pos);
        nums.erase(nums.begin() + pos);
        nums.insert(nums.begin(), q);
    }
    return result;
}
```
The algorithm starts by initializing a list `nums` of values from 1 to `m` and an empty result list.

For each query `q` in the queries list:
1. Find the position `pos` of `q` in the `nums` list.
2. Add `pos` to the result list.
3. Remove `q` from its current position in the `nums` list.
4. Insert `q` at the beginning of the `nums` list.

Finally, return the result list.

## A solution in Python

```python
def process_queries(queries, m):
    nums = list(range(1, m+1))
    result = []
    for q in queries:
        pos = nums.index(q)
        result.append(pos)
        del nums[pos]
        nums.insert(0, q)
    return result
```
The algorithm starts by initializing a list `nums` of values from 1 to `m` and an empty result list.

For each query `q` in the queries list:
1. Find the position `pos` of `q` in the `nums` list.
2. Add `pos` to the result list.
3. Remove `q` from its current position in the `nums` list.
4. Insert `q` at the beginning of the `nums` list.

Finally, return the result list.

## A solution in Javascript

```javascript
function processQueries(queries, m) {
    const nums = Array.from({ length: m }, (_, i) => i + 1);
    const result = [];
    for (const q of queries) {
        const pos = nums.indexOf(q);
        result.push(pos);
        nums.splice(pos, 1);
        nums.unshift(q);
    }
    return result;
}
```
The algorithm starts by initializing a list `nums` of values from 1 to `m` and an empty result list.

For each query `q` in the queries list:
1. Find the position `pos` of `q` in the `nums` list.
2. Add `pos` to the result list.
3. Remove `q` from its current position in the `nums` list.
4. Insert `q` at the beginning of the `nums` list.

Finally, return the result list.


# Minimum Number of Increments on Subarrays to Form a Target Array

- slug: minimum-number-of-increments-on-subarrays-to-form-a-target-array
- difficulty: Hard

You are given an integer array `target`. You have an integer array `initial` of the same size as `target` with all elements initially zeros.

In one operation you can choose **any** subarray from `initial` and increment each value by one.

Return _the minimum number of operations to form a_ `target` _array from_ `initial`.

The test cases are generated so that the answer fits in a 32-bit integer.

**Example 1:**

**Input:** target = \[1,2,3,2,1\]
**Output:** 3
**Explanation:** We need at least 3 operations to form the target array from the initial array.
\[**0,0,0,0,0**\] increment 1 from index 0 to 4 (inclusive).
\[1,**1,1,1**,1\] increment 1 from index 1 to 3 (inclusive).
\[1,2,**2**,2,1\] increment 1 at index 2.
\[1,2,3,2,1\] target array is formed.

**Example 2:**

**Input:** target = \[3,1,1,2\]
**Output:** 4
**Explanation:** \[**0,0,0,0**\] -> \[1,1,1,**1**\] -> \[**1**,1,1,2\] -> \[**2**,1,1,2\] -> \[3,1,1,2\]

**Example 3:**

**Input:** target = \[3,1,5,4,2\]
**Output:** 7
**Explanation:** \[**0,0,0,0,0**\] -> \[**1**,1,1,1,1\] -> \[**2**,1,1,1,1\] -> \[3,1,**1,1,1**\] -> \[3,1,**2,2**,2\] -> \[3,1,**3,3**,2\] -> \[3,1,**4**,4,2\] -> \[3,1,5,4,2\].

**Constraints:**

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

## A solution in Java

```java
import java.util.HashMap;

public String entityParser(String text) {
    HashMap<String, Character> entities = new HashMap<String, Character>();
    entities.put(""", '\"');
    entities.put("'", '\'');
    entities.put("&", '&');
    entities.put(">", '>');
    entities.put("<", '<');
    entities.put("⁄", '/');

    StringBuilder result = new StringBuilder();
    for (int i = 0; i < text.length(); ++i) {
        if (text.charAt(i) == '&') {
            StringBuilder temp = new StringBuilder();
            for (int j = i; j < text.length() && j < i + 7; ++j) {
                temp.append(text.charAt(j));
                Character c = entities.get(temp.toString());
                if (c != null) {
                    result.append(c);
                    i = j;
                    break;
                }
            }
            if (temp.charAt(temp.length() - 1) != ';') result.append(text.charAt(i));
        } else {
            result.append(text.charAt(i));
        }
    }
    return result.toString();
}
```
1. Initialize a dictionary or hashmap named `entities` with keys as the HTML entity representation and values as the corresponding plaintext characters.
2. Initialize an empty string or character list named `result` to store the parsed text.
3. Loop through each character of the input `text`.
4. If the character is '&', try to match it as an entity in the dictionary.
5. If a match is found within the next 7 characters, append the decoded entity character to the `result` and update the loop counter `i` to skip the matched entity.
6. If no match is found, append the character to `result` as is.
7. After the loop, return the `result` as the parsed text.

## A solution in C++

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

string entityParser(string text) {
    unordered_map<string, char> entities{
        {""", '\"'},
        {"'", '\''},
        {"&", '&'},
        {">", '>'},
        {"<", '<'},
        {"⁄", '/'}
    };
    string result;
    for (int i = 0; i < text.size(); ++i) {
        if (text[i] == '&') {
            string temp;
            for (int j = i; j < text.size() && j < i + 7; ++j) {
                temp.push_back(text[j]);
                if (entities.find(temp) != entities.end()) {
                    result.push_back(entities[temp]);
                    i = j;
                    break;
                }
            }
            if (temp.back() != ';') result.push_back(text[i]);
        } else {
            result.push_back(text[i]);
        }
    }
    return result;
}
```
1. Initialize a dictionary or hashmap named `entities` with keys as the HTML entity representation and values as the corresponding plaintext characters.
2. Initialize an empty string or character list named `result` to store the parsed text.
3. Loop through each character of the input `text`.
4. If the character is '&', try to match it as an entity in the dictionary.
5. If a match is found within the next 7 characters, append the decoded entity character to the `result` and update the loop counter `i` to skip the matched entity.
6. If no match is found, append the character to `result` as is.
7. After the loop, return the `result` as the parsed text.

## A solution in Python

```python
def entityParser(text: str) -> str:
    entities = {
        """: '\"',
        "'": '\'',
        "&": '&',
        ">": '>',
        "<": '<',
        "⁄": '/'
    }

    result, i = [], 0
    while i < len(text):
        if text[i] == '&':
            temp = ''
            for j in range(i, min(i+7, len(text))):
                temp += text[j]
                if temp in entities:
                    result.append(entities[temp])
                    i = j
                    break
            else:
                result.append(text[i])
        else:
            result.append(text[i])
        i += 1
    return ''.join(result)
```
1. Initialize a dictionary or hashmap named `entities` with keys as the HTML entity representation and values as the corresponding plaintext characters.
2. Initialize an empty string or character list named `result` to store the parsed text.
3. Loop through each character of the input `text`.
4. If the character is '&', try to match it as an entity in the dictionary.
5. If a match is found within the next 7 characters, append the decoded entity character to the `result` and update the loop counter `i` to skip the matched entity.
6. If no match is found, append the character to `result` as is.
7. After the loop, return the `result` as the parsed text.

## A solution in Javascript

```javascript
function entityParser(text) {
    const entities = {
        """: '\"',
        "'": '\'',
        "&": '&',
        ">": '>',
        "<": '<',
        "⁄": '/'
    };

    let result = '';
    for (let i = 0; i < text.length; ++i) {
        if (text[i] === '&') {
            let temp = '';
            for (let j = i; j < text.length && j < i + 7; ++j) {
                temp += text[j];
                if (temp in entities) {
                    result += entities[temp];
                    i = j;
                    break;
                }
            }
            if (temp[temp.length - 1] !== ';') result += text[i];
        } else {
            result += text[i];
        }
    }
    return result;
}
```
1. Initialize a dictionary or hashmap named `entities` with keys as the HTML entity representation and values as the corresponding plaintext characters.
2. Initialize an empty string or character list named `result` to store the parsed text.
3. Loop through each character of the input `text`.
4. If the character is '&', try to match it as an entity in the dictionary.
5. If a match is found within the next 7 characters, append the decoded entity character to the `result` and update the loop counter `i` to skip the matched entity.
6. If no match is found, append the character to `result` as is.
7. After the loop, return the `result` as the parsed text.


# Shuffle String

- slug: shuffle-string
- difficulty: Easy

You are given a string `s` and an integer array `indices` of the **same length**. The string `s` will be shuffled such that the character at the `ith` position moves to `indices[i]` in the shuffled string.

Return _the shuffled string_.

**Example 1:**

**Input:** s =  "codeleet ", `indices` = \[4,5,6,7,0,2,1,3\]
**Output:**  "leetcode "
**Explanation:** As shown,  "codeleet " becomes  "leetcode " after shuffling.

**Example 2:**

**Input:** s =  "abc ", `indices` = \[0,1,2\]
**Output:**  "abc "
**Explanation:** After shuffling, each character remains in its position.

**Constraints:**

*   `s.length == indices.length == n`
*   `1 <= n <= 100`
*   `s` consists of only lowercase English letters.
*   `0 <= indices[i] < n`
*   All values of `indices` are **unique**.

## A solution in Java

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

public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
    int maxCandies = 0;
    for (int candy : candies) {
        maxCandies = Math.max(candy, maxCandies);
    }

    List<Boolean> result = new ArrayList<>();
    for (int candy : candies) {
        result.add(candy + extraCandies >= maxCandies);
    }

    return result;
}
```
The algorithm first finds the maximum number of candies any kid has by iterating over the candies array. Then, it iterates over the candies array again, checking if the number of candies a particular kid has plus the extra candies is greater than or equal to the maximum number of candies. If it is, it adds `true` to the result array, otherwise `false`. This result array is returned. The algorithm has a time complexity of O(n), where n is the length of the candies array.

## A solution in C++

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

vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
    int max_candies = *max_element(candies.begin(), candies.end());
    vector<bool> result(candies.size());

    for (int i = 0; i < candies.size(); i++) {
        result[i] = (candies[i] + extraCandies >= max_candies);
    }

    return result;
}
```
The algorithm first finds the maximum number of candies any kid has by iterating over the candies array. Then, it iterates over the candies array again, checking if the number of candies a particular kid has plus the extra candies is greater than or equal to the maximum number of candies. If it is, it adds `true` to the result array, otherwise `false`. This result array is returned. The algorithm has a time complexity of O(n), where n is the length of the candies array.

## A solution in Python

```python
from typing import List

def kids_with_candies(candies: List[int], extra_candies: int) -> List[bool]:
    max_candies = max(candies)
    result = [candy + extra_candies >= max_candies for candy in candies]
    return result
```
The algorithm first finds the maximum number of candies any kid has by iterating over the candies array. Then, it iterates over the candies array again, checking if the number of candies a particular kid has plus the extra candies is greater than or equal to the maximum number of candies. If it is, it adds `true` to the result array, otherwise `false`. This result array is returned. The algorithm has a time complexity of O(n), where n is the length of the candies array.

## A solution in Javascript

```javascript
function kidsWithCandies(candies, extraCandies) {
    let maxCandies = Math.max(...candies);
    let result = candies.map(candy => candy + extraCandies >= maxCandies);
    return result;
}
```
The algorithm first finds the maximum number of candies any kid has by iterating over the candies array. Then, it iterates over the candies array again, checking if the number of candies a particular kid has plus the extra candies is greater than or equal to the maximum number of candies. If it is, it adds `true` to the result array, otherwise `false`. This result array is returned. The algorithm has a time complexity of O(n), where n is the length of the candies array.


# Minimum Suffix Flips

- slug: minimum-suffix-flips
- difficulty: Medium

You are given a **0-indexed** binary string `target` of length `n`. You have another binary string `s` of length `n` that is initially set to all zeros. You want to make `s` equal to `target`.

In one operation, you can pick an index `i` where `0 <= i < n` and flip all bits in the **inclusive** range `[i, n - 1]`. Flip means changing `'0'` to `'1'` and `'1'` to `'0'`.

Return _the minimum number of operations needed to make_ `s` _equal to_ `target`.

**Example 1:**

**Input:** target =  "10111 "
**Output:** 3
**Explanation:** Initially, s =  "00000 ".
Choose index i = 2:  "00000 " ->  "00111 "
Choose index i = 0:  "00111 " ->  "11000 "
Choose index i = 1:  "11000 " ->  "10111 "
We need at least 3 flip operations to form target.

**Example 2:**

**Input:** target =  "101 "
**Output:** 3
**Explanation:** Initially, s =  "000 ".
Choose index i = 0:  "000 " ->  "111 "
Choose index i = 1:  "111 " ->  "100 "
Choose index i = 2:  "100 " ->  "101 "
We need at least 3 flip operations to form target.

**Example 3:**

**Input:** target =  "00000 "
**Output:** 0
**Explanation:** We do not need any operations since the initial s already equals target.

**Constraints:**

*   `n == target.length`
*   `1 <= n <= 105`
*   `target[i]` is either `'0'` or `'1'`.

## A solution in Java

```java
public int maxDifference(int num) {
    int a = num + 9 - (num % 10);
    int b = num - (num / 1000 % 10) * 111;

    return a - b;
}
```
The problem states that there are two operations applied to the given integer `num`. Let's find out the logic for determining the maximum difference between two numbers when these operations are applied to the given `num` twice:

1. In the first operation, try to increase the smallest digit of `num` to `9`. This will result in a new number `a`. Calculate `a` by adding `9` and subtracting the lowest digit (obtained using `num % 10`).
2. In the second operation, try to decrease the largest digit of `num` to `0`. This will result in a new number `b`. Calculate `b` by subtracting the highest digit multiplied by 111 (as it is a 4 digit number, so for each digit place the value is 1000s, 100s, 10s, and 1 respectively).

Finally, find the maximum difference between `a` and `b` by subtracting `b` from `a`.

## A solution in C++

```cpp
int maxDifference(int num) {
    int a = num + 9 - (num % 10);
    int b = num - (num / 1000 % 10) * 111;

    return a - b;
}
```
The problem states that there are two operations applied to the given integer `num`. Let's find out the logic for determining the maximum difference between two numbers when these operations are applied to the given `num` twice:

1. In the first operation, try to increase the smallest digit of `num` to `9`. This will result in a new number `a`. Calculate `a` by adding `9` and subtracting the lowest digit (obtained using `num % 10`).
2. In the second operation, try to decrease the largest digit of `num` to `0`. This will result in a new number `b`. Calculate `b` by subtracting the highest digit multiplied by 111 (as it is a 4 digit number, so for each digit place the value is 1000s, 100s, 10s, and 1 respectively).

Finally, find the maximum difference between `a` and `b` by subtracting `b` from `a`.

## A solution in Python

```python
def max_difference(num):
    a = num + 9 - (num % 10)
    b = num - (num // 1000 % 10) * 111

    return a - b
```
The problem states that there are two operations applied to the given integer `num`. Let's find out the logic for determining the maximum difference between two numbers when these operations are applied to the given `num` twice:

1. In the first operation, try to increase the smallest digit of `num` to `9`. This will result in a new number `a`. Calculate `a` by adding `9` and subtracting the lowest digit (obtained using `num % 10`).
2. In the second operation, try to decrease the largest digit of `num` to `0`. This will result in a new number `b`. Calculate `b` by subtracting the highest digit multiplied by 111 (as it is a 4 digit number, so for each digit place the value is 1000s, 100s, 10s, and 1 respectively).

Finally, find the maximum difference between `a` and `b` by subtracting `b` from `a`.

## A solution in Javascript

```javascript
function maxDifference(num) {
    const a = num + 9 - (num % 10);
    const b = num - (Math.floor(num / 1000) % 10) * 111;

    return a - b;
}
```
The problem states that there are two operations applied to the given integer `num`. Let's find out the logic for determining the maximum difference between two numbers when these operations are applied to the given `num` twice:

1. In the first operation, try to increase the smallest digit of `num` to `9`. This will result in a new number `a`. Calculate `a` by adding `9` and subtracting the lowest digit (obtained using `num % 10`).
2. In the second operation, try to decrease the largest digit of `num` to `0`. This will result in a new number `b`. Calculate `b` by subtracting the highest digit multiplied by 111 (as it is a 4 digit number, so for each digit place the value is 1000s, 100s, 10s, and 1 respectively).

Finally, find the maximum difference between `a` and `b` by subtracting `b` from `a`.


# Number of Good Leaf Nodes Pairs

- slug: number-of-good-leaf-nodes-pairs
- difficulty: Medium

You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`.

Return _the number of good leaf node pairs_ in the tree.

**Example 1:**

**Input:** root = \[1,2,3,null,4\], distance = 3
**Output:** 1
**Explanation:** The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.

**Example 2:**

**Input:** root = \[1,2,3,4,5,6,7\], distance = 3
**Output:** 2
**Explanation:** The good pairs are \[4,5\] and \[6,7\] with shortest path = 2. The pair \[4,6\] is not good because the length of ther shortest path between them is 4.

**Example 3:**

**Input:** root = \[7,1,4,6,null,5,3,null,null,null,null,null,2\], distance = 3
**Output:** 1
**Explanation:** The only good pair is \[2,5\].

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public boolean checkIfCanBreak(String s1, String s2) {
    char[] arr1 = s1.toCharArray();
    char[] arr2 = s2.toCharArray();
    Arrays.sort(arr1);
    Arrays.sort(arr2);

    boolean canBreak1 = true, canBreak2 = true;
    for(int i = 0; i < arr1.length; i++) {
        if(arr1[i] < arr2[i]) canBreak1 = false;
        if(arr2[i] < arr1[i]) canBreak2 = false;
    }
    return canBreak1 || canBreak2;
}
```
In this problem, we need to identify if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. To achieve this, we can sort each string and then compare corresponding characters to check if one string has characters greater than or equal to the other string at every position.

Here are the steps for the algorithm:

1. Sort both strings, `s1` and `s2`.
2. Initialize two boolean variables `can_break_1` and `can_break_2` as `true`.
3. Compare each character of the sorted `s1` and `s2` at the same index. If `s1[i]` is smaller than `s2[i]`, set `can_break_1` to `false`. If `s2[i]` is smaller than `s1[i]`, set `can_break_2` to `false`.
4. If `can_break_1` or `can_break_2` is `true`, return `true`. Otherwise, return `false`.

The algorithm is implemented in all four languages - C++, Java, Python, and JavaScript - following the syntax and conventions for each language. The core logic remains the same for all implementations.

## A solution in C++

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

bool checkIfCanBreak(std::string s1, std::string s2) {
    std::sort(s1.begin(), s1.end());
    std::sort(s2.begin(), s2.end());

    bool can_break_1 = true, can_break_2 = true;
    for(int i = 0; i < s1.size(); i++) {
        if(s1[i] < s2[i]) can_break_1 = false;
        if(s2[i] < s1[i]) can_break_2 = false;
    }
    return can_break_1 || can_break_2;
}
```
In this problem, we need to identify if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. To achieve this, we can sort each string and then compare corresponding characters to check if one string has characters greater than or equal to the other string at every position.

Here are the steps for the algorithm:

1. Sort both strings, `s1` and `s2`.
2. Initialize two boolean variables `can_break_1` and `can_break_2` as `true`.
3. Compare each character of the sorted `s1` and `s2` at the same index. If `s1[i]` is smaller than `s2[i]`, set `can_break_1` to `false`. If `s2[i]` is smaller than `s1[i]`, set `can_break_2` to `false`.
4. If `can_break_1` or `can_break_2` is `true`, return `true`. Otherwise, return `false`.

The algorithm is implemented in all four languages - C++, Java, Python, and JavaScript - following the syntax and conventions for each language. The core logic remains the same for all implementations.

## A solution in Python

```python
def check_if_can_break(s1, s2):
    s1 = sorted(s1)
    s2 = sorted(s2)

    can_break_1 = can_break_2 = True
    for c1, c2 in zip(s1, s2):
        if c1 < c2:
            can_break_1 = False
        if c2 < c1:
            can_break_2 = False

    return can_break_1 or can_break_2
```
In this problem, we need to identify if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. To achieve this, we can sort each string and then compare corresponding characters to check if one string has characters greater than or equal to the other string at every position.

Here are the steps for the algorithm:

1. Sort both strings, `s1` and `s2`.
2. Initialize two boolean variables `can_break_1` and `can_break_2` as `true`.
3. Compare each character of the sorted `s1` and `s2` at the same index. If `s1[i]` is smaller than `s2[i]`, set `can_break_1` to `false`. If `s2[i]` is smaller than `s1[i]`, set `can_break_2` to `false`.
4. If `can_break_1` or `can_break_2` is `true`, return `true`. Otherwise, return `false`.

The algorithm is implemented in all four languages - C++, Java, Python, and JavaScript - following the syntax and conventions for each language. The core logic remains the same for all implementations.

## A solution in Javascript

```javascript
function checkIfCanBreak(s1, s2) {
    let sorted1 = [...s1].sort();
    let sorted2 = [...s2].sort();

    let canBreak1 = true, canBreak2 = true;
    for(let i = 0; i < sorted1.length; i++) {
        if(sorted1[i] < sorted2[i]) canBreak1 = false;
        if(sorted2[i] < sorted1[i]) canBreak2 = false;
    }
    return canBreak1 || canBreak2;
}
```
In this problem, we need to identify if some permutation of string `s1` can break some permutation of string `s2` or vice-versa. To achieve this, we can sort each string and then compare corresponding characters to check if one string has characters greater than or equal to the other string at every position.

Here are the steps for the algorithm:

1. Sort both strings, `s1` and `s2`.
2. Initialize two boolean variables `can_break_1` and `can_break_2` as `true`.
3. Compare each character of the sorted `s1` and `s2` at the same index. If `s1[i]` is smaller than `s2[i]`, set `can_break_1` to `false`. If `s2[i]` is smaller than `s1[i]`, set `can_break_2` to `false`.
4. If `can_break_1` or `can_break_2` is `true`, return `true`. Otherwise, return `false`.

The algorithm is implemented in all four languages - C++, Java, Python, and JavaScript - following the syntax and conventions for each language. The core logic remains the same for all implementations.


# String Compression II

- slug: string-compression-ii
- difficulty: Hard

[Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string `"aabccc "` we replace `"aa "` by `"a2 "` and replace `"ccc "` by `"c3 "`. Thus the compressed string becomes `"a2bc3 "`.

Notice that in this problem, we are not adding `'1'` after single characters.

Given a string `s` and an integer `k`. You need to delete **at most** `k` characters from `s` such that the run-length encoded version of `s` has minimum length.

Find the _minimum length of the run-length encoded version of_ `s` _after deleting at most_ `k` _characters_.

**Example 1:**

**Input:** s =  "aaabcccd ", k = 2
**Output:** 4
**Explanation:** Compressing s without deleting anything will give us  "a3bc3d " of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s =  "abcccd " which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be  "a3c3 " of length 4.

**Example 2:**

**Input:** s =  "aabbaa ", k = 2
**Output:** 2
**Explanation:** If we delete both 'b' characters, the resulting compressed string would be  "a4 " of length 2.

**Example 3:**

**Input:** s =  "aaaaaaaaaaa ", k = 0
**Output:** 3
**Explanation:** Since k is zero, we cannot delete anything. The compressed string is  "a11 " of length 3.

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

public int numberWays(List<List<Integer>> hats) {
    final int kMod = 1000000007;
    final int kMaxHats = 40;

    int num_people = hats.size();
    List<List<Integer>> people_with_hat = new ArrayList<>();

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

    for (int i = 0; i < num_people; ++i) {
        for (int hat : hats.get(i)) {
            people_with_hat.get(hat - 1).add(i);
        }
    }

    int[][] dp = new int[1 << num_people][kMaxHats + 1];
    dp[0][0] = 1;

    for (int hat = 0; hat < kMaxHats; ++hat) {
        for (int mask = (1 << num_people) - 1; mask >= 0; --mask) {
            dp[mask][hat + 1] = (dp[mask][hat + 1] + dp[mask][hat]) % kMod;
            for (int person : people_with_hat.get(hat)) {
                if ((mask & (1 << person)) == 0) {
                    dp[mask | (1 << person)][hat + 1] = (dp[mask | (1 << person)][hat + 1] + dp[mask][hat]) % kMod;
                }
            }
        }
    }

    return dp[(1 << num_people) - 1][kMaxHats];
}
```
We create an array `people_with_hat` to store the indexes of people who prefer each hat. Then, we use dynamic programming to find the number of ways that the n people wear different hats to each other.

Our DP state is `dp[mask][hat]`, which represents the number of ways to assign hats 1 through hat to people, such that people with index `i` (0-indexed) gets a hat if the `i`-th bit of `mask` is set. We initialize `dp[0][0] = 1`.

We iterate through each hat (0-indexed array) and, for each mask from (1<<num_people)-1 to 0, we try two options:
1. Assign the current hat to no one - add `dp[mask][hat]` to `dp[mask][hat+1]`.
2. Assign the current hat to one of the people who prefer it, if the `i`-th bit of `mask` (0-indexed) is unset. In this case, we set the `i`-th bit of the mask and update `dp[mask | (1<<person)][hat+1]`.

Finally, we return the value in `dp[(1<<num_people) - 1][kMaxHats]`, which represents the number of ways of assigning all hats to the given people with their preferences.

Notice that we are using modulo 109 + 7 to avoid integer overflow.

## A solution in C++

```cpp
#include<vector>

int numberWays(std::vector<std::vector<int>>& hats) {
    const int kMod = 1000000007;
    const int kMaxHats = 40;

    int num_people = hats.size();
    std::vector<std::vector<int>> people_with_hat(kMaxHats);
    std::vector<std::vector<int>> dp(1<<num_people, std::vector<int>(kMaxHats+1, 0));

    for(int i = 0; i < num_people; ++i) {
        for(int hat : hats[i]) {
            people_with_hat[hat - 1].push_back(i);
        }
    }

    dp[0][0] = 1;

    for(int hat = 0; hat < kMaxHats; ++hat) {
        for(int mask = (1<<num_people) - 1; mask >= 0; --mask) {
            dp[mask][hat + 1] = (dp[mask][hat + 1] + dp[mask][hat]) % kMod;
            for(int person : people_with_hat[hat]) {
                if((mask & (1<<person)) == 0) {
                    dp[mask | (1<<person)][hat + 1] = (dp[mask | (1<<person)][hat + 1] + dp[mask][hat]) % kMod;
                }
            }
        }
    }

    return dp[(1<<num_people) - 1][kMaxHats];
}
```
We create an array `people_with_hat` to store the indexes of people who prefer each hat. Then, we use dynamic programming to find the number of ways that the n people wear different hats to each other.

Our DP state is `dp[mask][hat]`, which represents the number of ways to assign hats 1 through hat to people, such that people with index `i` (0-indexed) gets a hat if the `i`-th bit of `mask` is set. We initialize `dp[0][0] = 1`.

We iterate through each hat (0-indexed array) and, for each mask from (1<<num_people)-1 to 0, we try two options:
1. Assign the current hat to no one - add `dp[mask][hat]` to `dp[mask][hat+1]`.
2. Assign the current hat to one of the people who prefer it, if the `i`-th bit of `mask` (0-indexed) is unset. In this case, we set the `i`-th bit of the mask and update `dp[mask | (1<<person)][hat+1]`.

Finally, we return the value in `dp[(1<<num_people) - 1][kMaxHats]`, which represents the number of ways of assigning all hats to the given people with their preferences.

Notice that we are using modulo 109 + 7 to avoid integer overflow.

## A solution in Python

```python
def number_ways(hats):
    kMod = 1000000007
    kMaxHats = 40

    num_people = len(hats)
    people_with_hat = [[] for _ in range(kMaxHats)]

    for i in range(num_people):
        for hat in hats[i]:
            people_with_hat[hat - 1].append(i)

    dp = [[0] * (kMaxHats + 1) for _ in range(1 << num_people)]
    dp[0][0] = 1

    for hat in range(kMaxHats):
        for mask in reversed(range(1 << num_people)):
            dp[mask][hat + 1] = (dp[mask][hat + 1] + dp[mask][hat]) % kMod
            for person in people_with_hat[hat]:
                if mask & (1 << person) == 0:
                    dp[mask | (1 << person)][hat + 1] = (dp[mask | (1 << person)][hat + 1] + dp[mask][hat]) % kMod

    return dp[(1 << num_people) - 1][kMaxHats]
```
We create an array `people_with_hat` to store the indexes of people who prefer each hat. Then, we use dynamic programming to find the number of ways that the n people wear different hats to each other.

Our DP state is `dp[mask][hat]`, which represents the number of ways to assign hats 1 through hat to people, such that people with index `i` (0-indexed) gets a hat if the `i`-th bit of `mask` is set. We initialize `dp[0][0] = 1`.

We iterate through each hat (0-indexed array) and, for each mask from (1<<num_people)-1 to 0, we try two options:
1. Assign the current hat to no one - add `dp[mask][hat]` to `dp[mask][hat+1]`.
2. Assign the current hat to one of the people who prefer it, if the `i`-th bit of `mask` (0-indexed) is unset. In this case, we set the `i`-th bit of the mask and update `dp[mask | (1<<person)][hat+1]`.

Finally, we return the value in `dp[(1<<num_people) - 1][kMaxHats]`, which represents the number of ways of assigning all hats to the given people with their preferences.

Notice that we are using modulo 109 + 7 to avoid integer overflow.

## A solution in Javascript

```javascript
function numberWays(hats) {
    const kMod = 1000000007;
    const kMaxHats = 40;

    const num_people = hats.length;
    const people_with_hat = Array.from({length: kMaxHats}, () => []);

    for (let i = 0; i < num_people; ++i) {
        for (const hat of hats[i]) {
            people_with_hat[hat - 1].push(i);
        }
    }

    const dp = Array.from({length: 1 << num_people}, () => Array(kMaxHats + 1).fill(0));
    dp[0][0] = 1;

    for (let hat = 0; hat < kMaxHats; ++hat) {
        for (let mask = (1 << num_people) - 1; mask >= 0; --mask) {
            dp[mask][hat + 1] = (dp[mask][hat + 1] + dp[mask][hat]) % kMod;
            for (const person of people_with_hat[hat]) {
                if ((mask & (1 << person)) === 0) {
                    dp[mask | (1 << person)][hat + 1] = (dp[mask | (1 << person)][hat + 1] + dp[mask][hat]) % kMod;
                }
            }
        }
    }

    return dp[(1 << num_people) - 1][kMaxHats];
}
```
We create an array `people_with_hat` to store the indexes of people who prefer each hat. Then, we use dynamic programming to find the number of ways that the n people wear different hats to each other.

Our DP state is `dp[mask][hat]`, which represents the number of ways to assign hats 1 through hat to people, such that people with index `i` (0-indexed) gets a hat if the `i`-th bit of `mask` is set. We initialize `dp[0][0] = 1`.

We iterate through each hat (0-indexed array) and, for each mask from (1<<num_people)-1 to 0, we try two options:
1. Assign the current hat to no one - add `dp[mask][hat]` to `dp[mask][hat+1]`.
2. Assign the current hat to one of the people who prefer it, if the `i`-th bit of `mask` (0-indexed) is unset. In this case, we set the `i`-th bit of the mask and update `dp[mask | (1<<person)][hat+1]`.

Finally, we return the value in `dp[(1<<num_people) - 1][kMaxHats]`, which represents the number of ways of assigning all hats to the given people with their preferences.

Notice that we are using modulo 109 + 7 to avoid integer overflow.


# Find the Index of the Large Integer

- slug: find-the-index-of-the-large-integer
- difficulty: Medium

We have an integer array `arr`, where all the integers in `arr` are equal except for one integer which is **larger** than the rest of the integers. You will not be given direct access to the array, instead, you will have an **API** `ArrayReader` which have the following functions:

*   `int compareSub(int l, int r, int x, int y)`: where `0 <= l, r, x, y < ArrayReader.length()`, `l <= r and` `x <= y`. The function compares the sum of sub-array `arr[l..r]` with the sum of the sub-array `arr[x..y]` and returns:
    *   **1** if `arr[l]+arr[l+1]+...+arr[r] > arr[x]+arr[x+1]+...+arr[y]`.
    *   **0** if `arr[l]+arr[l+1]+...+arr[r] == arr[x]+arr[x+1]+...+arr[y]`.
    *   **\-1** if `arr[l]+arr[l+1]+...+arr[r] < arr[x]+arr[x+1]+...+arr[y]`.
*   `int length()`: Returns the size of the array.

You are allowed to call `compareSub()` **20 times** at most. You can assume both functions work in `O(1)` time.

Return _the index of the array `arr` which has the largest integer_.

**Example 1:**

**Input:** arr = \[7,7,7,7,10,7,7,7\]
**Output:** 4
**Explanation:** The following calls to the API
reader.compareSub(0, 0, 1, 1) // returns 0 this is a query comparing the sub-array (0, 0) with the sub array (1, 1), (i.e. compares arr\[0\] with arr\[1\]).
Thus we know that arr\[0\] and arr\[1\] doesn't contain the largest element.
reader.compareSub(2, 2, 3, 3) // returns 0, we can exclude arr\[2\] and arr\[3\].
reader.compareSub(4, 4, 5, 5) // returns 1, thus for sure arr\[4\] is the largest element in the array.
Notice that we made only 3 calls, so the answer is valid.

**Example 2:**

**Input:** nums = \[6,6,12\]
**Output:** 2

**Constraints:**

*   `2 <= arr.length <= 5 * 105`
*   `1 <= arr[i] <= 100`
*   All elements of `arr` are equal except for one element which is larger than all other elements.

**Follow up:**

*   What if there are two numbers in `arr` that are bigger than all other numbers?
*   What if there is one number that is bigger than other numbers and one number that is smaller than other numbers?

## A solution in Java

```java
import java.util.*;

public List<List<String>> displayTable(List<List<String>> orders) {
    TreeSet<String> foodItems = new TreeSet<>();
    TreeMap<Integer, Map<String, Integer>> tableOrders = new TreeMap<>();

    for (List<String> order : orders) {
        foodItems.add(order.get(2));
        int tableNumber = Integer.parseInt(order.get(1));
        tableOrders.putIfAbsent(tableNumber, new HashMap<>());
        tableOrders.get(tableNumber).put(order.get(2), tableOrders.get(tableNumber).getOrDefault(order.get(2), 0) + 1);
    }

    List<List<String>> result = new ArrayList<>();
    List<String> header = new ArrayList<>();
    header.add("Table");
    header.addAll(foodItems);
    result.add(header);

    for (Map.Entry<Integer, Map<String, Integer>> entry : tableOrders.entrySet()) {
        List<String> row = new ArrayList<>();
        row.add(String.valueOf(entry.getKey()));
        for (String food : foodItems) {
            row.add(String.valueOf(entry.getValue().getOrDefault(food, 0)));
        }
        result.add(row);
    }

    return result;
}
```
1. Initialize a set for unique food items and a map for table orders.
2. Iterate over all orders and add food items to the set and update the table orders map.
3. Prepare a header row with the sorted food items.
4. Iterate over the sorted table orders and create an array for each table with the number of food items ordered.
5. Return the result with the header and table order rows.

## A solution in C++

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

using namespace std;

vector<vector<string>> displayTable(vector<vector<string>>& orders) {
    set<string> foodItems;
    map<int, map<string, int>> tableOrders;

    for (const auto& order : orders) {
        foodItems.insert(order[2]);
        tableOrders[stoi(order[1])][order[2]]++;
    }

    vector<vector<string>> result;
    vector<string> header;
    header.push_back("Table");
    header.insert(header.end(), foodItems.begin(), foodItems.end());
    result.push_back(header);

    for (const auto& entry : tableOrders) {
        vector<string> row;
        row.push_back(to_string(entry.first));
        for (const auto& food : foodItems) {
            row.push_back(to_string(entry.second[food]));
        }
        result.push_back(row);
    }

    return result;
}
```
1. Initialize a set for unique food items and a map for table orders.
2. Iterate over all orders and add food items to the set and update the table orders map.
3. Prepare a header row with the sorted food items.
4. Iterate over the sorted table orders and create an array for each table with the number of food items ordered.
5. Return the result with the header and table order rows.

## A solution in Python

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

def displayTable(orders: List[List[str]]) -> List[List[str]]:
    foodItems = set()
    tableOrders = defaultdict(lambda: defaultdict(int))

    for order in orders:
        foodItems.add(order[2])
        tableOrders[int(order[1])][order[2]] += 1

    foodItems = sorted(foodItems)
    header = ["Table"] + foodItems
    result = [header]

    for tableNumber, foodOrder in sorted(tableOrders.items()):
        row = [str(tableNumber)] + [str(foodOrder[food]) for food in foodItems]
        result.append(row)

    return result
```
1. Initialize a set for unique food items and a map for table orders.
2. Iterate over all orders and add food items to the set and update the table orders map.
3. Prepare a header row with the sorted food items.
4. Iterate over the sorted table orders and create an array for each table with the number of food items ordered.
5. Return the result with the header and table order rows.

## A solution in Javascript

```javascript
function displayTable(orders) {
    const foodItems = new Set();
    const tableOrders = new Map();

    for (const order of orders) {
        foodItems.add(order[2]);
        const tableNumber = parseInt(order[1]);
        if (!tableOrders.has(tableNumber)) {
            tableOrders.set(tableNumber, new Map());
        }
        const table = tableOrders.get(tableNumber);
        table.set(order[2], (table.get(order[2]) || 0) + 1);
    }

    const sortedFoodItems = Array.from(foodItems).sort();
    const header = ['Table', ...sortedFoodItems];
    const result = [header];

    for (const [tableNumber, foodOrder] of [...tableOrders.entries()].sort((a, b) => a[0] - b[0])) {
        const row = [tableNumber.toString(), ...sortedFoodItems.map(food => (foodOrder.get(food) || 0).toString())];
        result.push(row);
    }

    return result;
}
```
1. Initialize a set for unique food items and a map for table orders.
2. Iterate over all orders and add food items to the set and update the table orders map.
3. Prepare a header row with the sorted food items.
4. Iterate over the sorted table orders and create an array for each table with the number of food items ordered.
5. Return the result with the header and table order rows.


# Count Good Triplets

- slug: count-good-triplets
- difficulty: Easy

Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.

A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:

*   `0 <= i < j < k < arr.length`
*   `|arr[i] - arr[j]| <= a`
*   `|arr[j] - arr[k]| <= b`
*   `|arr[i] - arr[k]| <= c`

Where `|x|` denotes the absolute value of `x`.

Return _the number of good triplets_.

**Example 1:**

**Input:** arr = \[3,0,1,1,9,7\], a = 7, b = 2, c = 3
**Output:** 4
**Explanation:** There are 4 good triplets: \[(3,0,1), (3,0,1), (3,1,1), (0,1,1)\].

**Example 2:**

**Input:** arr = \[1,1,2,2,3\], a = 0, b = 0, c = 1
**Output:** 0
**Explanation:** No triplet satisfies all conditions.

**Constraints:**

*   `3 <= arr.length <= 100`
*   `0 <= arr[i] <= 1000`
*   `0 <= a, b, c <= 1000`

## A solution in Java

```java
int minNumberOfFrogs(String croakOfFrogs) {
    int[] counts = new int[5];
    int max_frogs = 0;

    for (char c : croakOfFrogs.toCharArray()) {
        int index = "croak".indexOf(c);
        if (index == 0) {
            counts[0]++;
            max_frogs = Math.max(max_frogs, counts[0]);
        } else if (counts[index - 1] > 0) {
            counts[index - 1]--;
            counts[index]++;
        } else {
            return -1;
        }
    }

    if (counts[0] == counts[4]) {
        return max_frogs;
    } else {
        return -1;
    }
}
```
The algorithm starts by initializing an array `counts` with five elements and `max_frogs` to zero. It iterates through the given string `croakOfFrogs`. For each character, it finds its index in the string "croak":

- If the character is a 'c', it increases the first element of `counts` and updates the `max_frogs`.
- If the character is one of 'r', 'o', 'a', or 'k', it checks if the previous letter in "croak" has a non-zero count in the `counts` array. If it does, it transfers the count of the previous letter to the count of the current character; otherwise, it returns -1, as the string does not represent a valid croak sequence.

After iterating through the entire string, the algorithm checks if the count of 'c's is equal to the count of 'k's, which indicates that all frog croaks are completed. If so, it returns the value of `max_frogs`; otherwise, it returns -1.

## A solution in C++

```cpp
#include <string>

int minNumberOfFrogs(std::string croakOfFrogs) {
    int counts[5] = {0}, max_frogs = 0;

    for (char c : croakOfFrogs) {
        int index = std::string("croak").find(c);
        if (index == 0) {
            counts[0]++;
            max_frogs = std::max(max_frogs, counts[0]);
        } else if (counts[index - 1] > 0) {
            counts[index - 1]--;
            counts[index]++;
        } else {
            return -1;
        }
    }

    if (counts[0] == counts[4]) {
        return max_frogs;
    } else {
        return -1;
    }
}
```
The algorithm starts by initializing an array `counts` with five elements and `max_frogs` to zero. It iterates through the given string `croakOfFrogs`. For each character, it finds its index in the string "croak":

- If the character is a 'c', it increases the first element of `counts` and updates the `max_frogs`.
- If the character is one of 'r', 'o', 'a', or 'k', it checks if the previous letter in "croak" has a non-zero count in the `counts` array. If it does, it transfers the count of the previous letter to the count of the current character; otherwise, it returns -1, as the string does not represent a valid croak sequence.

After iterating through the entire string, the algorithm checks if the count of 'c's is equal to the count of 'k's, which indicates that all frog croaks are completed. If so, it returns the value of `max_frogs`; otherwise, it returns -1.

## A solution in Python

```python
def minNumberOfFrogs(croakOfFrogs: str) -> int:
    counts = [0] * 5
    max_frogs = 0

    for c in croakOfFrogs:
        index = "croak".find(c)
        if index == 0:
            counts[0] += 1
            max_frogs = max(max_frogs, counts[0])
        elif counts[index - 1] > 0:
            counts[index - 1] -= 1
            counts[index] += 1
        else:
            return -1

    if counts[0] == counts[4]:
        return max_frogs
    else:
        return -1
```
The algorithm starts by initializing an array `counts` with five elements and `max_frogs` to zero. It iterates through the given string `croakOfFrogs`. For each character, it finds its index in the string "croak":

- If the character is a 'c', it increases the first element of `counts` and updates the `max_frogs`.
- If the character is one of 'r', 'o', 'a', or 'k', it checks if the previous letter in "croak" has a non-zero count in the `counts` array. If it does, it transfers the count of the previous letter to the count of the current character; otherwise, it returns -1, as the string does not represent a valid croak sequence.

After iterating through the entire string, the algorithm checks if the count of 'c's is equal to the count of 'k's, which indicates that all frog croaks are completed. If so, it returns the value of `max_frogs`; otherwise, it returns -1.

## A solution in Javascript

```javascript
function minNumberOfFrogs(croakOfFrogs) {
    let counts = Array(5).fill(0);
    let max_frogs = 0;

    for (let c of croakOfFrogs) {
        let index = "croak".indexOf(c);
        if (index === 0) {
            counts[0]++;
            max_frogs = Math.max(max_frogs, counts[0]);
        } else if (counts[index - 1] > 0) {
            counts[index - 1]--;
            counts[index]++;
        } else {
            return -1;
        }
    }

    if (counts[0] === counts[4]) {
        return max_frogs;
    } else {
        return -1;
    }
}
```
The algorithm starts by initializing an array `counts` with five elements and `max_frogs` to zero. It iterates through the given string `croakOfFrogs`. For each character, it finds its index in the string "croak":

- If the character is a 'c', it increases the first element of `counts` and updates the `max_frogs`.
- If the character is one of 'r', 'o', 'a', or 'k', it checks if the previous letter in "croak" has a non-zero count in the `counts` array. If it does, it transfers the count of the previous letter to the count of the current character; otherwise, it returns -1, as the string does not represent a valid croak sequence.

After iterating through the entire string, the algorithm checks if the count of 'c's is equal to the count of 'k's, which indicates that all frog croaks are completed. If so, it returns the value of `max_frogs`; otherwise, it returns -1.


# Find the Winner of an Array Game

- slug: find-the-winner-of-an-array-game
- difficulty: Medium

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

A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to the end of the array. The game ends when an integer wins `k` consecutive rounds.

Return _the integer which will win the game_.

It is **guaranteed** that there will be a winner of the game.

**Example 1:**

**Input:** arr = \[2,1,3,5,4,6,7\], k = 2
**Output:** 5
**Explanation:** Let's see the rounds of the game:
Round |       arr       | winner | win\_count
  1   | \[2,1,3,5,4,6,7\] | 2      | 1
  2   | \[2,3,5,4,6,7,1\] | 3      | 1
  3   | \[3,5,4,6,7,1,2\] | 5      | 1
  4   | \[5,4,6,7,1,2,3\] | 5      | 2
So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.

**Example 2:**

**Input:** arr = \[3,2,1\], k = 10
**Output:** 3
**Explanation:** 3 will win the first 10 rounds consecutively.

**Constraints:**

*   `2 <= arr.length <= 105`
*   `1 <= arr[i] <= 106`
*   `arr` contains **distinct** integers.
*   `1 <= k <= 109`

## A solution in Java

```java
int numberOfWays(int n, int m, int k, int mod = 1_000_000_007) {
    if (k > 1) {
        long result = 1;
        for (int i = 0; i < n; ++i) {
            result = (result * m) % mod;
        }
        return (int)result;
    }
    return n % 2 == 0 ? 1 : m;
}
```
The algorithm first checks if k is greater than 1. If it is, initialize a variable 'result' to 1, and then loop through the range of n, at each iteration multiply 'result' by m and apply the modulo operation using the given 'mod' value. Return the final result value.

If k is not greater than 1, return 1 if n is even, and return m if n is odd.

## A solution in C++

```cpp
int numberOfWays(int n, int m, int k, int mod = 1'000'000'007) {
    if (k > 1) {
        long long result = 1;
        for (int i = 0; i < n; ++i) {
            result = (result * m) % mod;
        }
        return result;
    }
    return n % 2 == 0 ? 1 : m;
}
```
The algorithm first checks if k is greater than 1. If it is, initialize a variable 'result' to 1, and then loop through the range of n, at each iteration multiply 'result' by m and apply the modulo operation using the given 'mod' value. Return the final result value.

If k is not greater than 1, return 1 if n is even, and return m if n is odd.

## A solution in Python

```python
def number_of_ways(n, m, k, mod=1_000_000_007):
    if k > 1:
        result = 1
        for _ in range(n):
            result = (result * m) % mod
        return result
    return 1 if n % 2 == 0 else m
```
The algorithm first checks if k is greater than 1. If it is, initialize a variable 'result' to 1, and then loop through the range of n, at each iteration multiply 'result' by m and apply the modulo operation using the given 'mod' value. Return the final result value.

If k is not greater than 1, return 1 if n is even, and return m if n is odd.

## A solution in Javascript

```javascript
function numberOfWays(n, m, k, mod = 1_000_000_007) {
    if (k > 1) {
        let result = 1;
        for (let i = 0; i < n; ++i) {
            result = (result * m) % mod;
        }
        return result;
    }
    return n % 2 === 0 ? 1 : m;
}
```
The algorithm first checks if k is greater than 1. If it is, initialize a variable 'result' to 1, and then loop through the range of n, at each iteration multiply 'result' by m and apply the modulo operation using the given 'mod' value. Return the final result value.

If k is not greater than 1, return 1 if n is even, and return m if n is odd.


# Minimum Swaps to Arrange a Binary Grid

- slug: minimum-swaps-to-arrange-a-binary-grid
- difficulty: Medium

Given an `n x n` binary `grid`, in one step you can choose two **adjacent rows** of the grid and swap them.

A grid is said to be **valid** if all the cells above the main diagonal are **zeros**.

Return _the minimum number of steps_ needed to make the grid valid, or **\-1** if the grid cannot be valid.

The main diagonal of a grid is the diagonal that starts at cell `(1, 1)` and ends at cell `(n, n)`.

**Example 1:**

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

**Example 2:**

**Input:** grid = \[\[0,1,1,0\],\[0,1,1,0\],\[0,1,1,0\],\[0,1,1,0\]\]
**Output:** -1
**Explanation:** All rows are similar, swaps have no effect on the grid.

**Example 3:**

**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,1\]\]
**Output:** 0

**Constraints:**

*   `n == grid.length` `== grid[i].length`
*   `1 <= n <= 200`
*   `grid[i][j]` is either `0` or `1`

## A solution in Java

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

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

        while (row > i) {
            int[] temp = grid[row];
            grid[row] = grid[row - 1];
            grid[row - 1] = temp;
            steps++;
            row--;
        }
    }
    return steps;
}
```
The algorithm first initializes steps to 0. Then, for each column i from 0 to n-1, it tries to find a row in which the cell in the current column is 0. If a row is found, it swaps this row with the previous row to move the 0 value up until the required position is reached. While doing the swaps, it increments the steps counter. If the row is not found for any column, the algorithm returns -1 as the grid cannot be valid.

## A solution in C++

```cpp
int minSwaps(vector<vector<int>>& grid) {
    int n = grid.size();
    int steps = 0;

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

        while (row > i) {
            swap(grid[row], grid[row - 1]);
            steps++;
            row--;
        }
    }
    return steps;
}
```
The algorithm first initializes steps to 0. Then, for each column i from 0 to n-1, it tries to find a row in which the cell in the current column is 0. If a row is found, it swaps this row with the previous row to move the 0 value up until the required position is reached. While doing the swaps, it increments the steps counter. If the row is not found for any column, the algorithm returns -1 as the grid cannot be valid.

## A solution in Python

```python
def minSwaps(grid):
    n = len(grid)
    steps = 0

    for i in range(n):
        row = -1
        for j in range(i, n):
            if grid[j][i] == 0:
                row = j
                break
        if row == -1:
            return -1

        while row > i:
            grid[row], grid[row - 1] = grid[row - 1], grid[row]
            steps += 1
            row -= 1

    return steps
```
The algorithm first initializes steps to 0. Then, for each column i from 0 to n-1, it tries to find a row in which the cell in the current column is 0. If a row is found, it swaps this row with the previous row to move the 0 value up until the required position is reached. While doing the swaps, it increments the steps counter. If the row is not found for any column, the algorithm returns -1 as the grid cannot be valid.

## A solution in Javascript

```javascript
function minSwaps(grid) {
    const n = grid.length;
    let steps = 0;

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

        while (row > i) {
            [grid[row], grid[row - 1]] = [grid[row - 1], grid[row]];
            steps++;
            row--;
        }
    }
    return steps;
}
```
The algorithm first initializes steps to 0. Then, for each column i from 0 to n-1, it tries to find a row in which the cell in the current column is 0. If a row is found, it swaps this row with the previous row to move the 0 value up until the required position is reached. While doing the swaps, it increments the steps counter. If the row is not found for any column, the algorithm returns -1 as the grid cannot be valid.


# Get the Maximum Score

- slug: get-the-maximum-score
- difficulty: Hard

You are given two **sorted** arrays of distinct integers `nums1` and `nums2.`

A **valid path** is defined as follows:

*   Choose array `nums1` or `nums2` to traverse (from index-0).
*   Traverse the current array from left to right.
*   If you are reading any value that is present in `nums1` and `nums2` you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).

The **score** is defined as the sum of uniques values in a valid path.

Return _the maximum score you can obtain of all possible **valid paths**_. Since the answer may be too large, return it modulo `109 + 7`.

**Example 1:**

**Input:** nums1 = \[2,4,5,8,10\], nums2 = \[4,6,8,9\]
**Output:** 30
**Explanation:** Valid paths:
\[2,4,5,8,10\], \[2,4,5,8,9\], \[2,4,6,8,9\], \[2,4,6,8,10\],  (starting from nums1)
\[4,6,8,9\], \[4,5,8,10\], \[4,5,8,9\], \[4,6,8,10\]    (starting from nums2)
The maximum is obtained with the path in green **\[2,4,6,8,10\]**.

**Example 2:**

**Input:** nums1 = \[1,3,5,7,9\], nums2 = \[3,5,100\]
**Output:** 109
**Explanation:** Maximum sum is obtained with the path **\[1,3,5,100\]**.

**Example 3:**

**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[6,7,8,9,10\]
**Output:** 40
**Explanation:** There are no common elements between nums1 and nums2.
Maximum sum is obtained with the path \[6,7,8,9,10\].

**Constraints:**

*   `1 <= nums1.length, nums2.length <= 105`
*   `1 <= nums1[i], nums2[i] <= 107`
*   `nums1` and `nums2` are strictly increasing.

## A solution in Java

```java
public int maxScore(String s) {
    int left_zeros = 0, right_ones = 0, max_score = 0;
    for(char c : s.toCharArray()) if(c == '1') right_ones++;

    for(int i = 0; i < s.length() - 1; i++) {
        if(s.charAt(i) == '0') left_zeros++;
        else right_ones--;
        max_score = Math.max(max_score, left_zeros + right_ones);
    }
    return max_score;
}
```
The algorithm works as follows:
1. Initialize three variables: `left_zeros` to count zeros in the left substring, `right_ones` to count ones in the right substring, and `max_score` to store the maximum score after checking all possible splits.
2. Count the total number of ones in the whole string and store it in `right_ones`.
3. Iterate through the string (excluding the last character since both substrings should be non-empty) and for each character i, do the following:
   a. If the character is '0', increment `left_zeros`. Else, decrement `right_ones` as the character '1' is moving from the right substring to the left substring.
   b. Calculate the score by adding `left_zeros` and `right_ones`, and update `max_score` if it is less than the current score.
4. Return the `max_score` after the iteration is complete.

## A solution in C++

```cpp
int maxScore(string s) {
    int left_zeros = 0, right_ones = 0, max_score = 0;
    for(char c : s) if(c == '1') right_ones++;

    for(int i = 0; i < s.size() - 1; i++) {
        if(s[i] == '0') left_zeros++;
        else right_ones--;
        max_score = max(max_score, left_zeros + right_ones);
    }
    return max_score;
}
```
The algorithm works as follows:
1. Initialize three variables: `left_zeros` to count zeros in the left substring, `right_ones` to count ones in the right substring, and `max_score` to store the maximum score after checking all possible splits.
2. Count the total number of ones in the whole string and store it in `right_ones`.
3. Iterate through the string (excluding the last character since both substrings should be non-empty) and for each character i, do the following:
   a. If the character is '0', increment `left_zeros`. Else, decrement `right_ones` as the character '1' is moving from the right substring to the left substring.
   b. Calculate the score by adding `left_zeros` and `right_ones`, and update `max_score` if it is less than the current score.
4. Return the `max_score` after the iteration is complete.

## A solution in Python

```python
def maxScore(s):
    left_zeros, right_ones, max_score = 0, s.count('1'), 0
    for i in range(len(s) - 1):
        if s[i] == '0': left_zeros += 1
        else: right_ones -= 1
        max_score = max(max_score, left_zeros + right_ones)
    return max_score
```
The algorithm works as follows:
1. Initialize three variables: `left_zeros` to count zeros in the left substring, `right_ones` to count ones in the right substring, and `max_score` to store the maximum score after checking all possible splits.
2. Count the total number of ones in the whole string and store it in `right_ones`.
3. Iterate through the string (excluding the last character since both substrings should be non-empty) and for each character i, do the following:
   a. If the character is '0', increment `left_zeros`. Else, decrement `right_ones` as the character '1' is moving from the right substring to the left substring.
   b. Calculate the score by adding `left_zeros` and `right_ones`, and update `max_score` if it is less than the current score.
4. Return the `max_score` after the iteration is complete.

## A solution in Javascript

```javascript
function maxScore(s) {
    let left_zeros = 0, right_ones = 0, max_score = 0;
    for(let c of s) if(c === '1') right_ones++;

    for(let i = 0; i < s.length - 1; i++) {
        if(s[i] === '0') left_zeros++;
        else right_ones--;
        max_score = Math.max(max_score, left_zeros + right_ones);
    }
    return max_score;
}
```
The algorithm works as follows:
1. Initialize three variables: `left_zeros` to count zeros in the left substring, `right_ones` to count ones in the right substring, and `max_score` to store the maximum score after checking all possible splits.
2. Count the total number of ones in the whole string and store it in `right_ones`.
3. Iterate through the string (excluding the last character since both substrings should be non-empty) and for each character i, do the following:
   a. If the character is '0', increment `left_zeros`. Else, decrement `right_ones` as the character '1' is moving from the right substring to the left substring.
   b. Calculate the score by adding `left_zeros` and `right_ones`, and update `max_score` if it is less than the current score.
4. Return the `max_score` after the iteration is complete.


# Guess the Majority in a Hidden Array

- slug: guess-the-majority-in-a-hidden-array
- difficulty: Medium

We have an integer array `nums`, where all the integers in `nums` are **0** or **1**. You will not be given direct access to the array, instead, you will have an **API** `ArrayReader` which have the following functions:

*   `int query(int a, int b, int c, int d)`: where `0 <= a < b < c < d < ArrayReader.length()`. The function returns the distribution of the value of the 4 elements and returns:
    *   **4** : if the values of the 4 elements are the same (0 or 1).
    *   **2** : if three elements have a value equal to 0 and one element has value equal to 1 or vice versa.
    *   **0** : if two element have a value equal to 0 and two elements have a value equal to 1.
*   `int length()`: Returns the size of the array.

You are allowed to call `query()` **2 \* n times** at most where n is equal to `ArrayReader.length()`.

Return **any** index of the most frequent value in `nums`, in case of tie, return -1.

**Example 1:**

**Input:** nums = \[0,0,1,0,1,1,1,1\]
**Output:** 5
**Explanation:** The following calls to the API
reader.length() // returns 8 because there are 8 elements in the hidden array.
reader.query(0,1,2,3) // returns 2 this is a query that compares the elements nums\[0\], nums\[1\], nums\[2\], nums\[3\]
// Three elements have a value equal to 0 and one element has value equal to 1 or viceversa.
reader.query(4,5,6,7) // returns 4 because nums\[4\], nums\[5\], nums\[6\], nums\[7\] have the same value.
we can infer that the most frequent value is found in the last 4 elements.
Index 2, 4, 6, 7 is also a correct answer.

**Example 2:**

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

**Example 3:**

**Input:** nums = \[1,0,1,0,1,0,1,0\]
**Output:** -1

**Constraints:**

*   `5 <= nums.length <= 105`
*   `0 <= nums[i] <= 1`

**Follow up:** What is the minimum number of calls needed to find the majority element?

## A solution in Java

```java
public int maxScore(int[] cardPoints, int k) {
    int n = cardPoints.length;
    int total = 0;
    for (int i = 0; i < k; i++) {
        total += cardPoints[i];
    }

    int maxScore = total;
    for (int i = k - 1, j = n - 1; i >= 0; i--, j--) {
        total += cardPoints[j] - cardPoints[i];
        maxScore = Math.max(maxScore, total);
    }

    return maxScore;
}
```
The algorithm starts by taking the first k cards and calculating the initial total score. Then, in a loop, it iteratively removes the first card and adds the next card from the end. By doing this, it explores all possible combinations of taking `k` cards from the beginning or the end of the row. The maximum score is updated each time a potentially higher score is found. The loop ends when all combinations are explored, and the resulting maximum score is returned.

## A solution in C++

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

int maxScore(vector<int>& cardPoints, int k) {
    int n = cardPoints.size();
    int total = 0;
    for (int i = 0; i < k; ++i) {
        total += cardPoints[i];
    }

    int maxScore = total;
    for (int i = k - 1, j = n - 1; i >= 0; --i, --j) {
        total += cardPoints[j] - cardPoints[i];
        maxScore = max(maxScore, total);
    }

    return maxScore;
}
```
The algorithm starts by taking the first k cards and calculating the initial total score. Then, in a loop, it iteratively removes the first card and adds the next card from the end. By doing this, it explores all possible combinations of taking `k` cards from the beginning or the end of the row. The maximum score is updated each time a potentially higher score is found. The loop ends when all combinations are explored, and the resulting maximum score is returned.

## A solution in Python

```python
def maxScore(cardPoints, k):
    n = len(cardPoints)
    total = sum(cardPoints[:k])

    max_score = total
    for i in range(k - 1, -1, -1):
        j = n - k + i
        total += cardPoints[j] - cardPoints[i]
        max_score = max(max_score, total)

    return max_score
```
The algorithm starts by taking the first k cards and calculating the initial total score. Then, in a loop, it iteratively removes the first card and adds the next card from the end. By doing this, it explores all possible combinations of taking `k` cards from the beginning or the end of the row. The maximum score is updated each time a potentially higher score is found. The loop ends when all combinations are explored, and the resulting maximum score is returned.

## A solution in Javascript

```javascript
function maxScore(cardPoints, k) {
    let n = cardPoints.length;
    let total = 0;
    for (let i = 0; i < k; i++) {
        total += cardPoints[i];
    }

    let maxScore = total;
    for (let i = k - 1, j = n - 1; i >= 0; i--, j--) {
        total += cardPoints[j] - cardPoints[i];
        maxScore = Math.max(maxScore, total);
    }

    return maxScore;
}
```
The algorithm starts by taking the first k cards and calculating the initial total score. Then, in a loop, it iteratively removes the first card and adds the next card from the end. By doing this, it explores all possible combinations of taking `k` cards from the beginning or the end of the row. The maximum score is updated each time a potentially higher score is found. The loop ends when all combinations are explored, and the resulting maximum score is returned.


# Kth Missing Positive Number

- slug: kth-missing-positive-number
- difficulty: Easy

Given an array `arr` of positive integers sorted in a **strictly increasing order**, and an integer `k`.

Return _the_ `kth` _**positive** integer that is **missing** from this array._

**Example 1:**

**Input:** arr = \[2,3,4,7,11\], k = 5
**Output:** 9
**Explanation:** The missing positive integers are \[1,5,6,8,9,10,12,13,...\]. The 5th missing positive integer is 9.

**Example 2:**

**Input:** arr = \[1,2,3,4\], k = 2
**Output:** 6
**Explanation:** The missing positive integers are \[5,6,7,...\]. The 2nd missing positive integer is 6.

**Constraints:**

*   `1 <= arr.length <= 1000`
*   `1 <= arr[i] <= 1000`
*   `1 <= k <= 1000`
*   `arr[i] < arr[j]` for `1 <= i < j <= arr.length`

**Follow up:**

Could you solve this problem in less than O(n) complexity?

## A solution in Java

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

public List<Integer> findDiagonalOrder(List<List<Integer>> nums) {
    List<Integer> res = new ArrayList<>();
    int m = nums.size();
    HashMap<Integer, List<Integer>> diagonals = new HashMap<>();

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < nums.get(i).size(); j++) {
            int key = i + j;
            if (!diagonals.containsKey(key)) {
                diagonals.put(key, new ArrayList<>());
            }
            diagonals.get(key).add(nums.get(i).get(j));
        }
    }

    for (int key : diagonals.keySet()) {
        List<Integer> diag = diagonals.get(key);
        Collections.reverse(diag);
        res.addAll(diag);
    }

    return res;
}
```
First, we iterate through the 2D array nums using nested loops over `i` and `j`. At each loop iteration, we insert the current element nums[i][j] into diagonals[i + j] list for a specific diagonal associated with (i + j). If the list doesn't exist, we create it.

Then, we iterate through the diagonals and reverse the order of each diagonal list because elements with larger row index should come first in the result. We use `std::reverse()` in C++, `Collections.reverse()` in Java, `reversed()` in Python, and `Array.prototype.reverse()` in JavaScript.

Finally, we concatenate the reversed diagonal lists to form the result array using `std::vector::insert()` in C++, `List.addAll()` in Java, `list.extend()` in Python, and by using the spread operator (`...`) in JavaScript.

## A solution in C++

```cpp
#include <vector>

std::vector<int> findDiagonalOrder(std::vector<std::vector<int>>& nums) {
    std::vector<int> res;
    int m = nums.size();
    std::map<int, std::vector<int>> diagonals;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < nums[i].size(); j++) {
            diagonals[i + j].push_back(nums[i][j]);
        }
    }

    for (auto& diag : diagonals) {
        std::reverse(diag.second.begin(), diag.second.end());
        res.insert(res.end(), diag.second.begin(), diag.second.end());
    }

    return res;
}
```
First, we iterate through the 2D array nums using nested loops over `i` and `j`. At each loop iteration, we insert the current element nums[i][j] into diagonals[i + j] list for a specific diagonal associated with (i + j). If the list doesn't exist, we create it.

Then, we iterate through the diagonals and reverse the order of each diagonal list because elements with larger row index should come first in the result. We use `std::reverse()` in C++, `Collections.reverse()` in Java, `reversed()` in Python, and `Array.prototype.reverse()` in JavaScript.

Finally, we concatenate the reversed diagonal lists to form the result array using `std::vector::insert()` in C++, `List.addAll()` in Java, `list.extend()` in Python, and by using the spread operator (`...`) in JavaScript.

## A solution in Python

```python
def find_diagonal_order(nums):
    diagonals = {}
    for i in range(len(nums)):
        for j in range(len(nums[i])):
            if i + j not in diagonals:
                diagonals[i + j] = []
            diagonals[i + j].append(nums[i][j])

    res = []
    for key in diagonals:
        res.extend(reversed(diagonals[key]))

    return res
```
First, we iterate through the 2D array nums using nested loops over `i` and `j`. At each loop iteration, we insert the current element nums[i][j] into diagonals[i + j] list for a specific diagonal associated with (i + j). If the list doesn't exist, we create it.

Then, we iterate through the diagonals and reverse the order of each diagonal list because elements with larger row index should come first in the result. We use `std::reverse()` in C++, `Collections.reverse()` in Java, `reversed()` in Python, and `Array.prototype.reverse()` in JavaScript.

Finally, we concatenate the reversed diagonal lists to form the result array using `std::vector::insert()` in C++, `List.addAll()` in Java, `list.extend()` in Python, and by using the spread operator (`...`) in JavaScript.

## A solution in Javascript

```javascript
function findDiagonalOrder(nums) {
    const diagonals = {};
    const m = nums.length;
    const res = [];

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < nums[i].length; j++) {
            if (!diagonals[i + j]) {
                diagonals[i + j] = [];
            }
            diagonals[i + j].push(nums[i][j]);
        }
    }

    for (const key in diagonals) {
        res.push(...diagonals[key].reverse());
    }

    return res;
}
```
First, we iterate through the 2D array nums using nested loops over `i` and `j`. At each loop iteration, we insert the current element nums[i][j] into diagonals[i + j] list for a specific diagonal associated with (i + j). If the list doesn't exist, we create it.

Then, we iterate through the diagonals and reverse the order of each diagonal list because elements with larger row index should come first in the result. We use `std::reverse()` in C++, `Collections.reverse()` in Java, `reversed()` in Python, and `Array.prototype.reverse()` in JavaScript.

Finally, we concatenate the reversed diagonal lists to form the result array using `std::vector::insert()` in C++, `List.addAll()` in Java, `list.extend()` in Python, and by using the spread operator (`...`) in JavaScript.


# Can Convert String in K Moves

- slug: can-convert-string-in-k-moves
- difficulty: Medium

Given two strings `s` and `t`, your goal is to convert `s` into `t` in `k` moves or less.

During the `ith` (`1 <= i <= k`) move you can:

*   Choose any index `j` (1-indexed) from `s`, such that `1 <= j <= s.length` and `j` has not been chosen in any previous move, and shift the character at that index `i` times.
*   Do nothing.

Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that `'z'` becomes `'a'`). Shifting a character by `i` means applying the shift operations `i` times.

Remember that any index `j` can be picked at most once.

Return `true` if it's possible to convert `s` into `t` in no more than `k` moves, otherwise return `false`.

**Example 1:**

**Input:** s =  "input ", t =  "ouput ", k = 9
**Output:** true
**Explanation:** In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.

**Example 2:**

**Input:** s =  "abc ", t =  "bcd ", k = 10
**Output:** false
**Explanation:** We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.

**Example 3:**

**Input:** s =  "aab ", t =  "bbb ", k = 27
**Output:** true
**Explanation:** In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.

**Constraints:**

*   `1 <= s.length, t.length <= 10^5`
*   `0 <= k <= 10^9`
*   `s`, `t` contain only lowercase English letters.

## A solution in Java

```java
public boolean canConvertString(String s, String t, int k) {
    if (s.length() != t.length()) return false;
    int[] count = new int[26];
    for (int i = 0; i < s.length(); i++) {
        int diff = (t.charAt(i) - s.charAt(i) + 26) % 26;
        if (diff > 0) {
            count[diff]++;
        }
    }
    for (int i = 1; i < 26; i++) {
        if (count[i] > 0) {
            if (count[i] * 26 - 26 + i > k) {
                return false;
            }
        }
    }
    return true;
}
```
First, we check if the lengths of s and t are equal, if not then we return false. Then, we create an array named count with a size of 26 (the number of lowercase English letters) and initialize all its elements to 0. We iterate through the characters of both s and t and calculate the difference between the corresponding characters that need shifting to be equal. We increment the count of that difference by 1. Finally, we iterate through the count array, and for every element with a count greater than 0, we check if it's possible to make the needed shifts with the given number k. If it's not possible, we return false. If we pass through all the elements, then we return true as it's possible to convert s to t with the given number of moves k.

## A solution in C++

```cpp
bool canConvertString(string s, string t, int k) {
    if (s.length() != t.length()) return false;
    vector<int> count(26, 0);
    for (int i = 0; i < s.length(); i++) {
        int diff = (t[i] - s[i] + 26) % 26;
        if (diff > 0) {
            count[diff]++;
        }
    }
    for (int i = 1; i < 26; i++) {
        if (count[i] > 0) {
            if (count[i] * 26 - 26 + i > k) {
                return false;
            }
        }
    }
    return true;
}
```
First, we check if the lengths of s and t are equal, if not then we return false. Then, we create an array named count with a size of 26 (the number of lowercase English letters) and initialize all its elements to 0. We iterate through the characters of both s and t and calculate the difference between the corresponding characters that need shifting to be equal. We increment the count of that difference by 1. Finally, we iterate through the count array, and for every element with a count greater than 0, we check if it's possible to make the needed shifts with the given number k. If it's not possible, we return false. If we pass through all the elements, then we return true as it's possible to convert s to t with the given number of moves k.

## A solution in Python

```python
def canConvertString(s: str, t: str, k: int) -> bool:
    if len(s) != len(t):
        return False
    count = [0] * 26
    for i in range(len(s)):
        diff = (ord(t[i]) - ord(s[i]) + 26) % 26
        if diff > 0:
            count[diff] += 1
    for i in range(1, 26):
        if count[i] > 0:
            if count[i] * 26 - 26 + i > k:
                return False
    return True
```
First, we check if the lengths of s and t are equal, if not then we return false. Then, we create an array named count with a size of 26 (the number of lowercase English letters) and initialize all its elements to 0. We iterate through the characters of both s and t and calculate the difference between the corresponding characters that need shifting to be equal. We increment the count of that difference by 1. Finally, we iterate through the count array, and for every element with a count greater than 0, we check if it's possible to make the needed shifts with the given number k. If it's not possible, we return false. If we pass through all the elements, then we return true as it's possible to convert s to t with the given number of moves k.

## A solution in Javascript

```javascript
function canConvertString(s, t, k) {
    if (s.length !== t.length) return false;
    const count = new Array(26).fill(0);
    for (let i = 0; i < s.length; i++) {
        const diff = (t.charCodeAt(i) - s.charCodeAt(i) + 26) % 26;
        if (diff > 0) {
            count[diff]++;
        }
    }
    for (let i = 1; i < 26; i++) {
        if (count[i] > 0) {
            if (count[i] * 26 - 26 + i > k) {
                return false;
            }
        }
    }
    return true;
}
```
First, we check if the lengths of s and t are equal, if not then we return false. Then, we create an array named count with a size of 26 (the number of lowercase English letters) and initialize all its elements to 0. We iterate through the characters of both s and t and calculate the difference between the corresponding characters that need shifting to be equal. We increment the count of that difference by 1. Finally, we iterate through the count array, and for every element with a count greater than 0, we check if it's possible to make the needed shifts with the given number k. If it's not possible, we return false. If we pass through all the elements, then we return true as it's possible to convert s to t with the given number of moves k.


# Minimum Insertions to Balance a Parentheses String

- slug: minimum-insertions-to-balance-a-parentheses-string
- difficulty: Medium

Given a parentheses string `s` containing only the characters `'('` and `')'`. A parentheses string is **balanced** if:

*   Any left parenthesis `'('` must have a corresponding two consecutive right parenthesis `'))'`.
*   Left parenthesis `'('` must go before the corresponding two consecutive right parenthesis `'))'`.

In other words, we treat `'('` as an opening parenthesis and `'))'` as a closing parenthesis.

*   For example, `"()) "`, `"())(()))) "` and `"(())()))) "` are balanced, `")() "`, `"())) "` and `"(())) "` are not balanced.

You can insert the characters `'('` and `')'` at any position of the string to balance it if needed.

Return _the minimum number of insertions_ needed to make `s` balanced.

**Example 1:**

**Input:** s =  "(())) "
**Output:** 1
**Explanation:** The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be  "(()))) " which is balanced.

**Example 2:**

**Input:** s =  "()) "
**Output:** 0
**Explanation:** The string is already balanced.

**Example 3:**

**Input:** s =  "))())( "
**Output:** 3
**Explanation:** Add '(' to match the first '))', Add '))' to match the last '('.

**Constraints:**

*   `1 <= s.length <= 105`
*   `s` consists of `'('` and `')'` only.

## A solution in Java

```java
public int minInsertions(String s) {
    int left = 0, res = 0;
    int n = s.length();
    for (int i = 0; i < n; i++) {
        if (s.charAt(i) == '(') {
            left++;
        } else {
            if (left == 0) res++;
            else left--;
            if (i == n - 1 || s.charAt(i + 1) != ')') {
                res++;
                i++;
            }
        }
    }
    return res + left * 2;
}
```
The algorithm iterates through the string and maintains a counter `left` for open parentheses that have not been closed yet. Whenever a close parenthesis is encountered, it checks if there is an open parenthesis which has not been closed yet.

1. If yes, decrement the `left` counter.
2. If no, then increment the `res` counter, because we need to insert an open parenthesis.

For the given rules, every close parenthesis should be followed by another close parenthesis to make it balanced. Therefore, if the current character is a close parenthesis and the next character is not a close parenthesis, increment the `res` counter, because we need to insert a close parenthesis.

Finally, each open parenthesis needs two close parentheses. After the loop, if there are any open parentheses left (which have not been closed yet), add their required number of close parentheses, i.e., `left * 2`, to the `res` counter.

Return the result as the minimum number of insertions required to make the string balanced.

## A solution in C++

```cpp
int minInsertions(string s) {
    int left = 0, res = 0;
    int n = s.length();
    for (int i = 0; i < n; i++) {
        if (s[i] == '(') {
            left++;
        } else {
            if (left == 0) res++;
            else left--;
            if (i == n - 1 || s[i + 1] != ')') {
                res++;
                i++;
            }
        }
    }
    return res + left * 2;
}
```
The algorithm iterates through the string and maintains a counter `left` for open parentheses that have not been closed yet. Whenever a close parenthesis is encountered, it checks if there is an open parenthesis which has not been closed yet.

1. If yes, decrement the `left` counter.
2. If no, then increment the `res` counter, because we need to insert an open parenthesis.

For the given rules, every close parenthesis should be followed by another close parenthesis to make it balanced. Therefore, if the current character is a close parenthesis and the next character is not a close parenthesis, increment the `res` counter, because we need to insert a close parenthesis.

Finally, each open parenthesis needs two close parentheses. After the loop, if there are any open parentheses left (which have not been closed yet), add their required number of close parentheses, i.e., `left * 2`, to the `res` counter.

Return the result as the minimum number of insertions required to make the string balanced.

## A solution in Python

```python
def minInsertions(s: str) -> int:
    left = 0
    res = 0
    n = len(s)
    i = 0
    while i < n:
        if s[i] == '(':
            left += 1
        else:
            if left == 0:
                res += 1
            else:
                left -= 1
            if i == n - 1 or s[i + 1] != ')':
                res += 1
                i += 1
        i += 1
    return res + left * 2
```
The algorithm iterates through the string and maintains a counter `left` for open parentheses that have not been closed yet. Whenever a close parenthesis is encountered, it checks if there is an open parenthesis which has not been closed yet.

1. If yes, decrement the `left` counter.
2. If no, then increment the `res` counter, because we need to insert an open parenthesis.

For the given rules, every close parenthesis should be followed by another close parenthesis to make it balanced. Therefore, if the current character is a close parenthesis and the next character is not a close parenthesis, increment the `res` counter, because we need to insert a close parenthesis.

Finally, each open parenthesis needs two close parentheses. After the loop, if there are any open parentheses left (which have not been closed yet), add their required number of close parentheses, i.e., `left * 2`, to the `res` counter.

Return the result as the minimum number of insertions required to make the string balanced.

## A solution in Javascript

```javascript
function minInsertions(s) {
    let left = 0, res = 0;
    const n = s.length;
    for (let i = 0; i < n; i++) {
        if (s[i] === '(') {
            left++;
        } else {
            if (left === 0) res++;
            else left--;
            if (i === n - 1 || s[i + 1] !== ')') {
                res++;
                i++;
            }
        }
    }
    return res + left * 2;
}
```
The algorithm iterates through the string and maintains a counter `left` for open parentheses that have not been closed yet. Whenever a close parenthesis is encountered, it checks if there is an open parenthesis which has not been closed yet.

1. If yes, decrement the `left` counter.
2. If no, then increment the `res` counter, because we need to insert an open parenthesis.

For the given rules, every close parenthesis should be followed by another close parenthesis to make it balanced. Therefore, if the current character is a close parenthesis and the next character is not a close parenthesis, increment the `res` counter, because we need to insert a close parenthesis.

Finally, each open parenthesis needs two close parentheses. After the loop, if there are any open parentheses left (which have not been closed yet), add their required number of close parentheses, i.e., `left * 2`, to the `res` counter.

Return the result as the minimum number of insertions required to make the string balanced.


# Find Longest Awesome Substring

- slug: find-longest-awesome-substring
- difficulty: Hard

You are given a string `s`. An **awesome** substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it a palindrome.

Return _the length of the maximum length **awesome substring** of_ `s`.

**Example 1:**

**Input:** s =  "3242415 "
**Output:** 5
**Explanation:**  "24241 " is the longest awesome substring, we can form the palindrome  "24142 " with some swaps.

**Example 2:**

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

**Example 3:**

**Input:** s =  "213123 "
**Output:** 6
**Explanation:**  "213123 " is the longest awesome substring, we can form the palindrome  "231132 " with some swaps.

**Constraints:**

*   `1 <= s.length <= 105`
*   `s` consists only of digits.

## A solution in Java

```java
public int maxPower(String s) {
    int maxPower = 0, currentPower = 1;

    for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == s.charAt(i-1)) {
            currentPower++;
        } else {
            maxPower = Math.max(maxPower, currentPower);
            currentPower = 1;
        }
    }

    return Math.max(maxPower, currentPower);
}
```
The given algorithm iterates through the input string `s` and compares the current character with the previous character. If the current character is equal to the previous one, it increments the `currentPower` value. If not, it compares the `maxPower` and `currentPower` values, assigning the maximum value to `maxPower` and resetting the `currentPower` to 1. Once the string has been iterated through, the max power is the maximum of `maxPower` and `currentPower`. This algorithm works in O(n) time complexity, where n is the length of the input string.

## A solution in C++

```cpp
int maxPower(const std::string& s) {
    int maxPower = 0, currentPower = 1;

    for (int i = 1; i < s.length(); ++i) {
        if (s[i] == s[i-1]) {
            currentPower++;
        } else {
            maxPower = std::max(maxPower, currentPower);
            currentPower = 1;
        }
    }

    return std::max(maxPower, currentPower);
}
```
The given algorithm iterates through the input string `s` and compares the current character with the previous character. If the current character is equal to the previous one, it increments the `currentPower` value. If not, it compares the `maxPower` and `currentPower` values, assigning the maximum value to `maxPower` and resetting the `currentPower` to 1. Once the string has been iterated through, the max power is the maximum of `maxPower` and `currentPower`. This algorithm works in O(n) time complexity, where n is the length of the input string.

## A solution in Python

```python
def max_power(s: str) -> int:
    max_power = current_power = 1

    for i in range(1, len(s)):
        if s[i] == s[i-1]:
            current_power += 1
        else:
            max_power = max(max_power, current_power)
            current_power = 1

    return max(max_power, current_power)
```
The given algorithm iterates through the input string `s` and compares the current character with the previous character. If the current character is equal to the previous one, it increments the `currentPower` value. If not, it compares the `maxPower` and `currentPower` values, assigning the maximum value to `maxPower` and resetting the `currentPower` to 1. Once the string has been iterated through, the max power is the maximum of `maxPower` and `currentPower`. This algorithm works in O(n) time complexity, where n is the length of the input string.

## A solution in Javascript

```javascript
function maxPower(s) {
    let maxPower = 0, currentPower = 1;

    for (let i = 1; i < s.length; i++) {
        if (s[i] === s[i-1]) {
            currentPower++;
        } else {
            maxPower = Math.max(maxPower, currentPower);
            currentPower = 1;
        }
    }

    return Math.max(maxPower, currentPower);
}
```
The given algorithm iterates through the input string `s` and compares the current character with the previous character. If the current character is equal to the previous one, it increments the `currentPower` value. If not, it compares the `maxPower` and `currentPower` values, assigning the maximum value to `maxPower` and resetting the `currentPower` to 1. Once the string has been iterated through, the max power is the maximum of `maxPower` and `currentPower`. This algorithm works in O(n) time complexity, where n is the length of the input string.