# Odd String Difference

- slug: odd-string-difference
- difficulty: Easy

You are given an array of equal-length strings `words`. Assume that the length of each string is `n`.

Each string `words[i]` can be converted into a **difference integer array** `difference[i]` of length `n - 1` where `difference[i][j] = words[i][j+1] - words[i][j]` where `0 <= j <= n - 2`. Note that the difference between two letters is the difference between their **positions** in the alphabet i.e. the position of `'a'` is `0`, `'b'` is `1`, and `'z'` is `25`.

*   For example, for the string `"acb "`, the difference integer array is `[2 - 0, 1 - 2] = [2, -1]`.

All the strings in words have the same difference integer array, **except one**. You should find that string.

Return _the string in_ `words` _that has different **difference integer array**._

**Example 1:**

**Input:** words = \[ "adc ", "wzy ", "abc "\]
**Output:**  "abc "
**Explanation:**
- The difference integer array of  "adc " is \[3 - 0, 2 - 3\] = \[3, -1\].
- The difference integer array of  "wzy " is \[25 - 22, 24 - 25\]= \[3, -1\].
- The difference integer array of  "abc " is \[1 - 0, 2 - 1\] = \[1, 1\].
The odd array out is \[1, 1\], so we return the corresponding string,  "abc ".

**Example 2:**

**Input:** words = \[ "aaa ", "bob ", "ccc ", "ddd "\]
**Output:**  "bob "
**Explanation:** All the integer arrays are \[0, 0\] except for  "bob ", which corresponds to \[13, -13\].

**Constraints:**

*   `3 <= words.length <= 100`
*   `n == words[i].length`
*   `2 <= n <= 20`
*   `words[i]` consists of lowercase English letters.

## A solution in Java

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

public String stringWithDifferentDifference(String[] words) {
    List<List<Integer>> diffArrays = new ArrayList<>();
    for (String word : words) {
        diffArrays.add(getDifferenceArray(word));
    }

    int oddArrayIndex = -1;
    for (int i = 1; i < diffArrays.size(); i++) {
        int matchCount = 0;
        for (int j = 0; j < diffArrays.get(i).size(); j++) {
            if (diffArrays.get(0).get(j) == diffArrays.get(i).get(j)) {
                matchCount++;
            }
        }

        if (matchCount == 0) {
            oddArrayIndex = i;
            break;
        }
    }

    return words[oddArrayIndex];
}

private List<Integer> getDifferenceArray(String word) {
    List<Integer> differenceArray = new ArrayList<>();
    for (int i = 1; i < word.length(); i++) {
        differenceArray.add(word.charAt(i) - word.charAt(i - 1));
    }
    return differenceArray;
}
```
The algorithm starts by creating a helper function `getDifferenceArray`, which creates an array containing the differences of consecutive characters in the given string. Then, for each string in the `words` array, I call the helper function to generate difference arrays and store them in a new array `diffArrays`.`

