# Minimum Amount of Time to Fill Cups

- slug: minimum-amount-of-time-to-fill-cups
- difficulty: Easy

You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up `2` cups with **different** types of water, or `1` cup of any type of water.

You are given a **0-indexed** integer array `amount` of length `3` where `amount[0]`, `amount[1]`, and `amount[2]` denote the number of cold, warm, and hot water cups you need to fill respectively. Return _the **minimum** number of seconds needed to fill up all the cups_.

**Example 1:**

**Input:** amount = \[1,4,2\]
**Output:** 4
**Explanation:** One way to fill up the cups is:
Second 1: Fill up a cold cup and a warm cup.
Second 2: Fill up a warm cup and a hot cup.
Second 3: Fill up a warm cup and a hot cup.
Second 4: Fill up a warm cup.
It can be proven that 4 is the minimum number of seconds needed.

**Example 2:**

**Input:** amount = \[5,4,4\]
**Output:** 7
**Explanation:** One way to fill up the cups is:
Second 1: Fill up a cold cup, and a hot cup.
Second 2: Fill up a cold cup, and a warm cup.
Second 3: Fill up a cold cup, and a warm cup.
Second 4: Fill up a warm cup, and a hot cup.
Second 5: Fill up a cold cup, and a hot cup.
Second 6: Fill up a cold cup, and a warm cup.
Second 7: Fill up a hot cup.

**Example 3:**

**Input:** amount = \[5,0,0\]
**Output:** 5
**Explanation:** Every second, we fill up a cold cup.

**Constraints:**

*   `amount.length == 3`
*   `0 <= amount[i] <= 100`

## A solution in Java

```java
public int minSeconds(int[] amount) {
    int total = amount[0] + amount[1] + amount[2];
    int largestTwo = Math.max(amount[0] + amount[1], Math.max(amount[1] + amount[2], amount[0] + amount[2]));
    return (total + 1) / 2 - (largestTwo + 1) / 2 + largestTwo;
}
```
First, calculate the total number of cups required (total) and the combined amount of the two largest amounts of cups (largest_two). The minimum number of seconds needed is the sum of half the total (rounded up), minus half the largest_two (rounded up) plus largest_two. This should give us the minimum number of seconds to fill up all the cups.

## A solution in C++

```cpp
int min_seconds(vector<int>& amount) {
    int total = accumulate(amount.begin(), amount.end(), 0);
    int largest_two = max(amount[0] + amount[1], max(amount[1] + amount[2], amount[0] + amount[2]));
    return (total + 1) / 2 - (largest_two + 1) / 2 + largest_two;
}
```
First, calculate the total number of cups required (total) and the combined amount of the two largest amounts of cups (largest_two). The minimum number of seconds needed is the sum of half the total (rounded up), minus half the largest_two (rounded up) plus largest_two. This should give us the minimum number of seconds to fill up all the cups.

## A solution in Python

```python
def min_seconds(amount: List[int]) -> int:
    total = sum(amount)
    largest_two = max(amount[0] + amount[1], amount[1] + amount[2], amount[0] + amount[2])
    return (total + 1) // 2 - (largest_two + 1) // 2 + largest_two
```
First, calculate the total number of cups required (total) and the combined amount of the two largest amounts of cups (largest_two). The minimum number of seconds needed is the sum of half the total (rounded up), minus half the largest_two (rounded up) plus largest_two. This should give us the minimum number of seconds to fill up all the cups.

## A solution in Javascript

```javascript
function minSeconds(amount) {
    const total = amount[0] + amount[1] + amount[2];
    const largestTwo = Math.max(amount[0] + amount[1], amount[1] + amount[2], amount[0] + amount[2]);
    return Math.floor((total + 1) / 2) - Math.floor((largestTwo + 1) / 2) + largestTwo;
}
```
First, calculate the total number of cups required (total) and the combined amount of the two largest amounts of cups (largest_two). The minimum number of seconds needed is the sum of half the total (rounded up), minus half the largest_two (rounded up) plus largest_two. This should give us the minimum number of seconds to fill up all the cups.


# Smallest Number in Infinite Set

- slug: smallest-number-in-infinite-set
- difficulty: Medium

You have a set which contains all positive integers `[1, 2, 3, 4, 5, ...]`.

Implement the `SmallestInfiniteSet` class:

*   `SmallestInfiniteSet()` Initializes the **SmallestInfiniteSet** object to contain **all** positive integers.
*   `int popSmallest()` **Removes** and returns the smallest integer contained in the infinite set.
*   `void addBack(int num)` **Adds** a positive integer `num` back into the infinite set, if it is **not** already in the infinite set.

**Example 1:**

**Input**
\[ "SmallestInfiniteSet ",  "addBack ",  "popSmallest ",  "popSmallest ",  "popSmallest ",  "addBack ",  "popSmallest ",  "popSmallest ",  "popSmallest "\]
\[\[\], \[2\], \[\], \[\], \[\], \[1\], \[\], \[\], \[\]\]
**Output**
\[null, null, 1, 2, 3, null, 1, 4, 5\]

**Explanation**
SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();
smallestInfiniteSet.addBack(2);    // 2 is already in the set, so no change is made.
smallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.
smallestInfiniteSet.addBack(1);    // 1 is added back to the set.
smallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and
                                   // is the smallest number, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.
smallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.

**Constraints:**

*   `1 <= num <= 1000`
*   At most `1000` calls will be made **in total** to `popSmallest` and `addBack`.

## A solution in Java

```java
import java.util.TreeSet;

class SmallestInfiniteSet {
    TreeSet<Integer> available;
    int counter;

    SmallestInfiniteSet() {
        available = new TreeSet<>();
        counter = 1;
        for (int i = 1; i <= 1000; i++) {
            available.add(i);
        }
    }

    int popSmallest() {
        int smallest = counter;
        if (available.contains(counter)) {
            available.remove(counter);
        } else {
            counter++;
        }
        return smallest;
    }

    void addBack(int num) {
        available.add(num);
    }
}
```
The algorithm initializes the class by creating a set containing all integers from 1 to 1000 and setting a counter to 1. When `popSmallest` is called, it checks if the value of the counter is in the available set. If it is, it removes it from the set; if not, the counter is incremented. In both cases, the previous value of the counter is returned. When `addBack` is called, the number is simply added to the available set.

## A solution in C++

```cpp
#include <set>

class SmallestInfiniteSet {
public:
    std::set<int> available;
    int counter = 1;

    SmallestInfiniteSet() {
        for (int i = 1; i <= 1000; ++i)
            available.insert(i);
    }

    int popSmallest() {
        int smallest = counter;
        if (available.find(counter) != available.end())
            available.erase(counter);
        else
            counter++;
        return smallest;
    }

    void addBack(int num) {
        available.insert(num);
    }
};
```
The algorithm initializes the class by creating a set containing all integers from 1 to 1000 and setting a counter to 1. When `popSmallest` is called, it checks if the value of the counter is in the available set. If it is, it removes it from the set; if not, the counter is incremented. In both cases, the previous value of the counter is returned. When `addBack` is called, the number is simply added to the available set.

## A solution in Python

```python
class SmallestInfiniteSet:
    def __init__(self):
        self.available = set(range(1, 1001))
        self.counter = 1

    def popSmallest(self):
        smallest = self.counter
        if self.counter in self.available:
            self.available.remove(self.counter)
        else:
            self.counter += 1
        return smallest

    def addBack(self, num):
        self.available.add(num)
```
The algorithm initializes the class by creating a set containing all integers from 1 to 1000 and setting a counter to 1. When `popSmallest` is called, it checks if the value of the counter is in the available set. If it is, it removes it from the set; if not, the counter is incremented. In both cases, the previous value of the counter is returned. When `addBack` is called, the number is simply added to the available set.

## A solution in Javascript

```javascript
class SmallestInfiniteSet {
    constructor() {
        this.available = new Set();
        for (let i = 1; i <= 1000; i++) {
            this.available.add(i);
        }
        this.counter = 1;
    }

    popSmallest() {
        const smallest = this.counter;
        if (this.available.has(this.counter)) {
            this.available.delete(this.counter);
        } else {
            this.counter++;
        }
        return smallest;
    }

    addBack(num) {
        this.available.add(num);
    }
}
```
The algorithm initializes the class by creating a set containing all integers from 1 to 1000 and setting a counter to 1. When `popSmallest` is called, it checks if the value of the counter is in the available set. If it is, it removes it from the set; if not, the counter is incremented. In both cases, the previous value of the counter is returned. When `addBack` is called, the number is simply added to the available set.


# Move Pieces to Obtain a String

- slug: move-pieces-to-obtain-a-string
- difficulty: Medium

You are given two strings `start` and `target`, both of length `n`. Each string consists **only** of the characters `'L'`, `'R'`, and `'_'` where:

*   The characters `'L'` and `'R'` represent pieces, where a piece `'L'` can move to the **left** only if there is a **blank** space directly to its left, and a piece `'R'` can move to the **right** only if there is a **blank** space directly to its right.
*   The character `'_'` represents a blank space that can be occupied by **any** of the `'L'` or `'R'` pieces.

Return `true` _if it is possible to obtain the string_ `target` _by moving the pieces of the string_ `start` _**any** number of times_. Otherwise, return `false`.

**Example 1:**

**Input:** start =  "\_L\_\_R\_\_R\_ ", target =  "L\_\_\_\_\_\_RR "
**Output:** true
**Explanation:** We can obtain the string target from start by doing the following moves:
- Move the first piece one step to the left, start becomes equal to  "**L**\_\_\_R\_\_R\_ ".
- Move the last piece one step to the right, start becomes equal to  "L\_\_\_R\_\_\_**R** ".
- Move the second piece three steps to the right, start becomes equal to  "L\_\_\_\_\_\_**R**R ".
Since it is possible to get the string target from start, we return true.

**Example 2:**

**Input:** start =  "R\_L\_ ", target =  "\_\_LR "
**Output:** false
**Explanation:** The 'R' piece in the string start can move one step to the right to obtain  "\_**R**L\_ ".
After that, no pieces can move anymore, so it is impossible to obtain the string target from start.

**Example 3:**

**Input:** start =  "\_R ", target =  "R\_ "
**Output:** false
**Explanation:** The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.

**Constraints:**

*   `n == start.length == target.length`
*   `1 <= n <= 105`
*   `start` and `target` consist of the characters `'L'`, `'R'`, and `'_'`.

## A solution in Java