After that, a loop iterates over `diffArrays`, comparing each difference array with the first one in the array (`diffArrays[0]`). If there are no matches at all (meaning it's completely different from the first difference array), I set `oddArrayIndex` to that index and break the loop. Finally, I return the string in the `words` array at the index of `oddArrayIndex`.

## A solution in C++

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

std::string stringWithDifferentDifference(std::vector<std::string>& words) {
    auto getDifferenceArray = [](const std::string& word) {
        std::vector<int> differenceArray;
        for (size_t i = 1; i < word.size(); i++) {
            differenceArray.push_back(word[i] - word[i - 1]);
        }
        return differenceArray;
    };

    std::vector<std::vector<int>> diffArrays;
    for (const auto& word : words) {
        diffArrays.push_back(getDifferenceArray(word));
    }

    int oddArrayIndex = -1;
    for (int i = 1; i < diffArrays.size(); i++) {
        int matchCount = 0;
        for (int j = 0; j < diffArrays[i].size(); j++) {
            if (diffArrays[0][j] == diffArrays[i][j]) {
                matchCount++;
            }
        }

        if (matchCount == 0) {
            oddArrayIndex = i;
            break;
        }
    }

    return words[oddArrayIndex];
}
```
The algorithm starts by creating a helper function `getDifferenceArray`, which creates an array containing the differences of consecutive characters in the given string. Then, for each string in the `words` array, I call the helper function to generate difference arrays and store them in a new array `diffArrays`.`

After that, a loop iterates over `diffArrays`, comparing each difference array with the first one in the array (`diffArrays[0]`). If there are no matches at all (meaning it's completely different from the first difference array), I set `oddArrayIndex` to that index and break the loop. Finally, I return the string in the `words` array at the index of `oddArrayIndex`.

## A solution in Python

```python
def stringWithDifferentDifference(words):
    def get_difference_array(word):
        return [ord(word[i+1]) - ord(word[i]) for i in range(len(word) - 1)]

    diffArrays = [get_difference_array(word) for word in words]

    oddArrayIndex = -1
    for i in range(1, len(diffArrays)):
        matchCount = sum(diffArrays[0][j] == diffArrays[i][j] for j in range(len(diffArrays[i])))
        if matchCount == 0:
            oddArrayIndex = i
            break

    return words[oddArrayIndex]
```
The algorithm starts by creating a helper function `getDifferenceArray`, which creates an array containing the differences of consecutive characters in the given string. Then, for each string in the `words` array, I call the helper function to generate difference arrays and store them in a new array `diffArrays`.`

After that, a loop iterates over `diffArrays`, comparing each difference array with the first one in the array (`diffArrays[0]`). If there are no matches at all (meaning it's completely different from the first difference array), I set `oddArrayIndex` to that index and break the loop. Finally, I return the string in the `words` array at the index of `oddArrayIndex`.

## A solution in Javascript

```javascript
function stringWithDifferentDifference(words) {
    const getDifferenceArray = (word) => {
        const differenceArray = [];
        for (let i = 1; i < word.length; i++) {
            differenceArray.push(word.charCodeAt(i) - word.charCodeAt(i - 1));
        }
        return differenceArray;
    };

    const diffArrays = words.map(getDifferenceArray);

    let oddArrayIndex = -1;
    for (let i = 1; i < diffArrays.length; i++) {
        let matchCount = 0;
        for (let j = 0; j < diffArrays[i].length; j++) {
            if (diffArrays[0][j] == diffArrays[i][j]) {
                matchCount++;
            }
        }

        if (matchCount == 0) {
            oddArrayIndex = i;
            break;
        }
    }

    return words[oddArrayIndex];
}
```
The algorithm starts by creating a helper function `getDifferenceArray`, which creates an array containing the differences of consecutive characters in the given string. Then, for each string in the `words` array, I call the helper function to generate difference arrays and store them in a new array `diffArrays`.`

After that, a loop iterates over `diffArrays`, comparing each difference array with the first one in the array (`diffArrays[0]`). If there are no matches at all (meaning it's completely different from the first difference array), I set `oddArrayIndex` to that index and break the loop. Finally, I return the string in the `words` array at the index of `oddArrayIndex`.


# Words Within Two Edits of Dictionary

- slug: words-within-two-edits-of-dictionary
- difficulty: Medium

You are given two string arrays, `queries` and `dictionary`. All words in each array comprise of lowercase English letters and have the same length.

In one **edit** you can take a word from `queries`, and change any letter in it to any other letter. Find all words from `queries` that, after a **maximum** of two edits, equal some word from `dictionary`.

Return _a list of all words from_ `queries`_,_ _that match with some word from_ `dictionary` _after a maximum of **two edits**_. Return the words in the **same order** they appear in `queries`.

**Example 1:**

**Input:** queries = \[ "word ", "note ", "ants ", "wood "\], dictionary = \[ "wood ", "joke ", "moat "\]
**Output:** \[ "word ", "note ", "wood "\]
**Explanation:**
- Changing the 'r' in  "word " to 'o' allows it to equal the dictionary word  "wood ".
- Changing the 'n' to 'j' and the 't' to 'k' in  "note " changes it to  "joke ".
- It would take more than 2 edits for  "ants " to equal a dictionary word.
-  "wood " can remain unchanged (0 edits) and match the corresponding dictionary word.
Thus, we return \[ "word ", "note ", "wood "\].

**Example 2:**

**Input:** queries = \[ "yes "\], dictionary = \[ "not "\]
**Output:** \[\]
**Explanation:**
Applying any two edits to  "yes " cannot make it equal to  "not ". Thus, we return an empty array.

**Constraints:**

*   `1 <= queries.length, dictionary.length <= 100`
*   `n == queries[i].length == dictionary[j].length`
*   `1 <= n <= 100`
*   All `queries[i]` and `dictionary[j]` are composed of lowercase English letters.

## A solution in Java

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

public int countDifferences(String a, String b) {
    int diff = 0;
    for (int i = 0; i < a.length(); ++i) {
        if (a.charAt(i) != b.charAt(i)) {
            ++diff;
        }
    }
    return diff;
}

public List<String> findMatchingWords(String[] queries, String[] dictionary) {
    ArrayList<String> result = new ArrayList<>();
    for (String query : queries) {
        for (String dictWord : dictionary) {
            if (countDifferences(query, dictWord) <= 2) {
                result.add(query);
                break;
            }
        }
    }
    return result;
}
```
The algorithm works as follows:

1. Define a helper function `countDifferences` that takes in two strings and returns the number of differences between them.
2. Iterate through the `queries` array, and for each word in the `queries` array, iterate through the `dictionary` array.
3. For each pair of query and dictionary words, call `countDifferences` to determine if the number of differences is less than or equal to 2.
4. If the number of differences is less than or equal to 2 for any dictionary word, add the query word to the result list and stop checking for this query.
5. At the end, return the result list that contains all the matching words.

Note that the code will be the same for each language, except for language-specific syntax differences.

## A solution in C++

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

int countDifferences(const std::string& a, const std::string& b) {
    int diff = 0;
    for (int i = 0; i < a.size(); ++i) {
        if (a[i] != b[i]) {
            ++diff;
        }
    }
    return diff;
}

std::vector<std::string> findMatchingWords(const std::vector<std::string>& queries, const std::vector<std::string>& dictionary) {
    std::vector<std::string> result;
    for (const std::string& query : queries) {
        for (const std::string& dictWord : dictionary) {
            if (countDifferences(query, dictWord) <= 2) {
                result.push_back(query);
                break;
            }
        }
    }
    return result;
}
```
The algorithm works as follows:

1. Define a helper function `countDifferences` that takes in two strings and returns the number of differences between them.
2. Iterate through the `queries` array, and for each word in the `queries` array, iterate through the `dictionary` array.
3. For each pair of query and dictionary words, call `countDifferences` to determine if the number of differences is less than or equal to 2.
4. If the number of differences is less than or equal to 2 for any dictionary word, add the query word to the result list and stop checking for this query.
5. At the end, return the result list that contains all the matching words.

Note that the code will be the same for each language, except for language-specific syntax differences.

## A solution in Python

```python
def count_differences(a, b):
    return sum(c1 != c2 for c1, c2 in zip(a, b))

def find_matching_words(queries, dictionary):
    result = []
    for query in queries:
        for dict_word in dictionary:
            if count_differences(query, dict_word) <= 2:
                result.append(query)
                break
    return result
```
The algorithm works as follows:

1. Define a helper function `countDifferences` that takes in two strings and returns the number of differences between them.
2. Iterate through the `queries` array, and for each word in the `queries` array, iterate through the `dictionary` array.
3. For each pair of query and dictionary words, call `countDifferences` to determine if the number of differences is less than or equal to 2.
4. If the number of differences is less than or equal to 2 for any dictionary word, add the query word to the result list and stop checking for this query.
5. At the end, return the result list that contains all the matching words.

Note that the code will be the same for each language, except for language-specific syntax differences.

## A solution in Javascript

```javascript
function countDifferences(a, b) {
    let diff = 0;
    for (let i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) {
            ++diff;
        }
    }
    return diff;
}

function findMatchingWords(queries, dictionary) {
    const result = [];
    for (const query of queries) {
        for (const dictWord of dictionary) {
            if (countDifferences(query, dictWord) <= 2) {
                result.push(query);
                break;
            }
        }
    }
    return result;
}
```
The algorithm works as follows:

1. Define a helper function `countDifferences` that takes in two strings and returns the number of differences between them.
2. Iterate through the `queries` array, and for each word in the `queries` array, iterate through the `dictionary` array.
3. For each pair of query and dictionary words, call `countDifferences` to determine if the number of differences is less than or equal to 2.
4. If the number of differences is less than or equal to 2 for any dictionary word, add the query word to the result list and stop checking for this query.
5. At the end, return the result list that contains all the matching words.

Note that the code will be the same for each language, except for language-specific syntax differences.


# Destroy Sequential Targets

- slug: destroy-sequential-targets
- difficulty: Medium

You are given a **0-indexed** array `nums` consisting of positive integers, representing targets on a number line. You are also given an integer `space`.

You have a machine which can destroy targets. **Seeding** the machine with some `nums[i]` allows it to destroy all targets with values that can be represented as `nums[i] + c * space`, where `c` is any non-negative integer. You want to destroy the **maximum** number of targets in `nums`.

Return _the **minimum value** of_ `nums[i]` _you can seed the machine with to destroy the maximum number of targets._

**Example 1:**

**Input:** nums = \[3,7,8,1,1,5\], space = 2
**Output:** 1
**Explanation:** If we seed the machine with nums\[3\], then we destroy all targets equal to 1,3,5,7,9,...
In this case, we would destroy 5 total targets (all except for nums\[2\]).
It is impossible to destroy more than 5 targets, so we return nums\[3\].

**Example 2:**

**Input:** nums = \[1,3,5,2,4,6\], space = 2
**Output:** 1
**Explanation:** Seeding the machine with nums\[0\], or nums\[3\] destroys 3 targets.
It is not possible to destroy more than 3 targets.
Since nums\[0\] is the minimal integer that can destroy 3 targets, we return 1.

**Example 3:**

**Input:** nums = \[6,2,5\], space = 100
**Output:** 2
**Explanation:** Whatever initial seed we select, we can only destroy 1 target. The minimal seed is nums\[1\].

**Constraints:**

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

## A solution in Java

```java
int minSeededValue(int[] nums, int space) {
    Map<Integer, Integer> count = new HashMap<>();
    for (int num : nums) {
        count.put(num % space, count.getOrDefault(num % space, 0) + 1);
    }
    return Collections.max(count.entrySet(), (a, b) -> {
            if (a.getValue() < b.getValue()) {
                return -1;
            } else if (a.getValue() > b.getValue()) {
                return 1;
            } else { // a.getValue() == b.getValue()
                return Integer.compare(b.getKey(), a.getKey());
            }
        }).getKey();
}
```
The algorithm consists of the following steps:
1. Iterate over the numbers in the array `nums` and store the remainders obtained when dividing each number by the `space` in a hash map or dictionary, along with their counts.
2. Find the key (i.e., the remainder) in the hash map that has the maximum value for `(count[x], -x)` (in descending order). This corresponds to the largest count, and smallest remainder (breaking ties).
3. Return the key (remainder) with the maximum count and the smallest value.

The hash map/dictionary stores the count of the remainders of each number in the array when divided by `space`. This allows us to efficiently find the largest count of remainders that correspond to a certain `nums[i]`, so the machine can destroy the maximum number of targets.

## A solution in C++

```cpp
int minSeededValue(vector<int> &nums, int space) {
    unordered_map<int, int> count;
    for (int num : nums) {
        count[num % space]++;
    }
    return max_element(count.begin(), count.end(), [](const auto &a, const auto &b) {
        return a.second < b.second || (a.second == b.second && a.first > b.first);
    })->first;
}
```
The algorithm consists of the following steps:
1. Iterate over the numbers in the array `nums` and store the remainders obtained when dividing each number by the `space` in a hash map or dictionary, along with their counts.
2. Find the key (i.e., the remainder) in the hash map that has the maximum value for `(count[x], -x)` (in descending order). This corresponds to the largest count, and smallest remainder (breaking ties).
3. Return the key (remainder) with the maximum count and the smallest value.

The hash map/dictionary stores the count of the remainders of each number in the array when divided by `space`. This allows us to efficiently find the largest count of remainders that correspond to a certain `nums[i]`, so the machine can destroy the maximum number of targets.

## A solution in Python

```python
def minSeededValue(nums, space):
    count = {}
    for num in nums:
        count[num % space] = count.get(num % space, 0) + 1
    return max(count, key=lambda x: (count[x], -x))
```
The algorithm consists of the following steps:
1. Iterate over the numbers in the array `nums` and store the remainders obtained when dividing each number by the `space` in a hash map or dictionary, along with their counts.
2. Find the key (i.e., the remainder) in the hash map that has the maximum value for `(count[x], -x)` (in descending order). This corresponds to the largest count, and smallest remainder (breaking ties).
3. Return the key (remainder) with the maximum count and the smallest value.

The hash map/dictionary stores the count of the remainders of each number in the array when divided by `space`. This allows us to efficiently find the largest count of remainders that correspond to a certain `nums[i]`, so the machine can destroy the maximum number of targets.

## A solution in Javascript

```javascript
function minSeededValue(nums, space) {
    let count = new Map();
    for (const num of nums) {
        count.set(num % space, (count.get(num % space) || 0) + 1);
    }
    return [...count.entries()].reduce((a, b) => {
        if (a[1] < b[1] || (a[1] === b[1] && a[0] > b[0])) {
            return b;
        } else {
            return a;
        }
    })[0];
}
```
The algorithm consists of the following steps:
1. Iterate over the numbers in the array `nums` and store the remainders obtained when dividing each number by the `space` in a hash map or dictionary, along with their counts.
2. Find the key (i.e., the remainder) in the hash map that has the maximum value for `(count[x], -x)` (in descending order). This corresponds to the largest count, and smallest remainder (breaking ties).
3. Return the key (remainder) with the maximum count and the smallest value.

The hash map/dictionary stores the count of the remainders of each number in the array when divided by `space`. This allows us to efficiently find the largest count of remainders that correspond to a certain `nums[i]`, so the machine can destroy the maximum number of targets.


# Next Greater Element IV

- slug: next-greater-element-iv
- difficulty: Hard

You are given a **0-indexed** array of non-negative integers `nums`. For each integer in `nums`, you must find its respective **second greater** integer.

The **second greater** integer of `nums[i]` is `nums[j]` such that:

*   `j > i`
*   `nums[j] > nums[i]`
*   There exists **exactly one** index `k` such that `nums[k] > nums[i]` and `i < k < j`.

If there is no such `nums[j]`, the second greater integer is considered to be `-1`.

*   For example, in the array `[1, 2, 4, 3]`, the second greater integer of `1` is `4`, `2` is `3`, and that of `3` and `4` is `-1`.

Return _an integer array_ `answer`_, where_ `answer[i]` _is the second greater integer of_ `nums[i]`_._

**Example 1:**

**Input:** nums = \[2,4,0,9,6\]
**Output:** \[9,6,6,-1,-1\]
**Explanation:**
0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.
1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.
2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.
3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.
4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.
Thus, we return \[9,6,6,-1,-1\].

**Example 2:**

**Input:** nums = \[3,3\]
**Output:** \[-1,-1\]
**Explanation:**
We return \[-1,-1\] since neither integer has any integer greater than it.

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int[] findSecondGreater(int[] nums) {
    int n = nums.length;
    int[] answer = new int[n];
    Arrays.fill(answer, -1);

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

    return answer;
}
```
1. Initialize an `answer` array of the same length as `nums` with all elements set to -1.
2. Iterate over each element `i` of `nums`. Initialize a variable `k` to -1.
3. Iterate over all remaining elements to the right of `i` using another loop with index `j`.
4. If `nums[j] > nums[i]` and `k == -1`, set `k = j`. If `k != -1`, set `answer[i] = nums[j]` and break the inner loop.
5. Return the `answer` array.

## A solution in C++

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

vector<int> findSecondGreater(const vector<int>& nums) {
    int n = nums.size();
    vector<int> answer(n, -1);
    for (int i = 0; i < n; i++) {
        for (int j = i + 1, k = -1; j < n; j++) {
            if (nums[j] > nums[i]) {
                if (k == -1) {
                    k = j;
                } else {
                    answer[i] = nums[j];
                    break;
                }
            }
        }
    }
    return answer;
}
```
1. Initialize an `answer` array of the same length as `nums` with all elements set to -1.
2. Iterate over each element `i` of `nums`. Initialize a variable `k` to -1.
3. Iterate over all remaining elements to the right of `i` using another loop with index `j`.
4. If `nums[j] > nums[i]` and `k == -1`, set `k = j`. If `k != -1`, set `answer[i] = nums[j]` and break the inner loop.
5. Return the `answer` array.

## A solution in Python

```python
def find_second_greater(nums):
    n = len(nums)
    answer = [-1] * n
    for i in range(n):
        k = -1
        for j in range(i + 1, n):
            if nums[j] > nums[i]:
                if k == -1:
                    k = j
                else:
                    answer[i] = nums[j]
                    break
    return answer
```
1. Initialize an `answer` array of the same length as `nums` with all elements set to -1.
2. Iterate over each element `i` of `nums`. Initialize a variable `k` to -1.
3. Iterate over all remaining elements to the right of `i` using another loop with index `j`.
4. If `nums[j] > nums[i]` and `k == -1`, set `k = j`. If `k != -1`, set `answer[i] = nums[j]` and break the inner loop.
5. Return the `answer` array.

## A solution in Javascript

```javascript
function findSecondGreater(nums) {
    let n = nums.length;
    let answer = new Array(n).fill(-1);

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

    return answer;
}
```
1. Initialize an `answer` array of the same length as `nums` with all elements set to -1.
2. Iterate over each element `i` of `nums`. Initialize a variable `k` to -1.
3. Iterate over all remaining elements to the right of `i` using another loop with index `j`.
4. If `nums[j] > nums[i]` and `k == -1`, set `k = j`. If `k != -1`, set `answer[i] = nums[j]` and break the inner loop.
5. Return the `answer` array.


# Average Value of Even Numbers That Are Divisible by Three

- slug: average-value-of-even-numbers-that-are-divisible-by-three
- difficulty: Easy

Given an integer array `nums` of **positive** integers, return _the average value of all even integers that are divisible by_ `3`_._

Note that the **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.

**Example 1:**

**Input:** nums = \[1,3,6,10,12,15\]
**Output:** 9
**Explanation:** 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.

**Example 2:**

**Input:** nums = \[1,2,4,7,10\]
**Output:** 0
**Explanation:** There is no single number that satisfies the requirement, so return 0.

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `1 <= nums[i] <= 1000`

## A solution in Java

```java
public int averageEvenDivisibleByThree(int[] nums) {
    int sum = 0;
    int count = 0;
    for (int num : nums) {
        if (num % 2 == 0 && num % 3 == 0) {
            sum += num;
            count++;
        }
    }
    return count == 0 ? 0 : sum / count;
}
```
The algorithm iterates through the input array, checking if an element is even (`num % 2 == 0`) and divisible by 3 (`num % 3 == 0`). If the element satisfies both conditions, it is added to the `sum` and the `count` is incremented. After the iteration, if `count` is greater than 0, the average is calculated by dividing the `sum` by `count`. The result is returned as an integer by rounding down the division result in all languages. If `count` is 0, meaning there were no elements that satisfied the conditions, the function returns 0.

## A solution in C++

```cpp
int averageEvenDivisibleByThree(const std::vector<int>& nums) {
    int sum = 0;
    int count = 0;
    for (int num : nums) {
        if (num % 2 == 0 && num % 3 == 0) {
            sum += num;
            count++;
        }
    }
    return count == 0 ? 0 : sum / count;
}
```
The algorithm iterates through the input array, checking if an element is even (`num % 2 == 0`) and divisible by 3 (`num % 3 == 0`). If the element satisfies both conditions, it is added to the `sum` and the `count` is incremented. After the iteration, if `count` is greater than 0, the average is calculated by dividing the `sum` by `count`. The result is returned as an integer by rounding down the division result in all languages. If `count` is 0, meaning there were no elements that satisfied the conditions, the function returns 0.

## A solution in Python

```python
def average_even_divisible_by_three(nums):
    total = 0
    count = 0
    for num in nums:
        if num % 2 == 0 and num % 3 == 0:
            total += num
            count += 1
    return total // count if count > 0 else 0
```
The algorithm iterates through the input array, checking if an element is even (`num % 2 == 0`) and divisible by 3 (`num % 3 == 0`). If the element satisfies both conditions, it is added to the `sum` and the `count` is incremented. After the iteration, if `count` is greater than 0, the average is calculated by dividing the `sum` by `count`. The result is returned as an integer by rounding down the division result in all languages. If `count` is 0, meaning there were no elements that satisfied the conditions, the function returns 0.

## A solution in Javascript

```javascript
function averageEvenDivisibleByThree(nums) {
    let sum = 0;
    let count = 0;
    for (let num of nums) {
        if (num % 2 === 0 && num % 3 === 0) {
            sum += num;
            count++;
        }
    }
    return count === 0 ? 0 : Math.floor(sum / count);
}
```
The algorithm iterates through the input array, checking if an element is even (`num % 2 == 0`) and divisible by 3 (`num % 3 == 0`). If the element satisfies both conditions, it is added to the `sum` and the `count` is incremented. After the iteration, if `count` is greater than 0, the average is calculated by dividing the `sum` by `count`. The result is returned as an integer by rounding down the division result in all languages. If `count` is 0, meaning there were no elements that satisfied the conditions, the function returns 0.


# Most Popular Video Creator

- slug: most-popular-video-creator
- difficulty: Medium

You are given two string arrays `creators` and `ids`, and an integer array `views`, all of length `n`. The `ith` video on a platform was created by `creator[i]`, has an id of `ids[i]`, and has `views[i]` views.

The **popularity** of a creator is the **sum** of the number of views on **all** of the creator's videos. Find the creator with the **highest** popularity and the id of their **most** viewed video.

*   If multiple creators have the highest popularity, find all of them.
*   If multiple videos have the highest view count for a creator, find the lexicographically **smallest** id.

Return _a 2D array of strings_ `answer` _where_ `answer[i] = [creatori, idi]` _means that_ `creatori` _has the **highest** popularity and_ `idi` _is the id of their most popular video._ The answer can be returned in any order.

**Example 1:**

**Input:** creators = \[ "alice ", "bob ", "alice ", "chris "\], ids = \[ "one ", "two ", "three ", "four "\], views = \[5,10,5,4\]
**Output:** \[\[ "alice ", "one "\],\[ "bob ", "two "\]\]
**Explanation:**
The popularity of alice is 5 + 5 = 10.
The popularity of bob is 10.
The popularity of chris is 4.
alice and bob are the most popular creators.
For bob, the video with the highest view count is  "two ".
For alice, the videos with the highest view count are  "one " and  "three ". Since  "one " is lexicographically smaller than  "three ", it is included in the answer.

**Example 2:**

**Input:** creators = \[ "alice ", "alice ", "alice "\], ids = \[ "a ", "b ", "c "\], views = \[1,2,2\]
**Output:** \[\[ "alice ", "b "\]\]
**Explanation:**
The videos with id  "b " and  "c " have the highest view count.
Since  "b " is lexicographically smaller than  "c ", it is included in the answer.

**Constraints:**

*   `n == creators.length == ids.length == views.length`
*   `1 <= n <= 105`
*   `1 <= creators[i].length, ids[i].length <= 5`
*   `creators[i]` and `ids[i]` consist only of lowercase English letters.
*   `0 <= views[i] <= 105`

## A solution in Java

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

public List<List<String>> highestPopularity(String[] creators, String[] ids, int[] views) {
    Map<String, Integer> popularity = new HashMap<>();
    Map<String, Map.Entry<String, Integer>> mostViewed = new HashMap<>();

    for (int i = 0; i < creators.length; i++) {
        popularity.put(creators[i], popularity.getOrDefault(creators[i], 0) + views[i]);
        if (!mostViewed.containsKey(creators[i]) || views[i] > mostViewed.get(creators[i]).getValue()
            || (views[i] == mostViewed.get(creators[i]).getValue() && ids[i].compareTo(mostViewed.get(creators[i]).getKey()) < 0))
        {
            mostViewed.put(creators[i], Map.entry(ids[i], views[i]));
        }
    }

    int maxPopularity = 0;
    for (int value : popularity.values()) maxPopularity = Math.max(maxPopularity, value);

    List<List<String>> result = new ArrayList<>();
    for (Map.Entry<String, Integer> entry : popularity.entrySet()) {
        if (entry.getValue() == maxPopularity) {
            result.add(List.of(entry.getKey(), mostViewed.get(entry.getKey()).getKey()));
        }
    }
    return result;
}
```
1. Create two dictionaries: `popularity` to store the sum of views for each creator, and `most_viewed` to store the id of the most viewed video for each creator.
2. Iterate through the input arrays `creators`, `ids`, and `views`. For each creator, update the total views in `popularity`. After that, update the `most_viewed` dictionary to store the id of the video which has the highest view count. If there are multiple videos with the same view count, store the lexicographically smallest id.
3. Find the max popularity by iterating through the values in the `popularity` dictionary.
4. Initialize an empty list `result` to store the final answer. Iterate through the items in `popularity` dictionary, and if a creator's popularity is equal to the max popularity, append the creator and their most viewed video's id to the `result` list.
5. Return the `result` list.

## A solution in C++

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

std::vector<std::vector<std::string>> highestPopularity(std::vector<std::string>& creators, std::vector<std::string>& ids, std::vector<int>& views) {
    std::unordered_map<std::string, int> popularity;
    std::unordered_map<std::string, std::pair<std::string, int>> most_viewed;
    for(int i = 0; i < creators.size(); i++) {
        popularity[creators[i]] += views[i];
        if (!most_viewed.count(creators[i]) || views[i] > most_viewed[creators[i]].second
            || (views[i] == most_viewed[creators[i]].second && ids[i] < most_viewed[creators[i]].first))
        {
            most_viewed[creators[i]] = {ids[i], views[i]};
        }
    }

    int max_popularity = 0;
    for(auto& [creator, popular] : popularity) {
        max_popularity = std::max(max_popularity, popular);
    }

    std::vector<std::vector<std::string>> result;
    for(auto& [creator, popular] : popularity) {
        if (popular == max_popularity) {
            result.push_back({creator, most_viewed[creator].first});
        }
    }
    return result;
}
```
1. Create two dictionaries: `popularity` to store the sum of views for each creator, and `most_viewed` to store the id of the most viewed video for each creator.
2. Iterate through the input arrays `creators`, `ids`, and `views`. For each creator, update the total views in `popularity`. After that, update the `most_viewed` dictionary to store the id of the video which has the highest view count. If there are multiple videos with the same view count, store the lexicographically smallest id.
3. Find the max popularity by iterating through the values in the `popularity` dictionary.
4. Initialize an empty list `result` to store the final answer. Iterate through the items in `popularity` dictionary, and if a creator's popularity is equal to the max popularity, append the creator and their most viewed video's id to the `result` list.
5. Return the `result` list.

## A solution in Python

```python
from collections import defaultdict

def highest_popularity(creators, ids, views):
    popularity = defaultdict(int)
    most_viewed = {}

    for i in range(len(creators)):
        popularity[creators[i]] += views[i]
        if creators[i] not in most_viewed or views[i] > most_viewed[creators[i]][1] or (views[i] == most_viewed[creators[i]][1] and ids[i] < most_viewed[creators[i]][0]):
            most_viewed[creators[i]] = (ids[i], views[i])

    max_popularity = max(popularity.values())

    return [[creator, most_viewed[creator][0]] for creator, pop in popularity.items() if pop == max_popularity]
```
1. Create two dictionaries: `popularity` to store the sum of views for each creator, and `most_viewed` to store the id of the most viewed video for each creator.
2. Iterate through the input arrays `creators`, `ids`, and `views`. For each creator, update the total views in `popularity`. After that, update the `most_viewed` dictionary to store the id of the video which has the highest view count. If there are multiple videos with the same view count, store the lexicographically smallest id.
3. Find the max popularity by iterating through the values in the `popularity` dictionary.
4. Initialize an empty list `result` to store the final answer. Iterate through the items in `popularity` dictionary, and if a creator's popularity is equal to the max popularity, append the creator and their most viewed video's id to the `result` list.
5. Return the `result` list.

## A solution in Javascript

```javascript
function highestPopularity(creators, ids, views) {
    const popularity = {};
    const mostViewed = {};

    for (let i = 0; i < creators.length; i++) {
        const creator = creators[i];
        const id = ids[i];
        const view = views[i];

        popularity[creator] = (popularity[creator] || 0) + view;
        if (!mostViewed[creator] || view > mostViewed[creator].view
            || (view === mostViewed[creator].view && id < mostViewed[creator].id))
        {
            mostViewed[creator] = { id, view };
        }
    }

    const maxPopularity = Math.max(...Object.values(popularity));

    const result = [];
    for (const [creator, value] of Object.entries(popularity)) {
        if (value === maxPopularity) {
            result.push([creator, mostViewed[creator].id]);
        }
    }
    return result;
}
```
1. Create two dictionaries: `popularity` to store the sum of views for each creator, and `most_viewed` to store the id of the most viewed video for each creator.
2. Iterate through the input arrays `creators`, `ids`, and `views`. For each creator, update the total views in `popularity`. After that, update the `most_viewed` dictionary to store the id of the video which has the highest view count. If there are multiple videos with the same view count, store the lexicographically smallest id.
3. Find the max popularity by iterating through the values in the `popularity` dictionary.
4. Initialize an empty list `result` to store the final answer. Iterate through the items in `popularity` dictionary, and if a creator's popularity is equal to the max popularity, append the creator and their most viewed video's id to the `result` list.
5. Return the `result` list.


# Minimum Addition to Make Integer Beautiful

- slug: minimum-addition-to-make-integer-beautiful
- difficulty: Medium

You are given two positive integers `n` and `target`.

An integer is considered **beautiful** if the sum of its digits is less than or equal to `target`.

Return the _minimum **non-negative** integer_ `x` _such that_ `n + x` _is beautiful_. The input will be generated such that it is always possible to make `n` beautiful.

**Example 1:**

**Input:** n = 16, target = 6
**Output:** 4
**Explanation:** Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4.

**Example 2:**

**Input:** n = 467, target = 6
**Output:** 33
**Explanation:** Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33.

**Example 3:**

**Input:** n = 1, target = 1
**Output:** 0
**Explanation:** Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.

**Constraints:**

*   `1 <= n <= 1012`
*   `1 <= target <= 150`
*   The input will be generated such that it is always possible to make `n` beautiful.

## A solution in Java

```java
public int digitSum(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

public int minimumBeautiful(int n, int target) {
    int x = 0;
    while (digitSum(n + x) > target) {
        ++x;
    }
    return x;
}
```
The algorithm contains two main parts: calculating the digit sum and finding the minimum non-negative integer x. The digit sum can be calculated by successively dividing the input number by 10, taking the remainder, and adding it to the sum. We can then increment x until the digit sum of n + x is less than or equal to the target value. The functions minimumBeautiful (for C++, Java, and JavaScript) or minimum_beautiful (for Python) handle this calculation and return the final value of x.

## A solution in C++

```cpp
int digitSum(int n) {
    int sum = 0;
    while (n) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

int minimumBeautiful(int n, int target) {
    int x = 0;
    while (digitSum(n + x) > target) {
        ++x;
    }
    return x;
}
```
The algorithm contains two main parts: calculating the digit sum and finding the minimum non-negative integer x. The digit sum can be calculated by successively dividing the input number by 10, taking the remainder, and adding it to the sum. We can then increment x until the digit sum of n + x is less than or equal to the target value. The functions minimumBeautiful (for C++, Java, and JavaScript) or minimum_beautiful (for Python) handle this calculation and return the final value of x.

## A solution in Python

```python
def digit_sum(n):
    return sum(int(digit) for digit in str(n))

def minimum_beautiful(n, target):
    x = 0
    while digit_sum(n + x) > target:
        x += 1
    return x
```
The algorithm contains two main parts: calculating the digit sum and finding the minimum non-negative integer x. The digit sum can be calculated by successively dividing the input number by 10, taking the remainder, and adding it to the sum. We can then increment x until the digit sum of n + x is less than or equal to the target value. The functions minimumBeautiful (for C++, Java, and JavaScript) or minimum_beautiful (for Python) handle this calculation and return the final value of x.

## A solution in Javascript

```javascript
function digitSum(n) {
    return n.toString().split('').reduce((sum, digit) => sum + parseInt(digit), 0);
}

function minimumBeautiful(n, target) {
    let x = 0;
    while (digitSum(n + x) > target) {
        ++x;
    }
    return x;
}
```
The algorithm contains two main parts: calculating the digit sum and finding the minimum non-negative integer x. The digit sum can be calculated by successively dividing the input number by 10, taking the remainder, and adding it to the sum. We can then increment x until the digit sum of n + x is less than or equal to the target value. The functions minimumBeautiful (for C++, Java, and JavaScript) or minimum_beautiful (for Python) handle this calculation and return the final value of x.


# Height of Binary Tree After Subtree Removal Queries

- slug: height-of-binary-tree-after-subtree-removal-queries
- difficulty: Hard

You are given the `root` of a **binary tree** with `n` nodes. Each node is assigned a unique value from `1` to `n`. You are also given an array `queries` of size `m`.

You have to perform `m` **independent** queries on the tree where in the `ith` query you do the following:

*   **Remove** the subtree rooted at the node with the value `queries[i]` from the tree. It is **guaranteed** that `queries[i]` will **not** be equal to the value of the root.

Return _an array_ `answer` _of size_ `m` _where_ `answer[i]` _is the height of the tree after performing the_ `ith` _query_.

**Note**:

*   The queries are independent, so the tree returns to its **initial** state after each query.
*   The height of a tree is the **number of edges in the longest simple path** from the root to some node in the tree.

**Example 1:**

**Input:** root = \[1,3,4,2,null,6,5,null,null,null,null,null,7\], queries = \[4\]
**Output:** \[2\]
**Explanation:** The diagram above shows the tree after removing the subtree rooted at node with value 4.
The height of the tree is 2 (The path 1 -> 3 -> 2).

**Example 2:**

**Input:** root = \[5,8,9,2,1,3,7,4,6\], queries = \[3,2,4,8\]
**Output:** \[3,2,3,2\]
**Explanation:** We have the following queries:
- Removing the subtree rooted at node with value 3. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 4).
- Removing the subtree rooted at node with value 2. The height of the tree becomes 2 (The path 5 -> 8 -> 1).
- Removing the subtree rooted at node with value 4. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 6).
- Removing the subtree rooted at node with value 8. The height of the tree becomes 2 (The path 5 -> 9 -> 3).

**Constraints:**

*   The number of nodes in the tree is `n`.
*   `2 <= n <= 105`
*   `1 <= Node.val <= n`
*   All the values in the tree are **unique**.
*   `m == queries.length`
*   `1 <= m <= min(n, 104)`
*   `1 <= queries[i] <= n`
*   `queries[i] != root.val`

## A solution in Java

```java
// Definition for a binary tree node.
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public int[] removeSubtrees(TreeNode root, int[] queries) {
        int[] answer = new int[queries.length];

        for (int i = 0; i < queries.length; ++i) {
            removeSubtree(root, queries[i]);
            answer[i] = findHeight(root);
        }

        return answer;
    }

    public void removeSubtree(TreeNode node, int val) {
        if (node == null) return;

        if (node.left != null && node.left.val == val)
            node.left = null;
        else
            removeSubtree(node.left, val);

        if (node.right != null && node.right.val == val)
            node.right = null;
        else
            removeSubtree(node.right, val);
    }

    public int findHeight(TreeNode node) {
        if (node == null) return -1;

        return 1 + Math.max(findHeight(node.left), findHeight(node.right));
    }
}
```
The algorithm works as follows:
1. Iterate through the queries independently - for each query:
   a. Call the `removeSubtree` function, which searches for the node with the value equal to the current query and sets its reference in the parent node to null.
   b. Call the `findHeight` function, which calculates the height of the (modified) tree using a recursive approach.
   c. Add the height of the (modified) tree to the `answer` list/array.
2. Return the `answer` list/array.

## A solution in C++

```cpp
// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<int> removeSubtrees(TreeNode* root, vector<int>& queries) {
        vector<int> answer(queries.size());

        for (int i = 0; i < queries.size(); ++i) {
            removeSubtree(root, queries[i]);
            answer[i] = findHeight(root);
        }

        return answer;
    }

    void removeSubtree(TreeNode* node, int val) {
        if (node == nullptr) return;

        if (node->left && node->left->val == val)
            node->left = nullptr;
        else
            removeSubtree(node->left, val);

        if (node->right && node->right->val == val)
            node->right = nullptr;
        else
            removeSubtree(node->right, val);
    }

    int findHeight(TreeNode* node) {
        if (node == nullptr) return -1;

        return 1 + max(findHeight(node->left), findHeight(node->right));
    }
};
```
The algorithm works as follows:
1. Iterate through the queries independently - for each query:
   a. Call the `removeSubtree` function, which searches for the node with the value equal to the current query and sets its reference in the parent node to null.
   b. Call the `findHeight` function, which calculates the height of the (modified) tree using a recursive approach.
   c. Add the height of the (modified) tree to the `answer` list/array.
2. Return the `answer` list/array.

## A solution in Python

```python
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x: int):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def removeSubtrees(self, root: TreeNode, queries: List[int]) -> List[int]:
        def removeSubtree(node: TreeNode, val: int):
            if not node: return

            if node.left and node.left.val == val:
                node.left = None
            else:
                removeSubtree(node.left, val)

            if node.right and node.right.val == val:
                node.right = None
            else:
                removeSubtree(node.right, val)

        def findHeight(node: TreeNode) -> int:
            if not node: return -1

            return 1 + max(findHeight(node.left), findHeight(node.right))

        answer = []
        for query in queries:
            removeSubtree(root, query)
            answer.append(findHeight(root))

        return answer
```
The algorithm works as follows:
1. Iterate through the queries independently - for each query:
   a. Call the `removeSubtree` function, which searches for the node with the value equal to the current query and sets its reference in the parent node to null.
   b. Call the `findHeight` function, which calculates the height of the (modified) tree using a recursive approach.
   c. Add the height of the (modified) tree to the `answer` list/array.
2. Return the `answer` list/array.

## A solution in Javascript

```javascript
// Definition for a binary tree node.
function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val);
    this.left = (left === undefined ? null : left);
    this.right = (right === undefined ? null : right);
}

/**
 * @param {TreeNode} root
 * @param {number[]} queries
 * @return {number[]}
 */
var removeSubtrees = function(root, queries) {
    const removeSubtree = (node, val) => {
        if (!node) return;

        if (node.left && node.left.val === val) {
            node.left = null;
        } else {
            removeSubtree(node.left, val);
        }

        if (node.right && node.right.val === val) {
            node.right = null;
        } else {
            removeSubtree(node.right, val);
        }
    };

    const findHeight = (node) => {
        if (!node) return -1;

        return 1 + Math.max(findHeight(node.left), findHeight(node.right));
    };

    const answer = [];
    for (const query of queries) {
        removeSubtree(root, query);
        answer.push(findHeight(root));
    }

    return answer;
};
```
The algorithm works as follows:
1. Iterate through the queries independently - for each query:
   a. Call the `removeSubtree` function, which searches for the node with the value equal to the current query and sets its reference in the parent node to null.
   b. Call the `findHeight` function, which calculates the height of the (modified) tree using a recursive approach.
   c. Add the height of the (modified) tree to the `answer` list/array.
2. Return the `answer` list/array.


# Sort Array by Moving Items to Empty Space

- slug: sort-array-by-moving-items-to-empty-space
- difficulty: Hard

You are given an integer array `nums` of size `n` containing **each** element from `0` to `n - 1` (**inclusive**). Each of the elements from `1` to `n - 1` represents an item, and the element `0` represents an empty space.

In one operation, you can move **any** item to the empty space. `nums` is considered to be sorted if the numbers of all the items are in **ascending** order and the empty space is either at the beginning or at the end of the array.

For example, if `n = 4`, `nums` is sorted if:

*   `nums = [0,1,2,3]` or
*   `nums = [1,2,3,0]`

...and considered to be unsorted otherwise.

Return _the **minimum** number of operations needed to sort_ `nums`.

**Example 1:**

**Input:** nums = \[4,2,0,3,1\]
**Output:** 3
**Explanation:**
- Move item 2 to the empty space. Now, nums = \[4,0,2,3,1\].
- Move item 1 to the empty space. Now, nums = \[4,1,2,3,0\].
- Move item 4 to the empty space. Now, nums = \[0,1,2,3,4\].
It can be proven that 3 is the minimum number of operations needed.

**Example 2:**

**Input:** nums = \[1,2,3,4,0\]
**Output:** 0
**Explanation:** nums is already sorted so return 0.

**Example 3:**

**Input:** nums = \[1,0,2,4,3\]
**Output:** 2
**Explanation:**
- Move item 2 to the empty space. Now, nums = \[1,2,0,4,3\].
- Move item 3 to the empty space. Now, nums = \[1,2,3,4,0\].
It can be proven that 2 is the minimum number of operations needed.

**Constraints:**

*   `n == nums.length`
*   `2 <= n <= 105`
*   `0 <= nums[i] < n`
*   All the values of `nums` are **unique**.

## A solution in Java

```java
public int min_operations(int[] nums) {
    int n = nums.length;
    int idx0 = -1;

    for(int i = 0; i < n; i++) {
        if(nums[i] == 0) {
            idx0 = i;
            break;
        }
    }

    int cnt1 = 0, cnt2 = 0;

    for(int i = 1; i < n; i++) {
        if(Math.abs(nums[i] - nums[i - 1]) != 1) {
            cnt1 += Math.abs(nums[i] - nums[i - 1]) - 1;
        }
    }

    for(int i = idx0 + 1; i < n; i++) {
        if(nums[i] < nums[i - 1]) {
            cnt2++;
        }
    }

    return Math.min(cnt1, cnt2);
}
```
1. Find the position of the empty space represented by 0, store it in `idx0`
2. Initialize two count variables as `cnt1` and `cnt2` to store the minimum number of operations
3. Iterate through the array and calculate the difference between adjacent elements and increment the count `cnt1` by the difference minus 1.
4. Iterate through a subarray, starting from `idx0 + 1` to the end of the array. If the current element is less than the previous element, increment the count `cnt2`.
5. Return the minimum of `cnt1` and `cnt2`

## A solution in C++

```cpp
int min_operations(vector<int>& nums) {
    int n = nums.size();
    int idx0 = -1;

    for(int i = 0; i < n; i++) {
        if(nums[i] == 0) {
            idx0 = i;
            break;
        }
    }

    int cnt1 = 0, cnt2 = 0;

    for(int i = 1; i < n; i++) {
        if(abs(nums[i] - nums[i - 1]) != 1) {
            cnt1 += abs(nums[i] - nums[i - 1]) - 1;
        }
    }

    for(int i = idx0 + 1; i < n; i++) {
        if(nums[i] < nums[i - 1]) {
            cnt2++;
        }
    }

    return min(cnt1, cnt2);
}
```
1. Find the position of the empty space represented by 0, store it in `idx0`
2. Initialize two count variables as `cnt1` and `cnt2` to store the minimum number of operations
3. Iterate through the array and calculate the difference between adjacent elements and increment the count `cnt1` by the difference minus 1.
4. Iterate through a subarray, starting from `idx0 + 1` to the end of the array. If the current element is less than the previous element, increment the count `cnt2`.
5. Return the minimum of `cnt1` and `cnt2`

## A solution in Python

```python
def min_operations(nums):
    n = len(nums)
    idx0 = -1

    for i in range(n):
        if nums[i] == 0:
            idx0 = i
            break

    cnt1 = 0
    cnt2 = 0

    for i in range(1, n):
        if abs(nums[i] - nums[i - 1]) != 1:
            cnt1 += abs(nums[i] - nums[i - 1]) - 1

    for i in range(idx0 + 1, n):
        if nums[i] < nums[i - 1]:
            cnt2 += 1

    return min(cnt1, cnt2)
```
1. Find the position of the empty space represented by 0, store it in `idx0`
2. Initialize two count variables as `cnt1` and `cnt2` to store the minimum number of operations
3. Iterate through the array and calculate the difference between adjacent elements and increment the count `cnt1` by the difference minus 1.
4. Iterate through a subarray, starting from `idx0 + 1` to the end of the array. If the current element is less than the previous element, increment the count `cnt2`.
5. Return the minimum of `cnt1` and `cnt2`

## A solution in Javascript

```javascript
function min_operations(nums) {
    const n = nums.length;
    let idx0 = -1;

    for (let i = 0; i < n; i++) {
        if (nums[i] === 0) {
            idx0 = i;
            break;
        }
    }

    let cnt1 = 0, cnt2 = 0;

    for (let i = 1; i < n; i++) {
        if (Math.abs(nums[i] - nums[i - 1]) !== 1) {
            cnt1 += Math.abs(nums[i] - nums[i - 1]) - 1;
        }
    }

    for (let i = idx0 + 1; i < n; i++) {
        if (nums[i] < nums[i - 1]) {
            cnt2++;
        }
    }

    return Math.min(cnt1, cnt2);
}
```
1. Find the position of the empty space represented by 0, store it in `idx0`
2. Initialize two count variables as `cnt1` and `cnt2` to store the minimum number of operations
3. Iterate through the array and calculate the difference between adjacent elements and increment the count `cnt1` by the difference minus 1.
4. Iterate through a subarray, starting from `idx0 + 1` to the end of the array. If the current element is less than the previous element, increment the count `cnt2`.
5. Return the minimum of `cnt1` and `cnt2`


# Apply Operations to an Array

- slug: apply-operations-to-an-array
- difficulty: Easy

You are given a **0-indexed** array `nums` of size `n` consisting of **non-negative** integers.

You need to apply `n - 1` operations to this array where, in the `ith` operation (**0-indexed**), you will apply the following on the `ith` element of `nums`:

*   If `nums[i] == nums[i + 1]`, then multiply `nums[i]` by `2` and set `nums[i + 1]` to `0`. Otherwise, you skip this operation.

After performing **all** the operations, **shift** all the `0`'s to the **end** of the array.

*   For example, the array `[1,0,2,0,0,1]` after shifting all its `0`'s to the end, is `[1,2,1,0,0,0]`.

Return _the resulting array_.

**Note** that the operations are applied **sequentially**, not all at once.

**Example 1:**

**Input:** nums = \[1,2,2,1,1,0\]
**Output:** \[1,4,2,0,0,0\]
**Explanation:** We do the following operations:
- i = 0: nums\[0\] and nums\[1\] are not equal, so we skip this operation.
- i = 1: nums\[1\] and nums\[2\] are equal, we multiply nums\[1\] by 2 and change nums\[2\] to 0. The array becomes \[1,**4**,**0**,1,1,0\].
- i = 2: nums\[2\] and nums\[3\] are not equal, so we skip this operation.
- i = 3: nums\[3\] and nums\[4\] are equal, we multiply nums\[3\] by 2 and change nums\[4\] to 0. The array becomes \[1,4,0,**2**,**0**,0\].
- i = 4: nums\[4\] and nums\[5\] are equal, we multiply nums\[4\] by 2 and change nums\[5\] to 0. The array becomes \[1,4,0,2,**0**,**0**\].
After that, we shift the 0's to the end, which gives the array \[1,4,2,0,0,0\].

**Example 2:**

**Input:** nums = \[0,1\]
**Output:** \[1,0\]
**Explanation:** No operation can be applied, we just shift the 0 to the end.

**Constraints:**

*   `2 <= nums.length <= 2000`
*   `0 <= nums[i] <= 1000`

## A solution in Java

```java
public int[] performOps(int[] nums) {
    int n = nums.length;
    for (int i = 0; i < n - 1; ++i) {
        if (nums[i] == nums[i + 1]) {
            nums[i] *= 2;
            nums[i + 1] = 0;
        }
    }
    int nonZeroIndex = 0;
    for (int i = 0; i < n; ++i) {
        if (nums[i] != 0) {
            nums[nonZeroIndex++] = nums[i];
        }
    }
    while (nonZeroIndex < n) {
        nums[nonZeroIndex++] = 0;
    }
    return nums;
}
```
Iterate through the `nums` array from index `0` to `n - 2`.
For each index `i`, check if `nums[i]` equals `nums[i + 1]`. If equal, multiply `nums[i]` by `2` and set `nums[i + 1]` to `0`.
After the operations, shift all `0`'s to the end of the array. To do this, keep track of a `nonZeroIndex` and copy only non-zero elements to that index. Increment the `nonZeroIndex` for every non-zero element copied. Finally, fill the rest of the array with `0`'s starting from the `nonZeroIndex`.

## A solution in C++

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

vector<int> performOps(vector<int>& nums) {
    int n = nums.size();
    for (int i = 0; i < n - 1; ++i) {
        if (nums[i] == nums[i + 1]) {
            nums[i] *= 2;
            nums[i + 1] = 0;
        }
    }
    int nonZeroIndex = 0;
    for (int i = 0; i < n; ++i) {
        if (nums[i] != 0) {
            nums[nonZeroIndex++] = nums[i];
        }
    }
    while (nonZeroIndex < n) {
        nums[nonZeroIndex++] = 0;
    }
    return nums;
}
```
Iterate through the `nums` array from index `0` to `n - 2`.
For each index `i`, check if `nums[i]` equals `nums[i + 1]`. If equal, multiply `nums[i]` by `2` and set `nums[i + 1]` to `0`.
After the operations, shift all `0`'s to the end of the array. To do this, keep track of a `nonZeroIndex` and copy only non-zero elements to that index. Increment the `nonZeroIndex` for every non-zero element copied. Finally, fill the rest of the array with `0`'s starting from the `nonZeroIndex`.

## A solution in Python

```python
def performOps(nums):
    n = len(nums)
    for i in range(n - 1):
        if nums[i] == nums[i + 1]:
            nums[i] *= 2
            nums[i + 1] = 0
    nonZeroIndex = 0
    for i in range(n):
        if nums[i] != 0:
            nums[nonZeroIndex] = nums[i]
            nonZeroIndex += 1
    while(nonZeroIndex < n):
        nums[nonZeroIndex] = 0
        nonZeroIndex += 1
    return nums
```
Iterate through the `nums` array from index `0` to `n - 2`.
For each index `i`, check if `nums[i]` equals `nums[i + 1]`. If equal, multiply `nums[i]` by `2` and set `nums[i + 1]` to `0`.
After the operations, shift all `0`'s to the end of the array. To do this, keep track of a `nonZeroIndex` and copy only non-zero elements to that index. Increment the `nonZeroIndex` for every non-zero element copied. Finally, fill the rest of the array with `0`'s starting from the `nonZeroIndex`.

## A solution in Javascript

```javascript
function performOps(nums) {
    const n = nums.length;
    for (let i = 0; i < n - 1; ++i) {
        if (nums[i] === nums[i + 1]) {
            nums[i] *= 2;
            nums[i + 1] = 0;
        }
    }
    let nonZeroIndex = 0;
    for (let i = 0; i < n; ++i) {
        if (nums[i] !== 0) {
            nums[nonZeroIndex++] = nums[i];
        }
    }
    while(nonZeroIndex < n) {
        nums[nonZeroIndex++] = 0;
    }
    return nums;
}
```
Iterate through the `nums` array from index `0` to `n - 2`.
For each index `i`, check if `nums[i]` equals `nums[i + 1]`. If equal, multiply `nums[i]` by `2` and set `nums[i + 1]` to `0`.
After the operations, shift all `0`'s to the end of the array. To do this, keep track of a `nonZeroIndex` and copy only non-zero elements to that index. Increment the `nonZeroIndex` for every non-zero element copied. Finally, fill the rest of the array with `0`'s starting from the `nonZeroIndex`.


# Maximum Sum of Distinct Subarrays With Length K

- slug: maximum-sum-of-distinct-subarrays-with-length-k
- difficulty: Medium

You are given an integer array `nums` and an integer `k`. Find the maximum subarray sum of all the subarrays of `nums` that meet the following conditions:

*   The length of the subarray is `k`, and
*   All the elements of the subarray are **distinct**.

Return _the maximum subarray sum of all the subarrays that meet the conditions__._ If no subarray meets the conditions, return `0`.

_A **subarray** is a contiguous non-empty sequence of elements within an array._

**Example 1:**

**Input:** nums = \[1,5,4,2,9,9,9\], k = 3
**Output:** 15
**Explanation:** The subarrays of nums with length 3 are:
- \[1,5,4\] which meets the requirements and has a sum of 10.
- \[5,4,2\] which meets the requirements and has a sum of 11.
- \[4,2,9\] which meets the requirements and has a sum of 15.
- \[2,9,9\] which does not meet the requirements because the element 9 is repeated.
- \[9,9,9\] which does not meet the requirements because the element 9 is repeated.
We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions

**Example 2:**

**Input:** nums = \[4,4,4\], k = 3
**Output:** 0
**Explanation:** The subarrays of nums with length 3 are:
- \[4,4,4\] which does not meet the requirements because the element 4 is repeated.
We return 0 because no subarrays meet the conditions.

**Constraints:**

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

## A solution in Java

```java
public int maxSubarraySumWithDistinctElements(int[] nums, int k) {
    int max_sum = 0, window_sum = 0;
    HashMap<Integer, Integer> freq_map = new HashMap<>();

    for (int i = 0; i < nums.length; i++) {
        freq_map.put(nums[i], freq_map.getOrDefault(nums[i], 0) + 1);
        window_sum += nums[i];
        if (i >= k) {
            freq_map.put(nums[i - k], freq_map.get(nums[i - k]) - 1);
            window_sum -= nums[i - k];
        }
        if (i >= k - 1) {
            boolean is_distinct = true;
            for (Integer value : freq_map.values()) {
                if (value > 1) {
                    is_distinct = false;
                    break;
                }
            }
            if (is_distinct) {
                max_sum = Math.max(max_sum, window_sum);
            }
        }
    }
    return max_sum;
}
```
For each language implementation, the algorithm works as follows:
1. Initialize a frequency map to keep track of the number of occurrences of each element in the current window of `k` elements.
2. Iterate through the `nums` array, updating the frequency map and current `window_sum` at each step.
3. If the current index is greater than or equal to `k`, remove the oldest element from the frequency map and `window_sum` to maintain a sliding window of size `k`.
4. If the current index is greater than or equal to `k - 1`, check if all elements in the sliding window are distinct by ensuring no values in the frequency map are greater than 1.
5. If the elements in the sliding window are distinct, update `max_sum` to be the maximum of the current `max_sum` and `window_sum`.
6. After iteration is complete, return the `max_sum`.

This algorithm runs in O(n) time complexity as we iterate through the `nums` array once, and it only checks the values of elements in the frequency map at each step. The space complexity is also O(n) since we may need to store a frequency map for all distinct elements in the `nums` array.

## A solution in C++

```cpp
int maxSubarraySumWithDistinctElements(vector<int>& nums, int k) {
    int max_sum = 0, window_sum = 0;
    unordered_map<int, int> freq_map;

    for (int i = 0; i < nums.size(); i++) {
        freq_map[nums[i]]++;
        window_sum += nums[i];
        if (i >= k) {
            freq_map[nums[i - k]]--;
            window_sum -= nums[i - k];
        }
        if (i >= k - 1) {
            bool is_distinct = true;
            for (const auto& pair : freq_map) {
                if (pair.second > 1) {
                    is_distinct = false;
                    break;
                }
            }
            if (is_distinct) {
                max_sum = max(max_sum, window_sum);
            }
        }
    }
    return max_sum;
}
```
For each language implementation, the algorithm works as follows:
1. Initialize a frequency map to keep track of the number of occurrences of each element in the current window of `k` elements.
2. Iterate through the `nums` array, updating the frequency map and current `window_sum` at each step.
3. If the current index is greater than or equal to `k`, remove the oldest element from the frequency map and `window_sum` to maintain a sliding window of size `k`.
4. If the current index is greater than or equal to `k - 1`, check if all elements in the sliding window are distinct by ensuring no values in the frequency map are greater than 1.
5. If the elements in the sliding window are distinct, update `max_sum` to be the maximum of the current `max_sum` and `window_sum`.
6. After iteration is complete, return the `max_sum`.

This algorithm runs in O(n) time complexity as we iterate through the `nums` array once, and it only checks the values of elements in the frequency map at each step. The space complexity is also O(n) since we may need to store a frequency map for all distinct elements in the `nums` array.

## A solution in Python

```python
def maxSubarraySumWithDistinctElements(nums: List[int], k: int) -> int:
    max_sum = 0
    window_sum = 0
    freq_map = collections.defaultdict(int)

    for i, num in enumerate(nums):
        freq_map[num] += 1
        window_sum += num
        if i >= k:
            freq_map[nums[i - k]] -= 1
            window_sum -= nums[i - k]
        if i >= k - 1:
            is_distinct = all(value <= 1 for value in freq_map.values())
            if is_distinct:
                max_sum = max(max_sum, window_sum)

    return max_sum
```
For each language implementation, the algorithm works as follows:
1. Initialize a frequency map to keep track of the number of occurrences of each element in the current window of `k` elements.
2. Iterate through the `nums` array, updating the frequency map and current `window_sum` at each step.
3. If the current index is greater than or equal to `k`, remove the oldest element from the frequency map and `window_sum` to maintain a sliding window of size `k`.
4. If the current index is greater than or equal to `k - 1`, check if all elements in the sliding window are distinct by ensuring no values in the frequency map are greater than 1.
5. If the elements in the sliding window are distinct, update `max_sum` to be the maximum of the current `max_sum` and `window_sum`.
6. After iteration is complete, return the `max_sum`.

This algorithm runs in O(n) time complexity as we iterate through the `nums` array once, and it only checks the values of elements in the frequency map at each step. The space complexity is also O(n) since we may need to store a frequency map for all distinct elements in the `nums` array.

## A solution in Javascript

```javascript
function maxSubarraySumWithDistinctElements(nums, k) {
    let max_sum = 0, window_sum = 0;
    let freq_map = new Map();

    for (let i = 0; i < nums.length; i++) {
        freq_map.set(nums[i], (freq_map.get(nums[i]) || 0) + 1);
        window_sum += nums[i];
        if (i >= k) {
            freq_map.set(nums[i - k], freq_map.get(nums[i - k]) - 1);
            window_sum -= nums[i - k];
        }
        if (i >= k - 1) {
            let is_distinct = true;
            for (let value of freq_map.values()) {
                if (value > 1) {
                    is_distinct = false;
                    break;
                }
            }
            if (is_distinct) {
                max_sum = Math.max(max_sum, window_sum);
            }
        }
    }
    return max_sum;
}
```
For each language implementation, the algorithm works as follows:
1. Initialize a frequency map to keep track of the number of occurrences of each element in the current window of `k` elements.
2. Iterate through the `nums` array, updating the frequency map and current `window_sum` at each step.
3. If the current index is greater than or equal to `k`, remove the oldest element from the frequency map and `window_sum` to maintain a sliding window of size `k`.
4. If the current index is greater than or equal to `k - 1`, check if all elements in the sliding window are distinct by ensuring no values in the frequency map are greater than 1.
5. If the elements in the sliding window are distinct, update `max_sum` to be the maximum of the current `max_sum` and `window_sum`.
6. After iteration is complete, return the `max_sum`.

This algorithm runs in O(n) time complexity as we iterate through the `nums` array once, and it only checks the values of elements in the frequency map at each step. The space complexity is also O(n) since we may need to store a frequency map for all distinct elements in the `nums` array.


# Total Cost to Hire K Workers

- slug: total-cost-to-hire-k-workers
- difficulty: Medium

You are given a **0-indexed** integer array `costs` where `costs[i]` is the cost of hiring the `ith` worker.

You are also given two integers `k` and `candidates`. We want to hire exactly `k` workers according to the following rules:

*   You will run `k` sessions and hire exactly one worker in each session.
*   In each hiring session, choose the worker with the lowest cost from either the first `candidates` workers or the last `candidates` workers. Break the tie by the smallest index.
    *   For example, if `costs = [3,2,7,7,1,2]` and `candidates = 2`, then in the first hiring session, we will choose the `4th` worker because they have the lowest cost `[3,2,7,7,**1**,2]`.
    *   In the second hiring session, we will choose `1st` worker because they have the same lowest cost as `4th` worker but they have the smallest index `[3,**2**,7,7,2]`. Please note that the indexing may be changed in the process.
*   If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.
*   A worker can only be chosen once.

Return _the total cost to hire exactly_ `k` _workers._

**Example 1:**

**Input:** costs = \[17,12,10,2,7,2,11,20,8\], k = 3, candidates = 4
**Output:** 11
**Explanation:** We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from \[17,12,10,2,7,2,11,20,8\]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.
- In the second hiring round we choose the worker from \[17,12,10,7,2,11,20,8\]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.
- In the third hiring round we choose the worker from \[17,12,10,7,11,20,8\]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.
The total hiring cost is 11.

**Example 2:**

**Input:** costs = \[1,2,4,1\], k = 3, candidates = 3
**Output:** 4
**Explanation:** We hire 3 workers in total. The total cost is initially 0.
- In the first hiring round we choose the worker from \[1,2,4,1\]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.
- In the second hiring round we choose the worker from \[2,4,1\]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.
- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers \[2,4\]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.
The total hiring cost is 4.

**Constraints:**

*   `1 <= costs.length <= 105`
*   `1 <= costs[i] <= 105`
*   `1 <= k, candidates <= costs.length`

## A solution in Java

```java
public int hireWorkers(int[] costs, int k, int candidates) {
    int n = costs.length;
    int[][] workers = new int[n][2];

    for (int i = 0; i < n; ++i) {
        workers[i][0] = costs[i];
        workers[i][1] = i;
    }

    Arrays.sort(workers, (a, b) -> a[0] - b[0]);

    int cost = 0;
    for (int i = 0; i < k; ++i) {
        if (Math.min(workers[i][1], n - workers[i][1] - 1) < candidates) {
            cost += workers[i][0];
        }
    }

    return cost;
}
```
1. Create an array `workers` from `costs` that stores pairs of the cost and its original index (0-based).
2. Sort the `workers` array based on the cost.
3. Iterate over the `workers` array for `k` times and for each iteration, check if the current worker is included in the first or last `candidates` workers. This is done using the index (`min(workers[i][1], n - workers[i][1] - 1) < candidates`). Update the total cost if the current worker is included in the first or last `candidates`.
4. Return the total hiring cost.

*Complexity: O(n log n)* due to the sorting step.

## A solution in C++

```cpp
int hireWorkers(vector<int>& costs, int k, int candidates) {
    int n = costs.size();
    vector<pair<int, int>> workers;
    for (int i = 0; i < n; ++i)
        workers.emplace_back(costs[i], i);
    sort(workers.begin(), workers.end());

    int cost = 0;
    for (int i = 0; i < k; ++i) {
        if (min(workers[i].second, n - workers[i].second - 1) < candidates)
            cost += workers[i].first;
    }
    return cost;
}
```
1. Create an array `workers` from `costs` that stores pairs of the cost and its original index (0-based).
2. Sort the `workers` array based on the cost.
3. Iterate over the `workers` array for `k` times and for each iteration, check if the current worker is included in the first or last `candidates` workers. This is done using the index (`min(workers[i][1], n - workers[i][1] - 1) < candidates`). Update the total cost if the current worker is included in the first or last `candidates`.
4. Return the total hiring cost.

*Complexity: O(n log n)* due to the sorting step.

## A solution in Python

```python
def hireWorkers(costs, k, candidates):
    n = len(costs)
    workers = sorted([(cost, i) for i, cost in enumerate(costs)])

    cost = 0
    for i in range(k):
        if min(workers[i][1], n - workers[i][1] - 1) < candidates:
            cost += workers[i][0]

    return cost
```
1. Create an array `workers` from `costs` that stores pairs of the cost and its original index (0-based).
2. Sort the `workers` array based on the cost.
3. Iterate over the `workers` array for `k` times and for each iteration, check if the current worker is included in the first or last `candidates` workers. This is done using the index (`min(workers[i][1], n - workers[i][1] - 1) < candidates`). Update the total cost if the current worker is included in the first or last `candidates`.
4. Return the total hiring cost.

*Complexity: O(n log n)* due to the sorting step.

## A solution in Javascript

```javascript
function hireWorkers(costs, k, candidates) {
    const n = costs.length;
    const workers = costs
        .map((cost, i) => [cost, i])
        .sort((a, b) => a[0] - b[0]);

    let cost = 0;
    for (let i = 0; i < k; ++i) {
        if (Math.min(workers[i][1], n - workers[i][1] - 1) < candidates) {
            cost += workers[i][0];
        }
    }
    return cost;
}
```
1. Create an array `workers` from `costs` that stores pairs of the cost and its original index (0-based).
2. Sort the `workers` array based on the cost.
3. Iterate over the `workers` array for `k` times and for each iteration, check if the current worker is included in the first or last `candidates` workers. This is done using the index (`min(workers[i][1], n - workers[i][1] - 1) < candidates`). Update the total cost if the current worker is included in the first or last `candidates`.
4. Return the total hiring cost.

*Complexity: O(n log n)* due to the sorting step.


# Minimum Total Distance Traveled

- slug: minimum-total-distance-traveled
- difficulty: Hard

There are some robots and factories on the X-axis. You are given an integer array `robot` where `robot[i]` is the position of the `ith` robot. You are also given a 2D integer array `factory` where `factory[j] = [positionj, limitj]` indicates that `positionj` is the position of the `jth` factory and that the `jth` factory can repair at most `limitj` robots.

The positions of each robot are **unique**. The positions of each factory are also **unique**. Note that a robot can be **in the same position** as a factory initially.

All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.

**At any moment**, you can set the initial direction of moving for **some** robot. Your target is to minimize the total distance traveled by all the robots.

Return _the minimum total distance traveled by all the robots_. The test cases are generated such that all the robots can be repaired.

**Note that**

*   All robots move at the same speed.
*   If two robots move in the same direction, they will never collide.
*   If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other.
*   If a robot passes by a factory that reached its limits, it crosses it as if it does not exist.
*   If the robot moved from a position `x` to a position `y`, the distance it moved is `|y - x|`.

**Example 1:**

**Input:** robot = \[0,4,6\], factory = \[\[2,2\],\[6,2\]\]
**Output:** 4
**Explanation:** As shown in the figure:
- The first robot at position 0 moves in the positive direction. It will be repaired at the first factory.
- The second robot at position 4 moves in the negative direction. It will be repaired at the first factory.
- The third robot at position 6 will be repaired at the second factory. It does not need to move.
The limit of the first factory is 2, and it fixed 2 robots.
The limit of the second factory is 2, and it fixed 1 robot.
The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.

**Example 2:**

**Input:** robot = \[1,-1\], factory = \[\[-2,1\],\[2,1\]\]
**Output:** 2
**Explanation:** As shown in the figure:
- The first robot at position 1 moves in the positive direction. It will be repaired at the second factory.
- The second robot at position -1 moves in the negative direction. It will be repaired at the first factory.
The limit of the first factory is 1, and it fixed 1 robot.
The limit of the second factory is 1, and it fixed 1 robot.
The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.

**Constraints:**

*   `1 <= robot.length, factory.length <= 100`
*   `factory[j].length == 2`
*   `-109 <= robot[i], positionj <= 109`
*   `0 <= limitj <= robot.length`
*   The input will be generated such that it is always possible to repair every robot.

## A solution in Java

```java
public int minTotalDistance(int[] robot, int[][] factory) {
    Arrays.sort(robot);
    Arrays.sort(factory, (a, b) -> a[0] - b[0]);

    int res = 0, idx = 0;
    for (int[] f : factory) {
        int limit = f[1];
        while (limit-- > 0 && idx < robot.length) {
            res += Math.abs(f[0] - robot[idx]);
            idx++;
        }
    }

    return res;
}
```
We sort the `robot` and `factory` arrays in ascending order. We create two variables, `res` to store the result and `idx` to keep track of the current robot index.

We loop through each factory in the sorted `factory` array. For each factory, we have a nested loop to repair the robots. We decrement the `limit` of the current factory and increment the `idx` pointer. We add the distance from the current factory to the robot to the result.

Finally, we return the result `res` which represents the minimum total distance traveled by all the robots.

## A solution in C++

```cpp
int minTotalDistance(vector<int>& robot, vector<vector<int>>& factory) {
    sort(robot.begin(), robot.end());
    sort(factory.begin(), factory.end());

    int res = 0, idx = 0;
    for (const auto& f : factory) {
        int limit = f[1];
        while (limit-- > 0 && idx < robot.size()) {
            res += abs(f[0] - robot[idx]);
            idx++;
        }
    }

    return res;
}
```
We sort the `robot` and `factory` arrays in ascending order. We create two variables, `res` to store the result and `idx` to keep track of the current robot index.

We loop through each factory in the sorted `factory` array. For each factory, we have a nested loop to repair the robots. We decrement the `limit` of the current factory and increment the `idx` pointer. We add the distance from the current factory to the robot to the result.

Finally, we return the result `res` which represents the minimum total distance traveled by all the robots.

## A solution in Python

```python
def min_total_distance(robot: List[int], factory: List[List[int]]) -> int:
    robot.sort()
    factory.sort()

    res = 0
    idx = 0
    for f_pos, f_limit in factory:
        while f_limit > 0 and idx < len(robot):
            res += abs(f_pos - robot[idx])
            idx += 1
            f_limit -= 1

    return res
```
We sort the `robot` and `factory` arrays in ascending order. We create two variables, `res` to store the result and `idx` to keep track of the current robot index.

We loop through each factory in the sorted `factory` array. For each factory, we have a nested loop to repair the robots. We decrement the `limit` of the current factory and increment the `idx` pointer. We add the distance from the current factory to the robot to the result.

Finally, we return the result `res` which represents the minimum total distance traveled by all the robots.

## A solution in Javascript

```javascript
function minTotalDistance(robot, factory) {
    robot.sort((a, b) => a - b);
    factory.sort((a, b) => a[0] - b[0]);

    let res = 0, idx = 0;
    for (const f of factory) {
        let limit = f[1];
        while (limit-- > 0 && idx < robot.length) {
            res += Math.abs(f[0] - robot[idx]);
            idx++;
        }
    }

    return res;
}
```
We sort the `robot` and `factory` arrays in ascending order. We create two variables, `res` to store the result and `idx` to keep track of the current robot index.

We loop through each factory in the sorted `factory` array. For each factory, we have a nested loop to repair the robots. We decrement the `limit` of the current factory and increment the `idx` pointer. We add the distance from the current factory to the robot to the result.

Finally, we return the result `res` which represents the minimum total distance traveled by all the robots.


# Minimum Subarrays in a Valid Split

- slug: minimum-subarrays-in-a-valid-split
- difficulty: Medium

You are given an integer array `nums`.

Splitting of an integer array `nums` into **subarrays** is **valid** if:

*   the _greatest common divisor_ of the first and last elements of each subarray is **greater** than `1`, and
*   each element of `nums` belongs to exactly one subarray.

Return _the **minimum** number of subarrays in a **valid** subarray splitting of_ `nums`. If a valid subarray splitting is not possible, return `-1`.

**Note** that:

*   The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers.
*   A **subarray** is a contiguous non-empty part of an array.

**Example 1:**

**Input:** nums = \[2,6,3,4,3\]
**Output:** 2
**Explanation:** We can create a valid split in the following way: \[2,6\] | \[3,4,3\].
- The starting element of the 1st subarray is 2 and the ending is 6. Their greatest common divisor is 2, which is greater than 1.
- The starting element of the 2nd subarray is 3 and the ending is 3. Their greatest common divisor is 3, which is greater than 1.
It can be proved that 2 is the minimum number of subarrays that we can obtain in a valid split.

**Example 2:**

**Input:** nums = \[3,5\]
**Output:** 2
**Explanation:** We can create a valid split in the following way: \[3\] | \[5\].
- The starting element of the 1st subarray is 3 and the ending is 3. Their greatest common divisor is 3, which is greater than 1.
- The starting element of the 2nd subarray is 5 and the ending is 5. Their greatest common divisor is 5, which is greater than 1.
It can be proved that 2 is the minimum number of subarrays that we can obtain in a valid split.

**Example 3:**

**Input:** nums = \[1,2,1\]
**Output:** -1
**Explanation:** It is impossible to create valid split.

**Constraints:**

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

## A solution in Java

```java
public int minValidSubarrays(int[] nums) {
    int count = 0;
    while(nums.length > 0) {
        int i;
        for (i = 0; i < nums.length; i++) {
            if (gcd(nums[i], nums[nums.length - 1]) > 1) {
                break;
            }
        }
        if (i == nums.length) {
            nums = Arrays.copyOf(nums, nums.length - 1);
            count++;
        } else {
            break;
        }
    }
    return (count > 0) ? count : -1;
}

private int gcd(int a, int b) {
    while (b != 0) {
        int temp = a % b;
        a = b;
        b = temp;
    }
    return a;
}
```
The algorithm for this problem is as follows:
1. Initialize a counter to track the number of valid subarrays.
2. As long as the input array is not empty, iterate through the elements of the array.
3. For each element, check if the greatest common divisor (GCD) of the current element and the last element is greater than 1. If so, break the loop.
4. If we reached the end of the array and the loop didn't break, that means we don't have a valid subarray yet, so increment the counter and remove the last element of the array.
5. Repeat steps 2-4 until the array is empty or a valid subarray is found.
6. Finally, if the counter is greater than 0, return the counter value as the minimum number of valid subarrays, otherwise return -1 if no valid subarray splitting is possible.

## A solution in C++

```cpp
#include <numeric>
int min_valid_subarrays(vector<int>& nums) {
    int count = 0;
    for (int i = 0; i < nums.size(); i++) {
        while (i < nums.size() && std::gcd(nums[i], nums.back()) == 1) {
            i++;
        }
        if (i < nums.size()) {
            count++;
            nums.pop_back();
        }
    }
    return count > 0 ? count : -1;
}
```
The algorithm for this problem is as follows:
1. Initialize a counter to track the number of valid subarrays.
2. As long as the input array is not empty, iterate through the elements of the array.
3. For each element, check if the greatest common divisor (GCD) of the current element and the last element is greater than 1. If so, break the loop.
4. If we reached the end of the array and the loop didn't break, that means we don't have a valid subarray yet, so increment the counter and remove the last element of the array.
5. Repeat steps 2-4 until the array is empty or a valid subarray is found.
6. Finally, if the counter is greater than 0, return the counter value as the minimum number of valid subarrays, otherwise return -1 if no valid subarray splitting is possible.

## A solution in Python

```python
from math import gcd

def min_valid_subarrays(nums):
    count = 0
    while nums:
        for i in range(len(nums)):
            if gcd(nums[i], nums[-1]) > 1:
                break
        else:
            count += 1
            nums.pop()
    return count if count > 0 else -1
```
The algorithm for this problem is as follows:
1. Initialize a counter to track the number of valid subarrays.
2. As long as the input array is not empty, iterate through the elements of the array.
3. For each element, check if the greatest common divisor (GCD) of the current element and the last element is greater than 1. If so, break the loop.
4. If we reached the end of the array and the loop didn't break, that means we don't have a valid subarray yet, so increment the counter and remove the last element of the array.
5. Repeat steps 2-4 until the array is empty or a valid subarray is found.
6. Finally, if the counter is greater than 0, return the counter value as the minimum number of valid subarrays, otherwise return -1 if no valid subarray splitting is possible.

## A solution in Javascript

```javascript
function gcd(a, b) {
    while (b !== 0) {
        let temp = a % b;
        a = b;
        b = temp;
    }
    return a;
}

function minValidSubarrays(nums) {
    let count = 0;
    while (nums.length > 0) {
        let i;
        for (i = 0; i < nums.length; i++) {
            if (gcd(nums[i], nums[nums.length - 1]) > 1) {
                break;
            }
        }
        if (i === nums.length) {
            nums.pop();
            count++;
        } else {
            break;
        }
    }
    return (count > 0) ? count : -1;
}
```
The algorithm for this problem is as follows:
1. Initialize a counter to track the number of valid subarrays.
2. As long as the input array is not empty, iterate through the elements of the array.
3. For each element, check if the greatest common divisor (GCD) of the current element and the last element is greater than 1. If so, break the loop.
4. If we reached the end of the array and the loop didn't break, that means we don't have a valid subarray yet, so increment the counter and remove the last element of the array.
5. Repeat steps 2-4 until the array is empty or a valid subarray is found.
6. Finally, if the counter is greater than 0, return the counter value as the minimum number of valid subarrays, otherwise return -1 if no valid subarray splitting is possible.


# Number of Distinct Averages

- slug: number-of-distinct-averages
- difficulty: Easy

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

As long as `nums` is **not** empty, you must repetitively:

*   Find the minimum number in `nums` and remove it.
*   Find the maximum number in `nums` and remove it.
*   Calculate the average of the two removed numbers.

The **average** of two numbers `a` and `b` is `(a + b) / 2`.

*   For example, the average of `2` and `3` is `(2 + 3) / 2 = 2.5`.

Return _the number of **distinct** averages calculated using the above process_.

**Note** that when there is a tie for a minimum or maximum number, any can be removed.

**Example 1:**

**Input:** nums = \[4,1,4,0,3,5\]
**Output:** 2
**Explanation:**
1. Remove 0 and 5, and the average is (0 + 5) / 2 = 2.5. Now, nums = \[4,1,4,3\].
2. Remove 1 and 4. The average is (1 + 4) / 2 = 2.5, and nums = \[4,3\].
3. Remove 3 and 4, and the average is (3 + 4) / 2 = 3.5.
Since there are 2 distinct numbers among 2.5, 2.5, and 3.5, we return 2.

**Example 2:**

**Input:** nums = \[1,100\]
**Output:** 1
**Explanation:**
There is only one average to be calculated after removing 1 and 100, so we return 1.

**Constraints:**

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

## A solution in Java

```java
public int distinctAverages(int[] nums) {
    Set<Double> averages = new HashSet<>();
    Arrays.sort(nums);
    int n = nums.length;
    for (int i = 0; i < n / 2; i++) {
        averages.add((nums[i] + nums[n - 1 - i]) / 2.0);
    }
    return averages.size();
}
```
1. Initialize an empty sets called 'averages' to store the distinct averages.
2. Sort the input array 'nums'.
3. Iterate through the first half of the sorted array and calculate the average of the current number and its counterpart from the other end, then add this average to the 'averages' set.
4. Return the size of the 'averages' set which represents the distinct averages calculated using the given process.

## A solution in C++

```cpp
int distinctAverages(vector<int>& nums) {
    set<double> averages;
    sort(nums.begin(), nums.end());
    int n = nums.size();
    for (int i = 0; i < n / 2; i++) {
        averages.insert((nums[i] + nums[n - 1 - i]) / 2.0);
    }
    return averages.size();
}
```
1. Initialize an empty sets called 'averages' to store the distinct averages.
2. Sort the input array 'nums'.
3. Iterate through the first half of the sorted array and calculate the average of the current number and its counterpart from the other end, then add this average to the 'averages' set.
4. Return the size of the 'averages' set which represents the distinct averages calculated using the given process.

## A solution in Python

```python
def distinctAverages(nums):
    averages = set()
    nums.sort()
    n = len(nums)
    for i in range(n // 2):
        averages.add((nums[i] + nums[n - 1 - i]) / 2.0)
    return len(averages)
```
1. Initialize an empty sets called 'averages' to store the distinct averages.
2. Sort the input array 'nums'.
3. Iterate through the first half of the sorted array and calculate the average of the current number and its counterpart from the other end, then add this average to the 'averages' set.
4. Return the size of the 'averages' set which represents the distinct averages calculated using the given process.

## A solution in Javascript

```javascript
function distinctAverages(nums) {
    let averages = new Set();
    nums.sort((a, b) => a - b);
    let n = nums.length;
    for (let i = 0; i < n / 2; i++) {
        averages.add((nums[i] + nums[n - 1 - i]) / 2.0);
    }
    return averages.size;
}
```
1. Initialize an empty sets called 'averages' to store the distinct averages.
2. Sort the input array 'nums'.
3. Iterate through the first half of the sorted array and calculate the average of the current number and its counterpart from the other end, then add this average to the 'averages' set.
4. Return the size of the 'averages' set which represents the distinct averages calculated using the given process.