```java
public boolean canTransform(String start, String target) {
    int n = start.length();
    int p = 0, q = 0;

    while (p < n && q < n) {
        while (p < n && start.charAt(p) == '_') p++;
        while (q < n && target.charAt(q) == '_') q++;

        if (p == n || q == n) break;

        if (start.charAt(p) != target.charAt(q)) return false;

        if (start.charAt(p) == 'L' && p < q) return false;
        if (start.charAt(p) == 'R' && p > q) return false;

        p++; q++;
    }

    return p == n && q == n;
}
```
The solution checks if it is possible to move the pieces in the `start` string to form the `target` string. We can iterate through both strings with two pointers `p` and `q`.

1. Move the pointers `p` and `q` in `start` and `target` until a character 'L' or 'R' is encountered.
2. If both `p` and `q` hit the end of their strings, break the loop.
3. If the characters at pointer `p` and `q` are different, return false as it could never form the target string.
4. Check for illegal movements of 'L' and 'R':
   - If there is a 'L' at pointer `p` in `start` and pointer `p` is less than pointer `q`, it means 'L' should move to the right, which is an illegal movement, return false.
   - If there is a 'R' at pointer `p` in `start` and pointer `p` is greater than pointer `q`, it means 'R' should move to the left, which is an illegal movement, return false.
5. Move pointers `p` and `q` to the next character.
6. After breaking the loop, if both pointers reach the end of their respective strings, then it is possible to form `target` from `start`. Return true, otherwise return false.

## A solution in C++

```cpp
bool canTransform(string start, string target) {
    int n = start.length();
    int p = 0, q = 0;

    while (p < n && q < n) {
        // Move pointers until there is a letter.
        while (p < n && start[p] == '_') p++;
        while (q < n && target[q] == '_') q++;

        if (p == n || q == n) break;

        // Check if the chars at pointers are the same.
        if (start[p] != target[q]) return false;

        if (start[p] == 'L' && p < q) return false;
        if (start[p] == 'R' && p > q) return false;

        p++; q++;
    }

    return p == n && q == n;
}
```
The solution checks if it is possible to move the pieces in the `start` string to form the `target` string. We can iterate through both strings with two pointers `p` and `q`.

1. Move the pointers `p` and `q` in `start` and `target` until a character 'L' or 'R' is encountered.
2. If both `p` and `q` hit the end of their strings, break the loop.
3. If the characters at pointer `p` and `q` are different, return false as it could never form the target string.
4. Check for illegal movements of 'L' and 'R':
   - If there is a 'L' at pointer `p` in `start` and pointer `p` is less than pointer `q`, it means 'L' should move to the right, which is an illegal movement, return false.
   - If there is a 'R' at pointer `p` in `start` and pointer `p` is greater than pointer `q`, it means 'R' should move to the left, which is an illegal movement, return false.
5. Move pointers `p` and `q` to the next character.
6. After breaking the loop, if both pointers reach the end of their respective strings, then it is possible to form `target` from `start`. Return true, otherwise return false.

## A solution in Python

```python
def canTransform(start: str, target: str) -> bool:
    n = len(start)
    p, q = 0, 0

    while p < n and q < n:
        while p < n and start[p] == '_': p += 1
        while q < n and target[q] == '_': q += 1

        if p == n or q == n: break

        if start[p] != target[q]: return False

        if start[p] == 'L' and p < q: return False
        if start[p] == 'R' and p > q: return False

        p += 1
        q += 1

    return p == n and q == n
```
The solution checks if it is possible to move the pieces in the `start` string to form the `target` string. We can iterate through both strings with two pointers `p` and `q`.

1. Move the pointers `p` and `q` in `start` and `target` until a character 'L' or 'R' is encountered.
2. If both `p` and `q` hit the end of their strings, break the loop.
3. If the characters at pointer `p` and `q` are different, return false as it could never form the target string.
4. Check for illegal movements of 'L' and 'R':
   - If there is a 'L' at pointer `p` in `start` and pointer `p` is less than pointer `q`, it means 'L' should move to the right, which is an illegal movement, return false.
   - If there is a 'R' at pointer `p` in `start` and pointer `p` is greater than pointer `q`, it means 'R' should move to the left, which is an illegal movement, return false.
5. Move pointers `p` and `q` to the next character.
6. After breaking the loop, if both pointers reach the end of their respective strings, then it is possible to form `target` from `start`. Return true, otherwise return false.

## A solution in Javascript

```javascript
function canTransform(start, target) {
    let n = start.length;
    let p = 0, q = 0;

    while (p < n && q < n) {
        while (p < n && start[p] === '_') p++;
        while (q < n && target[q] === '_') q++;

        if (p === n || q === n) break;

        if (start[p] !== target[q]) return false;

        if (start[p] === 'L' && p < q) return false;
        if (start[p] === 'R' && p > q) return false;

        p++; q++;
    }

    return p === n && q === n;
}
```
The solution checks if it is possible to move the pieces in the `start` string to form the `target` string. We can iterate through both strings with two pointers `p` and `q`.

1. Move the pointers `p` and `q` in `start` and `target` until a character 'L' or 'R' is encountered.
2. If both `p` and `q` hit the end of their strings, break the loop.
3. If the characters at pointer `p` and `q` are different, return false as it could never form the target string.
4. Check for illegal movements of 'L' and 'R':
   - If there is a 'L' at pointer `p` in `start` and pointer `p` is less than pointer `q`, it means 'L' should move to the right, which is an illegal movement, return false.
   - If there is a 'R' at pointer `p` in `start` and pointer `p` is greater than pointer `q`, it means 'R' should move to the left, which is an illegal movement, return false.
5. Move pointers `p` and `q` to the next character.
6. After breaking the loop, if both pointers reach the end of their respective strings, then it is possible to form `target` from `start`. Return true, otherwise return false.


# Count the Number of Ideal Arrays

- slug: count-the-number-of-ideal-arrays
- difficulty: Hard

You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array.

A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold:

*   Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`.
*   Every `arr[i]` is divisible by `arr[i - 1]`, for `0 < i < n`.

Return _the number of **distinct** ideal arrays of length_ `n`. Since the answer may be very large, return it modulo `109 + 7`.

**Example 1:**

**Input:** n = 2, maxValue = 5
**Output:** 10
**Explanation:** The following are the possible ideal arrays:
- Arrays starting with the value 1 (5 arrays): \[1,1\], \[1,2\], \[1,3\], \[1,4\], \[1,5\]
- Arrays starting with the value 2 (2 arrays): \[2,2\], \[2,4\]
- Arrays starting with the value 3 (1 array): \[3,3\]
- Arrays starting with the value 4 (1 array): \[4,4\]
- Arrays starting with the value 5 (1 array): \[5,5\]
There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.

**Example 2:**

**Input:** n = 5, maxValue = 3
**Output:** 11
**Explanation:** The following are the possible ideal arrays:
- Arrays starting with the value 1 (9 arrays):
   - With no other distinct values (1 array): \[1,1,1,1,1\]
   - With 2nd distinct value 2 (4 arrays): \[1,1,1,1,2\], \[1,1,1,2,2\], \[1,1,2,2,2\], \[1,2,2,2,2\]
   - With 2nd distinct value 3 (4 arrays): \[1,1,1,1,3\], \[1,1,1,3,3\], \[1,1,3,3,3\], \[1,3,3,3,3\]
- Arrays starting with the value 2 (1 array): \[2,2,2,2,2\]
- Arrays starting with the value 3 (1 array): \[3,3,3,3,3\]
There are a total of 9 + 1 + 1 = 11 distinct ideal arrays.

**Constraints:**

*   `2 <= n <= 104`
*   `1 <= maxValue <= 104`

## A solution in Java

```java
public int numOfArrays(int n, int maxValue) {
    final int mod = 1_000_000_007;
    int[] dp = new int[maxValue + 1];

    for (int i = 1; i <= maxValue; i++) {
        dp[i] = i;
    }

    for (int i = 1; i < n; i++) {
        for (int j = maxValue; j > 0; j--) {
            dp[j] = (dp[j] + dp[j - 1]) % mod;
        }
    }

    return dp[maxValue];
}
```
The problem can be solved using dynamic programming, where we maintain an array `dp` of length `maxValue + 1`.

1. Initialize the `dp` array by assigning `i` to `dp[i]` for `i` in the range `[1, maxValue]`.
2. We need to find the number of ideal arrays of length `n`. So, we iterate from `1` to `n - 1`. In each iteration, we update the `dp` array.
3. For updating the `dp` array, we iterate from `maxValue` to `1`, and we update `dp[j]` as `(dp[j] + dp[j - 1]) % mod`, where `mod` is `10^9 + 7`.
4. The result of the function is the value at `dp[maxValue]`.

The time complexity of this algorithm is O(n * maxValue) and the space complexity is O(maxValue).

## A solution in C++

```cpp
int numOfArrays(int n, int maxValue) {
    const int mod = 1e9 + 7;
    vector<int> dp(maxValue + 1, 0);

    for (int i = 1; i <= maxValue; i++) {
        dp[i] = i;
    }

    for (int i = 1; i < n; i++) {
        for (int j = maxValue; j > 0; j--) {
            dp[j] = (dp[j] + dp[j - 1]) % mod;
        }
    }

    return dp[maxValue];
}
```
The problem can be solved using dynamic programming, where we maintain an array `dp` of length `maxValue + 1`.

1. Initialize the `dp` array by assigning `i` to `dp[i]` for `i` in the range `[1, maxValue]`.
2. We need to find the number of ideal arrays of length `n`. So, we iterate from `1` to `n - 1`. In each iteration, we update the `dp` array.
3. For updating the `dp` array, we iterate from `maxValue` to `1`, and we update `dp[j]` as `(dp[j] + dp[j - 1]) % mod`, where `mod` is `10^9 + 7`.
4. The result of the function is the value at `dp[maxValue]`.

The time complexity of this algorithm is O(n * maxValue) and the space complexity is O(maxValue).

## A solution in Python

```python
def numOfArrays(n: int, maxValue: int) -> int:
    mod = 10**9 + 7
    dp = [0] * (maxValue + 1)

    for i in range(1, maxValue + 1):
        dp[i] = i

    for i in range(1, n):
        for j in range(maxValue, 0, -1):
            dp[j] = (dp[j] + dp[j - 1]) % mod

    return dp[maxValue]
```
The problem can be solved using dynamic programming, where we maintain an array `dp` of length `maxValue + 1`.

1. Initialize the `dp` array by assigning `i` to `dp[i]` for `i` in the range `[1, maxValue]`.
2. We need to find the number of ideal arrays of length `n`. So, we iterate from `1` to `n - 1`. In each iteration, we update the `dp` array.
3. For updating the `dp` array, we iterate from `maxValue` to `1`, and we update `dp[j]` as `(dp[j] + dp[j - 1]) % mod`, where `mod` is `10^9 + 7`.
4. The result of the function is the value at `dp[maxValue]`.

The time complexity of this algorithm is O(n * maxValue) and the space complexity is O(maxValue).

## A solution in Javascript

```javascript
function numOfArrays(n, maxValue) {
    const mod = 1e9 + 7;
    const dp = Array(maxValue + 1).fill(0);

    for (let i = 1; i <= maxValue; i++) {
        dp[i] = i;
    }

    for (let i = 1; i < n; i++) {
        for (let j = maxValue; j > 0; j--) {
            dp[j] = (dp[j] + dp[j - 1]) % mod;
        }
    }

    return dp[maxValue];
}
```
The problem can be solved using dynamic programming, where we maintain an array `dp` of length `maxValue + 1`.

1. Initialize the `dp` array by assigning `i` to `dp[i]` for `i` in the range `[1, maxValue]`.
2. We need to find the number of ideal arrays of length `n`. So, we iterate from `1` to `n - 1`. In each iteration, we update the `dp` array.
3. For updating the `dp` array, we iterate from `maxValue` to `1`, and we update `dp[j]` as `(dp[j] + dp[j - 1]) % mod`, where `mod` is `10^9 + 7`.
4. The result of the function is the value at `dp[maxValue]`.

The time complexity of this algorithm is O(n * maxValue) and the space complexity is O(maxValue).


# Minimum Adjacent Swaps to Make a Valid Array

- slug: minimum-adjacent-swaps-to-make-a-valid-array
- difficulty: Medium

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

**Swaps** of **adjacent** elements are able to be performed on `nums`.

A **valid** array meets the following conditions:

*   The largest element (any of the largest elements if there are multiple) is at the rightmost position in the array.
*   The smallest element (any of the smallest elements if there are multiple) is at the leftmost position in the array.

Return _the **minimum** swaps required to make_ `nums` _a valid array_.

**Example 1:**

**Input:** nums = \[3,4,5,5,3,1\]
**Output:** 6
**Explanation:** Perform the following swaps:
- Swap 1: Swap the 3rd and 4th elements, nums is then \[3,4,5,**3**,**5**,1\].
- Swap 2: Swap the 4th and 5th elements, nums is then \[3,4,5,3,**1**,**5**\].
- Swap 3: Swap the 3rd and 4th elements, nums is then \[3,4,5,**1**,**3**,5\].
- Swap 4: Swap the 2nd and 3rd elements, nums is then \[3,4,**1**,**5**,3,5\].
- Swap 5: Swap the 1st and 2nd elements, nums is then \[3,**1**,**4**,5,3,5\].
- Swap 6: Swap the 0th and 1st elements, nums is then \[**1**,**3**,4,5,3,5\].
It can be shown that 6 swaps is the minimum swaps required to make a valid array.

**Example 2:**

**Input:** nums = \[9\]
**Output:** 0
**Explanation:** The array is already valid, so we return 0.

**Constraints:**

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

## A solution in Java

```java
public int minSwaps(int[] nums) {
    int n = nums.length;
    int minPos = 0, maxPos = 0, swaps = 0;

    for (int i = 1; i < n; i++) {
        if (nums[i] <= nums[minPos])
            minPos = i;
        if (nums[i] >= nums[maxPos])
            maxPos = i;
    }

    swaps = minPos + (n - 1 - maxPos);
    if (minPos < maxPos) swaps--;

    return swaps;
}
```
The algorithm first initializes the minimum and maximum element positions (`minPos` and `maxPos`) as 0.
Then, it iterates through each element of the array, updating the positions if it's smaller or equal to the current minimum or larger or equal to the current maximum.

After calculating the positions of the minimum and maximum elements, the algorithm calculates the number of swaps needed to place the minimum element at the leftmost position and the maximum element at the rightmost position, which is given by `minPos + (n - 1 - maxPos)`. At last, if `minPos` is smaller than `maxPos`, we decrement the swaps counter by 1 because we need one less swap to move both minimum and maximum elements to their designated positions.

Lastly, the algorithm returns the calculated `swaps` count.

## A solution in C++

```cpp
int minSwaps(vector<int>& nums) {
    int n = nums.size();
    int minPos = 0, maxPos = 0, swaps = 0;

    for (int i = 1; i < n; i++) {
        if (nums[i] <= nums[minPos])
            minPos = i;
        if (nums[i] >= nums[maxPos])
            maxPos = i;
    }

    swaps = minPos + (n - 1 - maxPos);
    if (minPos < maxPos) swaps--;

    return swaps;
}
```
The algorithm first initializes the minimum and maximum element positions (`minPos` and `maxPos`) as 0.
Then, it iterates through each element of the array, updating the positions if it's smaller or equal to the current minimum or larger or equal to the current maximum.

After calculating the positions of the minimum and maximum elements, the algorithm calculates the number of swaps needed to place the minimum element at the leftmost position and the maximum element at the rightmost position, which is given by `minPos + (n - 1 - maxPos)`. At last, if `minPos` is smaller than `maxPos`, we decrement the swaps counter by 1 because we need one less swap to move both minimum and maximum elements to their designated positions.

Lastly, the algorithm returns the calculated `swaps` count.

## A solution in Python

```python
def minSwaps(nums):
    n = len(nums)
    minPos = 0
    maxPos = 0
    swaps = 0

    for i in range(1, n):
        if nums[i] <= nums[minPos]:
            minPos = i
        if nums[i] >= nums[maxPos]:
            maxPos = i

    swaps = minPos + (n - 1 - maxPos)
    if minPos < maxPos:
        swaps -= 1

    return swaps
```
The algorithm first initializes the minimum and maximum element positions (`minPos` and `maxPos`) as 0.
Then, it iterates through each element of the array, updating the positions if it's smaller or equal to the current minimum or larger or equal to the current maximum.

After calculating the positions of the minimum and maximum elements, the algorithm calculates the number of swaps needed to place the minimum element at the leftmost position and the maximum element at the rightmost position, which is given by `minPos + (n - 1 - maxPos)`. At last, if `minPos` is smaller than `maxPos`, we decrement the swaps counter by 1 because we need one less swap to move both minimum and maximum elements to their designated positions.

Lastly, the algorithm returns the calculated `swaps` count.

## A solution in Javascript

```javascript
function minSwaps(nums) {
    let n = nums.length;
    let minPos = 0, maxPos = 0, swaps = 0;

    for (let i = 1; i < n; i++) {
        if (nums[i] <= nums[minPos])
            minPos = i;
        if (nums[i] >= nums[maxPos])
            maxPos = i;
    }

    swaps = minPos + (n - 1 - maxPos);
    if (minPos < maxPos) swaps--;

    return swaps;
}
```
The algorithm first initializes the minimum and maximum element positions (`minPos` and `maxPos`) as 0.
Then, it iterates through each element of the array, updating the positions if it's smaller or equal to the current minimum or larger or equal to the current maximum.

After calculating the positions of the minimum and maximum elements, the algorithm calculates the number of swaps needed to place the minimum element at the leftmost position and the maximum element at the rightmost position, which is given by `minPos + (n - 1 - maxPos)`. At last, if `minPos` is smaller than `maxPos`, we decrement the swaps counter by 1 because we need one less swap to move both minimum and maximum elements to their designated positions.

Lastly, the algorithm returns the calculated `swaps` count.


# Maximum Number of Pairs in Array

- slug: maximum-number-of-pairs-in-array
- difficulty: Easy

You are given a **0-indexed** integer array `nums`. In one operation, you may do the following:

*   Choose **two** integers in `nums` that are **equal**.
*   Remove both integers from `nums`, forming a **pair**.

The operation is done on `nums` as many times as possible.

Return _a **0-indexed** integer array_ `answer` _of size_ `2` _where_ `answer[0]` _is the number of pairs that are formed and_ `answer[1]` _is the number of leftover integers in_ `nums` _after doing the operation as many times as possible_.

**Example 1:**

**Input:** nums = \[1,3,2,1,3,2,2\]
**Output:** \[3,1\]
**Explanation:**
Form a pair with nums\[0\] and nums\[3\] and remove them from nums. Now, nums = \[3,2,3,2,2\].
Form a pair with nums\[0\] and nums\[2\] and remove them from nums. Now, nums = \[2,2,2\].
Form a pair with nums\[0\] and nums\[1\] and remove them from nums. Now, nums = \[2\].
No more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.

**Example 2:**

**Input:** nums = \[1,1\]
**Output:** \[1,0\]
**Explanation:** Form a pair with nums\[0\] and nums\[1\] and remove them from nums. Now, nums = \[\].
No more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.

**Example 3:**

**Input:** nums = \[0\]
**Output:** \[0,1\]
**Explanation:** No pairs can be formed, and there is 1 number leftover in nums.

**Constraints:**

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

## A solution in Java

```java
import java.util.HashMap;

public int[] countPairsLeftovers(int[] nums) {
    HashMap<Integer, Integer> counter = new HashMap<>();
    int pairs = 0, leftovers = 0;

    for (int n : nums) {
        counter.put(n, counter.getOrDefault(n, 0) + 1);
    }

    for (int count : counter.values()) {
        pairs += count / 2;
        leftovers += count % 2;
    }

    return new int[]{pairs, leftovers};
}
```
The algorithm first initializes an array or hash map (in Java) to count the occurrences of each number in the given `nums` array. Then, it iterates through the input array `nums` and increments the count of each number.

After that, the algorithm iterates over the counter array or values (in Java, using `.values()`) and calculates the number of pairs and leftovers for each element. The number of pairs for an element is equal to the integer division of its count by 2 (`count // 2` or `count / 2`), and the number of leftovers is equal to the count modulo 2 (`count % 2`).

Finally, the function returns an array containing the total number of pairs and leftovers.

## A solution in C++

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

vector<int> countPairsLeftovers(vector<int>& nums) {
    vector<int> counter(101, 0);
    int pairs = 0, leftovers = 0;

    for (int n : nums) {
        counter[n]++;
    }

    for (int count : counter) {
        pairs += count / 2;
        leftovers += count % 2;
    }

    return {pairs, leftovers};
}
```
The algorithm first initializes an array or hash map (in Java) to count the occurrences of each number in the given `nums` array. Then, it iterates through the input array `nums` and increments the count of each number.

After that, the algorithm iterates over the counter array or values (in Java, using `.values()`) and calculates the number of pairs and leftovers for each element. The number of pairs for an element is equal to the integer division of its count by 2 (`count // 2` or `count / 2`), and the number of leftovers is equal to the count modulo 2 (`count % 2`).

Finally, the function returns an array containing the total number of pairs and leftovers.

## A solution in Python

```python
def count_pairs_leftovers(nums):
    counter = [0] * 101
    pairs, leftovers = 0, 0

    for n in nums:
        counter[n] += 1

    for count in counter:
        pairs += count // 2
        leftovers += count % 2

    return [pairs, leftovers]
```
The algorithm first initializes an array or hash map (in Java) to count the occurrences of each number in the given `nums` array. Then, it iterates through the input array `nums` and increments the count of each number.

After that, the algorithm iterates over the counter array or values (in Java, using `.values()`) and calculates the number of pairs and leftovers for each element. The number of pairs for an element is equal to the integer division of its count by 2 (`count // 2` or `count / 2`), and the number of leftovers is equal to the count modulo 2 (`count % 2`).

Finally, the function returns an array containing the total number of pairs and leftovers.

## A solution in Javascript

```javascript
function countPairsLeftovers(nums) {
    let counter = new Array(101).fill(0);
    let pairs = 0, leftovers = 0;

    for (let n of nums) {
        counter[n]++;
    }

    for (let count of counter) {
        pairs += Math.floor(count / 2);
        leftovers += count % 2;
    }

    return [pairs, leftovers];
}
```
The algorithm first initializes an array or hash map (in Java) to count the occurrences of each number in the given `nums` array. Then, it iterates through the input array `nums` and increments the count of each number.

After that, the algorithm iterates over the counter array or values (in Java, using `.values()`) and calculates the number of pairs and leftovers for each element. The number of pairs for an element is equal to the integer division of its count by 2 (`count // 2` or `count / 2`), and the number of leftovers is equal to the count modulo 2 (`count % 2`).

Finally, the function returns an array containing the total number of pairs and leftovers.


# Max Sum of a Pair With Equal Sum of Digits

- slug: max-sum-of-a-pair-with-equal-sum-of-digits
- difficulty: Medium

You are given a **0-indexed** array `nums` consisting of **positive** integers. You can choose two indices `i` and `j`, such that `i != j`, and the sum of digits of the number `nums[i]` is equal to that of `nums[j]`.

Return _the **maximum** value of_ `nums[i] + nums[j]` _that you can obtain over all possible indices_ `i` _and_ `j` _that satisfy the conditions._

**Example 1:**

**Input:** nums = \[18,43,36,13,7\]
**Output:** 54
**Explanation:** The pairs (i, j) that satisfy the conditions are:
- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.
- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.
So the maximum sum that we can obtain is 54.

**Example 2:**

**Input:** nums = \[10,12,19,14\]
**Output:** -1
**Explanation:** There are no two numbers that satisfy the conditions, so we return -1.

**Constraints:**

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

## A solution in Java

```java
public int maxSumNumbersWithEqualSumOfDigits(int[] nums) {
    HashMap<Integer, Integer> digitSumToMax = new HashMap<>();
    int ans = -1;

    for (int num : nums) {
        int sumOfDigits = 0;
        for (int temp = num; temp != 0; temp /= 10) {
            sumOfDigits += temp % 10;
        }

        int prevMax = digitSumToMax.getOrDefault(sumOfDigits, 0);
        if (prevMax != 0) {
            ans = Math.max(ans, num + prevMax);
        }
        digitSumToMax.put(sumOfDigits, Math.max(num, prevMax));
    }

    return ans;
}
```
For each number in the input array, calculate the sum of its digits. Store the maximum value of the numbers with the same digit sum in a hashmap. For each number, check if there is a number in the hashmap with the same digit sum. If there is, calculate their sum and update the answer if their sum is greater than the current answer.

## A solution in C++

```cpp
int maxSumNumbersWithEqualSumOfDigits(vector<int>& nums) {
    unordered_map<int, int> digit_sum_to_max;
    int ans = -1;

    for (int num : nums) {
        int sum_of_digits = 0;
        for (int temp = num; temp; temp /= 10) {
            sum_of_digits += temp % 10;
        }

        int prev_max = digit_sum_to_max[sum_of_digits];
        if (prev_max) {
            ans = max(ans, num + prev_max);
        }
        digit_sum_to_max[sum_of_digits] = max(num, prev_max);
    }

    return ans;
}
```
For each number in the input array, calculate the sum of its digits. Store the maximum value of the numbers with the same digit sum in a hashmap. For each number, check if there is a number in the hashmap with the same digit sum. If there is, calculate their sum and update the answer if their sum is greater than the current answer.

## A solution in Python

```python
def max_sum_numbers_with_equal_sum_of_digits(nums):
    digit_sum_to_max = {}
    ans = -1

    for num in nums:
        sum_of_digits = sum(map(int, str(num)))

        prev_max = digit_sum_to_max.get(sum_of_digits, 0)
        if prev_max:
            ans = max(ans, num + prev_max)

        digit_sum_to_max[sum_of_digits] = max(num, prev_max)

    return ans
```
For each number in the input array, calculate the sum of its digits. Store the maximum value of the numbers with the same digit sum in a hashmap. For each number, check if there is a number in the hashmap with the same digit sum. If there is, calculate their sum and update the answer if their sum is greater than the current answer.

## A solution in Javascript

```javascript
function maxSumNumbersWithEqualSumOfDigits(nums) {
    const digitSumToMax = {};
    let ans = -1;

    for (const num of nums) {
        let sumOfDigits = 0;
        for (let temp = num; temp !== 0; temp = Math.floor(temp / 10)) {
            sumOfDigits += temp % 10;
        }

        const prevMax = digitSumToMax[sumOfDigits] || 0;
        if (prevMax) {
            ans = Math.max(ans, num + prevMax);
        }
        digitSumToMax[sumOfDigits] = Math.max(num, prevMax);
    }

    return ans;
}
```
For each number in the input array, calculate the sum of its digits. Store the maximum value of the numbers with the same digit sum in a hashmap. For each number, check if there is a number in the hashmap with the same digit sum. If there is, calculate their sum and update the answer if their sum is greater than the current answer.


# Query Kth Smallest Trimmed Number

- slug: query-kth-smallest-trimmed-number
- difficulty: Medium

You are given a **0-indexed** array of strings `nums`, where each string is of **equal length** and consists of only digits.

You are also given a **0-indexed** 2D integer array `queries` where `queries[i] = [ki, trimi]`. For each `queries[i]`, you need to:

*   **Trim** each number in `nums` to its **rightmost** `trimi` digits.
*   Determine the **index** of the `kith` smallest trimmed number in `nums`. If two trimmed numbers are equal, the number with the **lower** index is considered to be smaller.
*   Reset each number in `nums` to its original length.

Return _an array_ `answer` _of the same length as_ `queries`, _where_ `answer[i]` _is the answer to the_ `ith` _query._

**Note**:

*   To trim to the rightmost `x` digits means to keep removing the leftmost digit, until only `x` digits remain.
*   Strings in `nums` may contain leading zeros.

**Example 1:**

**Input:** nums = \[ "102 ", "473 ", "251 ", "814 "\], queries = \[\[1,1\],\[2,3\],\[4,2\],\[1,2\]\]
**Output:** \[2,2,1,0\]
**Explanation:**
1. After trimming to the last digit, nums = \[ "2 ", "3 ", "1 ", "4 "\]. The smallest number is 1 at index 2.
2. Trimmed to the last 3 digits, nums is unchanged. The 2nd smallest number is 251 at index 2.
3. Trimmed to the last 2 digits, nums = \[ "02 ", "73 ", "51 ", "14 "\]. The 4th smallest number is 73.
4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.
   Note that the trimmed number  "02 " is evaluated as 2.

**Example 2:**

**Input:** nums = \[ "24 ", "37 ", "96 ", "04 "\], queries = \[\[2,1\],\[2,2\]\]
**Output:** \[3,0\]
**Explanation:**
1. Trimmed to the last digit, nums = \[ "4 ", "7 ", "6 ", "4 "\]. The 2nd smallest number is 4 at index 3.
   There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.
2. Trimmed to the last 2 digits, nums is unchanged. The 2nd smallest number is 24.

**Constraints:**

*   `1 <= nums.length <= 100`
*   `1 <= nums[i].length <= 100`
*   `nums[i]` consists of only digits.
*   All `nums[i].length` are **equal**.
*   `1 <= queries.length <= 100`
*   `queries[i].length == 2`
*   `1 <= ki <= nums.length`
*   `1 <= trimi <= nums[i].length`

**Follow up:** Could you use the **Radix Sort Algorithm** to solve this problem? What will be the complexity of that solution?

## A solution in Java

```java
import java.util.*;

public class Solution {
    public int[] kthSmallestIndex(String[] nums, int[][] queries) {
        int[] answer = new int[queries.length];
        int[][] indices = new int[nums.length][2];
        for (int i = 0; i < nums.length; ++i) {
            indices[i][0] = Integer.parseInt(nums[i]);
            indices[i][1] = i;
        }

        Arrays.sort(indices, (a, b) -> (a[0] - b[0]) == 0 ? (a[1] - b[1]) : (a[0] - b[0]));

        for (int i = 0; i < queries.length; ++i) {
            int k = queries[i][0];
            int trim = queries[i][1];
            for (int j = 0; j < nums.length; ++j) {
                indices[j][0] = Integer.parseInt(nums[j].substring(nums[j].length() - trim));
            }
            Arrays.sort(indices, (a, b) -> (a[0] - b[0]) == 0 ? (a[1] - b[1]) : (a[0] - b[0]));
            answer[i] = indices[k - 1][1];
        }

        return answer;
    }
}
```
1. Prepare an array `indices` that contains the initial indices and the corresponding number values from `nums`. Sort this array by the number values, and then by the indices (in the case of equal numbers).
2. For each query, modify the numbers in the `indices` according to the trimming specified in the query, and resort the array using the same sorting criteria as before.
3. Then, find the (k-1)-th element in indices and append its index into the array `answer`.
4. Repeat steps 2-3 for all queries.
5. Return the `answer` array.

## A solution in C++

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

vector<int> kthSmallestIndex(vector<string>& nums, vector<vector<int>>& queries) {
    vector<int> answer;
    vector<pair<int, int>> indices(nums.size());
    for (size_t i = 0; i < nums.size(); ++i) {
        indices[i] = {stoi(nums[i]), i};
    }

    for (auto& query : queries) {
        auto k = query[0];
        auto trim = query[1];
        for (size_t i = 0; i < nums.size(); ++i) {
            indices[i].first = stoi(nums[i].substr(nums[i].size() - trim));
        }
        sort(indices.begin(), indices.end());
        answer.push_back(indices[k - 1].second);
    }

    return answer;
}
```
1. Prepare an array `indices` that contains the initial indices and the corresponding number values from `nums`. Sort this array by the number values, and then by the indices (in the case of equal numbers).
2. For each query, modify the numbers in the `indices` according to the trimming specified in the query, and resort the array using the same sorting criteria as before.
3. Then, find the (k-1)-th element in indices and append its index into the array `answer`.
4. Repeat steps 2-3 for all queries.
5. Return the `answer` array.

## A solution in Python

```python
from typing import List

def kthSmallestIndex(nums: List[str], queries: List[List[int]]) -> List[int]:
    answer = []
    indices = list(enumerate(map(int, nums)))
    indices.sort(key=lambda x: (x[1], x[0]))

    for k, trim in queries:
        trimmed_indices = [(i, int(n[-trim:])) for i, n in enumerate(nums)]
        trimmed_indices.sort(key=lambda x: (x[1], x[0]))
        answer.append(trimmed_indices[k-1][0])

    return answer
```
1. Prepare an array `indices` that contains the initial indices and the corresponding number values from `nums`. Sort this array by the number values, and then by the indices (in the case of equal numbers).
2. For each query, modify the numbers in the `indices` according to the trimming specified in the query, and resort the array using the same sorting criteria as before.
3. Then, find the (k-1)-th element in indices and append its index into the array `answer`.
4. Repeat steps 2-3 for all queries.
5. Return the `answer` array.

## A solution in Javascript

```javascript
var kthSmallestIndex = function(nums, queries) {
    let answer = [];
    let indices = [];
    for (let i = 0; i < nums.length; ++i) {
        indices.push({index: i, num: parseInt(nums[i])});
    }
    indices.sort((a, b) => a.num - b.num || a.index - b.index);

    for (let q of queries) {
        let [k, trim] = q;
        for (let i = 0; i < nums.length; ++i) {
            indices[i].num = parseInt(nums[i].slice(-trim));
        }
        indices.sort((a, b) => a.num - b.num || a.index - b.index);
        answer.push(indices[k - 1].index);
    }

    return answer;
};
```
1. Prepare an array `indices` that contains the initial indices and the corresponding number values from `nums`. Sort this array by the number values, and then by the indices (in the case of equal numbers).
2. For each query, modify the numbers in the `indices` according to the trimming specified in the query, and resort the array using the same sorting criteria as before.
3. Then, find the (k-1)-th element in indices and append its index into the array `answer`.
4. Repeat steps 2-3 for all queries.
5. Return the `answer` array.


# Minimum Deletions to Make Array Divisible

- slug: minimum-deletions-to-make-array-divisible
- difficulty: Hard

You are given two positive integer arrays `nums` and `numsDivide`. You can delete any number of elements from `nums`.

Return _the **minimum** number of deletions such that the **smallest** element in_ `nums` _**divides** all the elements of_ `numsDivide`. If this is not possible, return `-1`.

Note that an integer `x` divides `y` if `y % x == 0`.

**Example 1:**

**Input:** nums = \[2,3,2,4,3\], numsDivide = \[9,6,9,3,15\]
**Output:** 2
**Explanation:**
The smallest element in \[2,3,2,4,3\] is 2, which does not divide all the elements of numsDivide.
We use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = \[3,4,3\].
The smallest element in \[3,4,3\] is 3, which divides all the elements of numsDivide.
It can be shown that 2 is the minimum number of deletions needed.

**Example 2:**

**Input:** nums = \[4,3,6\], numsDivide = \[8,2,6,10\]
**Output:** -1
**Explanation:**
We want the smallest element in nums to divide all the elements of numsDivide.
There is no way to delete elements from nums to allow this.

**Constraints:**

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

## A solution in Java

```java
public int minDeletions(int[] nums, int[] numsDivide) {
    int res = Integer.MAX_VALUE;
    for (int num : nums) {
        int cnt = 0;
        boolean found = true;
        for (int d : numsDivide) {
            if (d % num != 0) {
                found = false;
                break;
            }
        }
        if (found) {
            for (int n : nums) {
                if (n == num) {
                    cnt++;
                }
            }
            res = Math.min(res, nums.length - cnt);
        }
    }
    return res == Integer.MAX_VALUE ? -1 : res;
}
```
For each number in `nums`, check if it divides all elements in `numsDivide`. If it does, count how many times it appears in `nums` and calculate the minimum number of deletions required to make it the smallest element in `nums` by subtracting the count (cnt) from the size (length) of the nums array (need to delete all other elements). Keep track of the minimum result for all numbers. If the minimum result is still Infinity (initial value) after looping through all numbers, it means there is no solution, and we return -1. Otherwise, return the minimum result.

## A solution in C++

```cpp
int minDeletions(vector<int>& nums, vector<int>& numsDivide) {
    int res = INT_MAX;
    for (int num : nums) {
        int cnt = 0;
        bool found = true;
        for (int d : numsDivide) {
            if (d % num != 0) {
                found = false;
                break;
            }
        }
        if (found) {
            for (int n : nums) {
                if (n == num) {
                    cnt++;
                }
            }
            res = min(res, (int)nums.size() - cnt);
        }
    }
    return res == INT_MAX ? -1 : res;
}
```
For each number in `nums`, check if it divides all elements in `numsDivide`. If it does, count how many times it appears in `nums` and calculate the minimum number of deletions required to make it the smallest element in `nums` by subtracting the count (cnt) from the size (length) of the nums array (need to delete all other elements). Keep track of the minimum result for all numbers. If the minimum result is still Infinity (initial value) after looping through all numbers, it means there is no solution, and we return -1. Otherwise, return the minimum result.

## A solution in Python

```python
def min_deletions(nums, nums_divide):
    res = float('inf')
    for num in nums:
        cnt = 0
        found = True
        for d in nums_divide:
            if d % num != 0:
                found = False
                break
        if found:
            for n in nums:
                if n == num:
                    cnt += 1
            res = min(res, len(nums) - cnt)
    return -1 if res == float('inf') else res
```
For each number in `nums`, check if it divides all elements in `numsDivide`. If it does, count how many times it appears in `nums` and calculate the minimum number of deletions required to make it the smallest element in `nums` by subtracting the count (cnt) from the size (length) of the nums array (need to delete all other elements). Keep track of the minimum result for all numbers. If the minimum result is still Infinity (initial value) after looping through all numbers, it means there is no solution, and we return -1. Otherwise, return the minimum result.

## A solution in Javascript

```javascript
function minDeletions(nums, numsDivide) {
    let res = Infinity;
    for (let num of nums) {
        let cnt = 0;
        let found = true;
        for (let d of numsDivide) {
            if (d % num !== 0) {
                found = false;
                break;
            }
        }
        if (found) {
            for (let n of nums) {
                if (n === num) {
                    cnt++;
                }
            }
            res = Math.min(res, nums.length - cnt);
        }
    }
    return res === Infinity ? -1 : res;
}
```
For each number in `nums`, check if it divides all elements in `numsDivide`. If it does, count how many times it appears in `nums` and calculate the minimum number of deletions required to make it the smallest element in `nums` by subtracting the count (cnt) from the size (length) of the nums array (need to delete all other elements). Keep track of the minimum result for all numbers. If the minimum result is still Infinity (initial value) after looping through all numbers, it means there is no solution, and we return -1. Otherwise, return the minimum result.


# Finding the Number of Visible Mountains

- slug: finding-the-number-of-visible-mountains
- difficulty: Medium

You are given a **0-indexed** 2D integer array `peaks` where `peaks[i] = [xi, yi]` states that mountain `i` has a peak at coordinates `(xi, yi)`. A mountain can be described as a right-angled isosceles triangle, with its base along the `x`\-axis and a right angle at its peak. More formally, the **gradients** of ascending and descending the mountain are `1` and `-1` respectively.

A mountain is considered **visible** if its peak does not lie within another mountain (including the border of other mountains).

Return _the number of visible mountains_.

**Example 1:**

**Input:** peaks = \[\[2,2\],\[6,3\],\[5,4\]\]
**Output:** 2
**Explanation:** The diagram above shows the mountains.
- Mountain 0 is visible since its peak does not lie within another mountain or its sides.
- Mountain 1 is not visible since its peak lies within the side of mountain 2.
- Mountain 2 is visible since its peak does not lie within another mountain or its sides.
There are 2 mountains that are visible.

**Example 2:**

**Input:** peaks = \[\[1,3\],\[1,3\]\]
**Output:** 0
**Explanation:** The diagram above shows the mountains (they completely overlap).
Both mountains are not visible since their peaks lie within each other.

**Constraints:**

*   `1 <= peaks.length <= 105`
*   `peaks[i].length == 2`
*   `1 <= xi, yi <= 105`

## A solution in Java

```java
public int minOperations(String current, String correct) {
    int currentMins = Integer.parseInt(current.substring(0, 2)) * 60 + Integer.parseInt(current.substring(3, 5));
    int correctMins = Integer.parseInt(correct.substring(0, 2)) * 60 + Integer.parseInt(correct.substring(3, 5));
    if(currentMins > correctMins) correctMins += 24 * 60;

    int diff = correctMins - currentMins;
    int count = diff / 60 + (diff % 60) / 15 + ((diff % 60) % 15) / 5 + (((diff % 60) % 15) % 5);

    return count;
}
```
1. Convert both `current` and `correct` strings into minutes (HH * 60 + MM).
2. If `currentMins` is greater than `correctMins`, increment `correctMins` by the number of minutes in a day (24 * 60) to account for potential timezone crossing.
3. Calculate the difference between `correctMins` and `currentMins`.
4. Count the minimum operations needed to cover the difference by dividing it by the largest possible operation (60) and updating the remaining difference for smaller operations such as 15, 5, and 1. Add the result of each calculation to `count`.
5. Return the minimum number of operations as `count`.

## A solution in C++

```cpp
int minOperations(std::string current, std::string correct) {
    int currentMins = stoi(current.substr(0, 2)) * 60 + stoi(current.substr(3, 2));
    int correctMins = stoi(correct.substr(0, 2)) * 60 + stoi(correct.substr(3, 2));
    if (currentMins > correctMins) correctMins += 24 * 60;

    int diff = correctMins - currentMins;
    int count = diff / 60 + (diff % 60) / 15 + ((diff % 60) % 15) / 5 + (((diff % 60) % 15) % 5);

    return count;
}
```
1. Convert both `current` and `correct` strings into minutes (HH * 60 + MM).
2. If `currentMins` is greater than `correctMins`, increment `correctMins` by the number of minutes in a day (24 * 60) to account for potential timezone crossing.
3. Calculate the difference between `correctMins` and `currentMins`.
4. Count the minimum operations needed to cover the difference by dividing it by the largest possible operation (60) and updating the remaining difference for smaller operations such as 15, 5, and 1. Add the result of each calculation to `count`.
5. Return the minimum number of operations as `count`.

## A solution in Python

```python
def min_operations(current, correct):
    current_mins = int(current[:2]) * 60 + int(current[3:])
    correct_mins = int(correct[:2]) * 60 + int(correct[3:])
    if current_mins > correct_mins:
        correct_mins += 24 * 60

    diff = correct_mins - current_mins
    count = diff // 60 + (diff % 60) // 15 + ((diff % 60) % 15) // 5 + (((diff % 60) % 15) % 5)

    return count
```
1. Convert both `current` and `correct` strings into minutes (HH * 60 + MM).
2. If `currentMins` is greater than `correctMins`, increment `correctMins` by the number of minutes in a day (24 * 60) to account for potential timezone crossing.
3. Calculate the difference between `correctMins` and `currentMins`.
4. Count the minimum operations needed to cover the difference by dividing it by the largest possible operation (60) and updating the remaining difference for smaller operations such as 15, 5, and 1. Add the result of each calculation to `count`.
5. Return the minimum number of operations as `count`.

## A solution in Javascript

```javascript
function minOperations(current, correct) {
    let currentMins = parseInt(current.substring(0, 2)) * 60 + parseInt(current.substring(3, 5));
    let correctMins = parseInt(correct.substring(0, 2)) * 60 + parseInt(correct.substring(3, 5));
    if (currentMins > correctMins) correctMins += 24 * 60;

    let diff = correctMins - currentMins;
    let count = Math.floor(diff / 60) + Math.floor((diff % 60) / 15) + Math.floor(((diff % 60) % 15) / 5) + Math.floor((((diff % 60) % 15) % 5));

    return count;
}
```
1. Convert both `current` and `correct` strings into minutes (HH * 60 + MM).
2. If `currentMins` is greater than `correctMins`, increment `correctMins` by the number of minutes in a day (24 * 60) to account for potential timezone crossing.
3. Calculate the difference between `correctMins` and `currentMins`.
4. Count the minimum operations needed to cover the difference by dividing it by the largest possible operation (60) and updating the remaining difference for smaller operations such as 15, 5, and 1. Add the result of each calculation to `count`.
5. Return the minimum number of operations as `count`.


# Best Poker Hand

- slug: best-poker-hand
- difficulty: Easy

You are given an integer array `ranks` and a character array `suits`. You have `5` cards where the `ith` card has a rank of `ranks[i]` and a suit of `suits[i]`.

The following are the types of **poker hands** you can make from best to worst:

1.  `"Flush "`: Five cards of the same suit.
2.  `"Three of a Kind "`: Three cards of the same rank.
3.  `"Pair "`: Two cards of the same rank.
4.  `"High Card "`: Any single card.

Return _a string representing the **best** type of **poker hand** you can make with the given cards._

**Note** that the return values are **case-sensitive**.

**Example 1:**

**Input:** ranks = \[13,2,3,1,9\], suits = \[ "a ", "a ", "a ", "a ", "a "\]
**Output:**  "Flush "
**Explanation:** The hand with all the cards consists of 5 cards with the same suit, so we have a  "Flush ".

**Example 2:**

**Input:** ranks = \[4,4,2,4,4\], suits = \[ "d ", "a ", "a ", "b ", "c "\]
**Output:**  "Three of a Kind "
**Explanation:** The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a  "Three of a Kind ".
Note that we could also make a  "Pair " hand but  "Three of a Kind " is a better hand.
Also note that other cards could be used to make the  "Three of a Kind " hand.

**Example 3:**

**Input:** ranks = \[10,10,2,12,9\], suits = \[ "a ", "b ", "c ", "a ", "d "\]
**Output:**  "Pair "
**Explanation:** The hand with the first and second card consists of 2 cards with the same rank, so we have a  "Pair ".
Note that we cannot make a  "Flush " or a  "Three of a Kind ".

**Constraints:**

*   `ranks.length == suits.length == 5`
*   `1 <= ranks[i] <= 13`
*   `'a' <= suits[i] <= 'd'`
*   No two cards have the same rank and suit.

## A solution in Java

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

public class Solution {
    public static String bestPokerHand(int[] ranks, char[] suits) {
        Map<Integer, Integer> rankCount = new HashMap<>();
        Map<Character, Integer> suitCount = new HashMap<>();
        for (int i = 0; i < ranks.length; i++) {
            rankCount.put(ranks[i], rankCount.getOrDefault(ranks[i], 0) + 1);
            suitCount.put(suits[i], suitCount.getOrDefault(suits[i], 0) + 1);
        }
        if (suitCount.size() == 1) return "Flush ";
        if (rankCount.size() == 3) return "Three of a Kind ";
        for (Map.Entry<Integer, Integer> entry : rankCount.entrySet()) {
            if (entry.getValue() == 2) return "Pair ";
        }
        return "High Card ";
    }
}
```
We first iterate through the `ranks` and `suits` arrays and store the count of each rank and suit in two separate hash maps (`rank_count` and `suit_count` respectively). Then we check the following to determine the best poker hand:
1. If `suit_count` has only one key, it means all cards have the same suit, so the result is a "Flush ".
2. If `rank_count` has only three keys, it means there's a "Three of a Kind ", because there are either 3 of one rank and 1 each of two other ranks or 2 of one rank and 1 each of three other ranks.
3. If we find a value of 2 in `rank_count`, it implies there's a "Pair ".
4. If none of the above conditions are met, the result is a "High Card ".

## A solution in C++

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

std::string bestPokerHand(std::vector<int> &ranks, std::vector<char> &suits) {
    std::map<int, int> rank_count;
    std::map<char, int> suit_count;
    for (int i = 0; i < ranks.size(); ++i) {
        rank_count[ranks[i]]++;
        suit_count[suits[i]]++;
    }
    if (suit_count.size() == 1) return "Flush ";
    if (rank_count.size() == 3) return "Three of a Kind ";
    for (const auto &pair : rank_count) {
        if (pair.second == 2) return "Pair ";
    }
    return "High Card ";
}
```
We first iterate through the `ranks` and `suits` arrays and store the count of each rank and suit in two separate hash maps (`rank_count` and `suit_count` respectively). Then we check the following to determine the best poker hand:
1. If `suit_count` has only one key, it means all cards have the same suit, so the result is a "Flush ".
2. If `rank_count` has only three keys, it means there's a "Three of a Kind ", because there are either 3 of one rank and 1 each of two other ranks or 2 of one rank and 1 each of three other ranks.
3. If we find a value of 2 in `rank_count`, it implies there's a "Pair ".
4. If none of the above conditions are met, the result is a "High Card ".

## A solution in Python

```python
def best_poker_hand(ranks, suits):
    rank_count = {}
    suit_count = {}
    for rank, suit in zip(ranks, suits):
        rank_count[rank] = rank_count.get(rank, 0) + 1
        suit_count[suit] = suit_count.get(suit, 0) + 1
    if len(suit_count) == 1:
        return "Flush "
    if len(rank_count) == 3:
        return "Three of a Kind "
    for value in rank_count.values():
        if value == 2:
            return "Pair "
    return "High Card "
```
We first iterate through the `ranks` and `suits` arrays and store the count of each rank and suit in two separate hash maps (`rank_count` and `suit_count` respectively). Then we check the following to determine the best poker hand:
1. If `suit_count` has only one key, it means all cards have the same suit, so the result is a "Flush ".
2. If `rank_count` has only three keys, it means there's a "Three of a Kind ", because there are either 3 of one rank and 1 each of two other ranks or 2 of one rank and 1 each of three other ranks.
3. If we find a value of 2 in `rank_count`, it implies there's a "Pair ".
4. If none of the above conditions are met, the result is a "High Card ".

## A solution in Javascript

```javascript
function bestPokerHand(ranks, suits) {
    const rankCount = new Map();
    const suitCount = new Map();
    for (let i = 0; i < ranks.length; i++) {
        rankCount.set(ranks[i], (rankCount.get(ranks[i]) || 0) + 1);
        suitCount.set(suits[i], (suitCount.get(suits[i]) || 0) + 1);
    }
    if (suitCount.size === 1) return "Flush ";
    if (rankCount.size === 3) return "Three of a Kind ";
    for (const value of rankCount.values()) {
        if (value === 2) return "Pair ";
    }
    return "High Card ";
}
```
We first iterate through the `ranks` and `suits` arrays and store the count of each rank and suit in two separate hash maps (`rank_count` and `suit_count` respectively). Then we check the following to determine the best poker hand:
1. If `suit_count` has only one key, it means all cards have the same suit, so the result is a "Flush ".
2. If `rank_count` has only three keys, it means there's a "Three of a Kind ", because there are either 3 of one rank and 1 each of two other ranks or 2 of one rank and 1 each of three other ranks.
3. If we find a value of 2 in `rank_count`, it implies there's a "Pair ".
4. If none of the above conditions are met, the result is a "High Card ".


# Number of Zero-Filled Subarrays

- slug: number-of-zero-filled-subarrays
- difficulty: Medium

Given an integer array `nums`, return _the number of **subarrays** filled with_ `0`.

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

**Example 1:**

**Input:** nums = \[1,3,0,0,2,0,0,4\]
**Output:** 6
**Explanation:**
There are 4 occurrences of \[0\] as a subarray.
There are 2 occurrences of \[0,0\] as a subarray.
There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.

**Example 2:**

**Input:** nums = \[0,0,0,2,0,0\]
**Output:** 9
**Explanation:**
There are 5 occurrences of \[0\] as a subarray.
There are 3 occurrences of \[0,0\] as a subarray.
There is 1 occurrence of \[0,0,0\] as a subarray.
There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.

**Example 3:**

**Input:** nums = \[2,10,2019\]
**Output:** 0
**Explanation:** There is no subarray filled with 0. Therefore, we return 0.

**Constraints:**

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

## A solution in Java

```java
public int numberOfSubarraysWithZeroes(int[] nums) {
    int count = 0;
    int zeroCount = 0;

    for (int num : nums) {
        if (num == 0) {
            zeroCount++;
            count += zeroCount;
        } else {
            zeroCount = 0;
        }
    }
    return count;
}
```
For this problem, we iterate through the given `nums` array. If we encounter a zero, we increment `zeroCount`, which keeps track of consecutive zeroes. We then add `zeroCount` to our total `count`, which represents the number of subarrays filled with zeroes.

If we encounter a non-zero number, we reset `zeroCount` to 0.

Finally, we return the total `count` as the result.

## A solution in C++

```cpp
int numberOfSubarraysWithZeroes(vector<int>& nums) {
    int count = 0;
    int zeroCount = 0;

    for (int num : nums) {
        if (num == 0) {
            zeroCount++;
            count += zeroCount;
        } else {
            zeroCount = 0;
        }
    }
    return count;
}
```
For this problem, we iterate through the given `nums` array. If we encounter a zero, we increment `zeroCount`, which keeps track of consecutive zeroes. We then add `zeroCount` to our total `count`, which represents the number of subarrays filled with zeroes.

If we encounter a non-zero number, we reset `zeroCount` to 0.

Finally, we return the total `count` as the result.

## A solution in Python

```python
def numberOfSubarraysWithZeroes(nums):
    count = 0
    zero_count = 0

    for num in nums:
        if num == 0:
            zero_count += 1
            count += zero_count
        else:
            zero_count = 0

    return count
```
For this problem, we iterate through the given `nums` array. If we encounter a zero, we increment `zeroCount`, which keeps track of consecutive zeroes. We then add `zeroCount` to our total `count`, which represents the number of subarrays filled with zeroes.

If we encounter a non-zero number, we reset `zeroCount` to 0.

Finally, we return the total `count` as the result.

## A solution in Javascript

```javascript
function numberOfSubarraysWithZeroes(nums) {
    let count = 0;
    let zeroCount = 0;

    for (const num of nums) {
        if (num === 0) {
            zeroCount++;
            count += zeroCount;
        } else {
            zeroCount = 0;
        }
    }
    return count;
}
```
For this problem, we iterate through the given `nums` array. If we encounter a zero, we increment `zeroCount`, which keeps track of consecutive zeroes. We then add `zeroCount` to our total `count`, which represents the number of subarrays filled with zeroes.

If we encounter a non-zero number, we reset `zeroCount` to 0.

Finally, we return the total `count` as the result.


# Design a Number Container System

- slug: design-a-number-container-system
- difficulty: Medium

Design a number container system that can do the following:

*   **Insert** or **Replace** a number at the given index in the system.
*   **Return** the smallest index for the given number in the system.

Implement the `NumberContainers` class:

*   `NumberContainers()` Initializes the number container system.
*   `void change(int index, int number)` Fills the container at `index` with the `number`. If there is already a number at that `index`, replace it.
*   `int find(int number)` Returns the smallest index for the given `number`, or `-1` if there is no index that is filled by `number` in the system.

**Example 1:**

**Input**
\[ "NumberContainers ",  "find ",  "change ",  "change ",  "change ",  "change ",  "find ",  "change ",  "find "\]
\[\[\], \[10\], \[2, 10\], \[1, 10\], \[3, 10\], \[5, 10\], \[10\], \[1, 20\], \[10\]\]
**Output**
\[null, -1, null, null, null, null, 1, null, 2\]

**Explanation**
NumberContainers nc = new NumberContainers();
nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.
nc.change(2, 10); // Your container at index 2 will be filled with number 10.
nc.change(1, 10); // Your container at index 1 will be filled with number 10.
nc.change(3, 10); // Your container at index 3 will be filled with number 10.
nc.change(5, 10); // Your container at index 5 will be filled with number 10.
nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.
nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20.
nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.

**Constraints:**

*   `1 <= index, number <= 109`
*   At most `105` calls will be made **in total** to `change` and `find`.

## A solution in Java

```java
import java.util.*;

class NumberContainers {
    private HashMap<Integer, Integer> indices = new HashMap<>();
    private TreeMap<Integer, TreeSet<Integer>> nums = new TreeMap<>();

    public NumberContainers() {
    }

    public void change(int index, int number) {
        if (indices.containsKey(index)) {
            int old_number = indices.get(index);
            nums.get(old_number).remove(index);
            if (nums.get(old_number).isEmpty()) {
                nums.remove(old_number);
            }
        }
        indices.put(index, number);
        nums.putIfAbsent(number, new TreeSet<>());
        nums.get(number).add(index);
    }

    public int find(int number) {
        if (nums.containsKey(number)) {
            return nums.get(number).first();
        }
        return -1;
    }
}
```
The algorithm for each language follows these steps:

1. Initialize two data structures, `indices` which is a hashmap to store the numbers with their indices as keys, and `nums` which is a map (in C++, Java, JavaScript) or dictionary (in Python) with keys as numbers, and values as sets of indices that the number is found at.
2. In the `change` function, if the given index is already present in `indices`, remove the index from the corresponding set in `nums`.
3. Next, update the hashmap `indices` with the new (index, number) pair.
4. If the number is not present in the `nums`, add the number with an empty set. Then, add the index to the set corresponding to the number.
5. In the `find` function, if the number is found in `nums`, return the smallest index present in the set for the given number. Otherwise, return -1.

The algorithm efficiently stores the indices based on the given numbers, making the `find()` operations as fast as possible.

## A solution in C++

```cpp
#include <unordered_map>
#include <map>

class NumberContainers {
public:
    NumberContainers() {
    }

    void change(int index, int number) {
        if (indices.count(index)) {
            int old_number = indices[index];
            nums[old_number].erase(index);
            if (nums[old_number].empty()) {
                nums.erase(old_number);
            }
        }
        indices[index] = number;
        nums[number].insert(index);
    }

    int find(int number) {
        if (nums.count(number)) {
            return *nums[number].begin();
        }
        return -1;
    }

private:
    std::unordered_map<int, int> indices;
    std::map<int, std::set<int>> nums;
};
```
The algorithm for each language follows these steps:

1. Initialize two data structures, `indices` which is a hashmap to store the numbers with their indices as keys, and `nums` which is a map (in C++, Java, JavaScript) or dictionary (in Python) with keys as numbers, and values as sets of indices that the number is found at.
2. In the `change` function, if the given index is already present in `indices`, remove the index from the corresponding set in `nums`.
3. Next, update the hashmap `indices` with the new (index, number) pair.
4. If the number is not present in the `nums`, add the number with an empty set. Then, add the index to the set corresponding to the number.
5. In the `find` function, if the number is found in `nums`, return the smallest index present in the set for the given number. Otherwise, return -1.

The algorithm efficiently stores the indices based on the given numbers, making the `find()` operations as fast as possible.

## A solution in Python

```python
class NumberContainers:
    def __init__(self):
        self.indices = {}
        self.nums = {}

    def change(self, index: int, number: int) -> None:
        if index in self.indices:
            old_number = self.indices[index]
            self.nums[old_number].remove(index)
            if not self.nums[old_number]:
                del self.nums[old_number]
        self.indices[index] = number
        if number not in self.nums:
            self.nums[number] = set()
        self.nums[number].add(index)

    def find(self, number: int) -> int:
        if number in self.nums:
            return min(self.nums[number])
        return -1
```
The algorithm for each language follows these steps:

1. Initialize two data structures, `indices` which is a hashmap to store the numbers with their indices as keys, and `nums` which is a map (in C++, Java, JavaScript) or dictionary (in Python) with keys as numbers, and values as sets of indices that the number is found at.
2. In the `change` function, if the given index is already present in `indices`, remove the index from the corresponding set in `nums`.
3. Next, update the hashmap `indices` with the new (index, number) pair.
4. If the number is not present in the `nums`, add the number with an empty set. Then, add the index to the set corresponding to the number.
5. In the `find` function, if the number is found in `nums`, return the smallest index present in the set for the given number. Otherwise, return -1.

The algorithm efficiently stores the indices based on the given numbers, making the `find()` operations as fast as possible.

## A solution in Javascript

```javascript
class NumberContainers {
    constructor() {
        this.indices = new Map();
        this.nums = new Map();
    }

    change(index, number) {
        if (this.indices.has(index)) {
            const oldNumber = this.indices.get(index);
            const oldSet = this.nums.get(oldNumber);
            oldSet.delete(index);
            if (oldSet.size === 0) {
                this.nums.delete(oldNumber);
            }
        }
        this.indices.set(index, number);
        if (!this.nums.has(number)) {
            this.nums.set(number, new Set());
        }
        this.nums.get(number).add(index);
    }

    find(number) {
        if (this.nums.has(number)) {
            return Math.min(...this.nums.get(number));
        }
        return -1;
    }
}
```
The algorithm for each language follows these steps:

1. Initialize two data structures, `indices` which is a hashmap to store the numbers with their indices as keys, and `nums` which is a map (in C++, Java, JavaScript) or dictionary (in Python) with keys as numbers, and values as sets of indices that the number is found at.
2. In the `change` function, if the given index is already present in `indices`, remove the index from the corresponding set in `nums`.
3. Next, update the hashmap `indices` with the new (index, number) pair.
4. If the number is not present in the `nums`, add the number with an empty set. Then, add the index to the set corresponding to the number.
5. In the `find` function, if the number is found in `nums`, return the smallest index present in the set for the given number. Otherwise, return -1.

The algorithm efficiently stores the indices based on the given numbers, making the `find()` operations as fast as possible.


# Shortest Impossible Sequence of Rolls

- slug: shortest-impossible-sequence-of-rolls
- difficulty: Hard

You are given an integer array `rolls` of length `n` and an integer `k`. You roll a `k` sided dice numbered from `1` to `k`, `n` times, where the result of the `ith` roll is `rolls[i]`.

Return _the length of the **shortest** sequence of rolls that **cannot** be taken from_ `rolls`.

A **sequence of rolls** of length `len` is the result of rolling a `k` sided dice `len` times.

**Note** that the sequence taken does not have to be consecutive as long as it is in order.

**Example 1:**

**Input:** rolls = \[4,2,1,2,3,3,2,4,1\], k = 4
**Output:** 3
**Explanation:** Every sequence of rolls of length 1, \[1\], \[2\], \[3\], \[4\], can be taken from rolls.
Every sequence of rolls of length 2, \[1, 1\], \[1, 2\], ..., \[4, 4\], can be taken from rolls.
The sequence \[1, 4, 2\] cannot be taken from rolls, so we return 3.
Note that there are other sequences that cannot be taken from rolls.

**Example 2:**

**Input:** rolls = \[1,1,2,2\], k = 2
**Output:** 2
**Explanation:** Every sequence of rolls of length 1, \[1\], \[2\], can be taken from rolls.
The sequence \[2, 1\] cannot be taken from rolls, so we return 2.
Note that there are other sequences that cannot be taken from rolls but \[2, 1\] is the shortest.

**Example 3:**

**Input:** rolls = \[1,1,3,2,2,2,3,3\], k = 4
**Output:** 1
**Explanation:** The sequence \[4\] cannot be taken from rolls, so we return 1.
Note that there are other sequences that cannot be taken from rolls but \[4\] is the shortest.

**Constraints:**

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

## A solution in Java

```java
public int shortestUnrollableSequence(int[] rolls, int k) {
    int[] count = new int[k + 1];
    for (int roll : rolls) {
        count[roll]++;
    }

    int len = 1;
    while (true) {
        int max_subsequences = 1;
        for (int i = 1; i <= k; i++) {
            max_subsequences *= count[i] + (len == 1 ? 1 : 0);
        }

        if (max_subsequences < len * rolls.length) {
            return len;
        }

        len++;
    }
}
```
The algorithm first counts the occurrences of each roll in the `rolls` array. Then, it iterates through the possible lengths of the unrollable sequence, starting at 1. For each length, the algorithm calculates the maximum number of unique sub-sequences of that length that can potentially be created by combining the existing rolls in the `rolls` array.

If the maximum number of unique sub-sequences that can be created is less than the expected number of sub-sequences (length * number of rolls), then it means there must exist a sequence of that length which cannot be formed from the given `rolls`. Therefore, the algorithm returns that length.

## A solution in C++

```cpp
int shortestUnrollableSequence(vector<int>& rolls, int k) {
    vector<int> count(k + 1);
    for (int roll : rolls) {
        count[roll]++;
    }

    int len = 1;
    while (true) {
        int max_subsequences = 1;
        for (int i = 1; i <= k; i++) {
            max_subsequences *= count[i] + (len == 1);
        }

        if (max_subsequences < len * rolls.size()) {
            return len;
        }

        len++;
    }
}
```
The algorithm first counts the occurrences of each roll in the `rolls` array. Then, it iterates through the possible lengths of the unrollable sequence, starting at 1. For each length, the algorithm calculates the maximum number of unique sub-sequences of that length that can potentially be created by combining the existing rolls in the `rolls` array.

If the maximum number of unique sub-sequences that can be created is less than the expected number of sub-sequences (length * number of rolls), then it means there must exist a sequence of that length which cannot be formed from the given `rolls`. Therefore, the algorithm returns that length.

## A solution in Python

```python
def shortest_unrollable_sequence(rolls, k):
    count = [0] * (k + 1)
    for roll in rolls:
        count[roll] += 1

    len_ = 1
    while True:
        max_subsequences = 1
        for i in range(1, k + 1):
            max_subsequences *= count[i] + (1 if len_ == 1 else 0)

        if max_subsequences < len_ * len(rolls):
            return len_

        len_ += 1
```
The algorithm first counts the occurrences of each roll in the `rolls` array. Then, it iterates through the possible lengths of the unrollable sequence, starting at 1. For each length, the algorithm calculates the maximum number of unique sub-sequences of that length that can potentially be created by combining the existing rolls in the `rolls` array.

If the maximum number of unique sub-sequences that can be created is less than the expected number of sub-sequences (length * number of rolls), then it means there must exist a sequence of that length which cannot be formed from the given `rolls`. Therefore, the algorithm returns that length.

## A solution in Javascript

```javascript
function shortestUnrollableSequence(rolls, k) {
    const count = new Array(k + 1).fill(0);
    for (const roll of rolls) {
        count[roll]++;
    }

    let len = 1;
    while (true) {
        let max_subsequences = 1;
        for (let i = 1; i <= k; i++) {
            max_subsequences *= count[i] + (len === 1 ? 1 : 0);
        }

        if (max_subsequences < len * rolls.length) {
            return len;
        }

        len++;
    }
}
```
The algorithm first counts the occurrences of each roll in the `rolls` array. Then, it iterates through the possible lengths of the unrollable sequence, starting at 1. For each length, the algorithm calculates the maximum number of unique sub-sequences of that length that can potentially be created by combining the existing rolls in the `rolls` array.

If the maximum number of unique sub-sequences that can be created is less than the expected number of sub-sequences (length * number of rolls), then it means there must exist a sequence of that length which cannot be formed from the given `rolls`. Therefore, the algorithm returns that length.


# First Letter to Appear Twice

- slug: first-letter-to-appear-twice
- difficulty: Easy

Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_.

**Note**:

*   A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`.
*   `s` will contain at least one letter that appears twice.

**Example 1:**

**Input:** s =  "abccbaacz "
**Output:**  "c "
**Explanation:**
The letter 'a' appears on the indexes 0, 5 and 6.
The letter 'b' appears on the indexes 1 and 4.
The letter 'c' appears on the indexes 2, 3 and 7.
The letter 'z' appears on the index 8.
The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.

**Example 2:**

**Input:** s =  "abcdd "
**Output:**  "d "
**Explanation:**
The only letter that appears twice is 'd' so we return 'd'.

**Constraints:**

*   `2 <= s.length <= 100`
*   `s` consists of lowercase English letters.
*   `s` has at least one repeated letter.

## A solution in Java

```java
public char firstLetterToAppearTwice(String s) {
    int[] occurrences = new int[26];
    for (char c : s.toCharArray()) {
        occurrences[c - 'a']++;
        if (occurrences[c - 'a'] == 2) {
            return c;
        }
    }
    return '?';
}
```
The solution in each programming language follows the same algorithm. First, we create an array to store the occurrences of each lowercase English letter. Then, we iterate through the given string, incrementing the count of the current character in the occurrences array. If an element in the occurrences array reaches 2, that means we've found a letter that appears twice, so we return that letter.

## A solution in C++

```cpp
char firstLetterToAppearTwice(std::string s) {
    std::array<int, 26> occurrences;
    occurrences.fill(0);
    for (char c : s) {
        occurrences[c - 'a']++;
        if (occurrences[c - 'a'] == 2) {
            return c;
        }
    }
    return '?';
}
```
The solution in each programming language follows the same algorithm. First, we create an array to store the occurrences of each lowercase English letter. Then, we iterate through the given string, incrementing the count of the current character in the occurrences array. If an element in the occurrences array reaches 2, that means we've found a letter that appears twice, so we return that letter.

## A solution in Python

```python
def first_letter_to_appear_twice(s: str) -> str:
    occurrences = [0] * 26
    for c in s:
        occurrences[ord(c) - ord('a')] += 1
        if occurrences[ord(c) - ord('a')] == 2:
            return c
    return '?'
```
The solution in each programming language follows the same algorithm. First, we create an array to store the occurrences of each lowercase English letter. Then, we iterate through the given string, incrementing the count of the current character in the occurrences array. If an element in the occurrences array reaches 2, that means we've found a letter that appears twice, so we return that letter.

## A solution in Javascript

```javascript
function firstLetterToAppearTwice(s) {
    const occurrences = new Array(26).fill(0);
    for (let c of s) {
        occurrences[c.charCodeAt(0) - 'a'.charCodeAt(0)]++;
        if (occurrences[c.charCodeAt(0) - 'a'.charCodeAt(0)] == 2) {
            return c;
        }
    }
    return '?';
}
```
The solution in each programming language follows the same algorithm. First, we create an array to store the occurrences of each lowercase English letter. Then, we iterate through the given string, incrementing the count of the current character in the occurrences array. If an element in the occurrences array reaches 2, that means we've found a letter that appears twice, so we return that letter.


# Equal Row and Column Pairs

- slug: equal-row-and-column-pairs
- difficulty: Medium

Given a **0-indexed** `n x n` integer matrix `grid`, _return the number of pairs_ `(ri, cj)` _such that row_ `ri` _and column_ `cj` _are equal_.

A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).

**Example 1:**

**Input:** grid = \[\[3,2,1\],\[1,7,6\],\[2,7,7\]\]
**Output:** 1
**Explanation:** There is 1 equal row and column pair:
- (Row 2, Column 1): \[2,7,7\]

**Example 2:**

**Input:** grid = \[\[3,1,2,2\],\[1,4,4,5\],\[2,4,2,2\],\[2,4,2,2\]\]
**Output:** 3
**Explanation:** There are 3 equal row and column pairs:
- (Row 0, Column 0): \[3,1,2,2\]
- (Row 2, Column 2): \[2,4,2,2\]
- (Row 3, Column 2): \[2,4,2,2\]

**Constraints:**

*   `n == grid.length == grid[i].length`
*   `1 <= n <= 200`
*   `1 <= grid[i][j] <= 105`

## A solution in Java

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

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            boolean equal = true;
            for (int k = 0; k < n; ++k) {
                if (grid[i][k] != grid[k][j]) {
                    equal = false;
                    break;
                }
            }
            if (equal) {
                ++ans;
            }
        }
    }

    return ans;
}
```
We use three nested loops to find the equal row and column pairs. For each row `i` and column `j`, we iterate through elements `k` from `0` to `n` checking if `grid[i][k]` equals `grid[k][j]`. If all elements match for a row and column pair, we increment the answer counter `ans`. Finally, return the value of `ans`.

## A solution in C++

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

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            bool equal = true;
            for (int k = 0; k < n; ++k) {
                if (grid[i][k] != grid[k][j]) {
                    equal = false;
                    break;
                }
            }
            if (equal) {
                ++ans;
            }
        }
    }

    return ans;
}
```
We use three nested loops to find the equal row and column pairs. For each row `i` and column `j`, we iterate through elements `k` from `0` to `n` checking if `grid[i][k]` equals `grid[k][j]`. If all elements match for a row and column pair, we increment the answer counter `ans`. Finally, return the value of `ans`.

## A solution in Python

```python
def countEqualRowColumnPairs(grid: List[List[int]]) -> int:
   n = len(grid)
   ans = 0

   for i in range(n):
      for j in range(n):
         equal = True
         for k in range(n):
             if grid[i][k] != grid[k][j]:
                 equal = False
                 break
         if equal:
             ans += 1

   return ans
```
We use three nested loops to find the equal row and column pairs. For each row `i` and column `j`, we iterate through elements `k` from `0` to `n` checking if `grid[i][k]` equals `grid[k][j]`. If all elements match for a row and column pair, we increment the answer counter `ans`. Finally, return the value of `ans`.

## A solution in Javascript

```javascript
function countEqualRowColumnPairs(grid) {
    let n = grid.length;
    let ans = 0;

    for (let i = 0; i < n; ++i) {
        for (let j = 0; j < n; ++j) {
            let equal = true;
            for (let k = 0; k < n; ++k) {
                if (grid[i][k] !== grid[k][j]) {
                    equal = false;
                    break;
                }
            }
            if (equal) {
                ++ans;
            }
        }
    }

    return ans;
}
```
We use three nested loops to find the equal row and column pairs. For each row `i` and column `j`, we iterate through elements `k` from `0` to `n` checking if `grid[i][k]` equals `grid[k][j]`. If all elements match for a row and column pair, we increment the answer counter `ans`. Finally, return the value of `ans`.