# Minimum Area Rectangle

- slug: minimum-area-rectangle
- difficulty: Medium

You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.

Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`.

**Example 1:**

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

**Example 2:**

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

**Constraints:**

*   `1 <= points.length <= 500`
*   `points[i].length == 2`
*   `0 <= xi, yi <= 4 * 104`
*   All the given points are **unique**.

## A solution in Java

```java
public int findValidPermutations(String s) {
    int n = s.length();
    long[] dp = new long[n + 2];
    dp[0] = 1;
    int MOD = 1000000007;

    for (char c : s.toCharArray()) {
        long[] new_dp = new long[n + 2];
        if (c == 'I') {
            for (int i = 0; i < n; ++i) {
                new_dp[i + 1] = (new_dp[i + 1] + dp[i]) % MOD;
            }
        } else {
            for (int i = n - 1; i >= 0; --i) {
                new_dp[i] = (new_dp[i + 1] + dp[i + 1]) % MOD;
            }
        }
        dp = new_dp;
    }
    return (int) dp[0];
}
```
The problem can be solved using dynamic programming. The main idea is to store the number of valid permutations at each position, for increasing and decreasing subsequences, based on the character in the input string. The DP array consists of n + 2 elements.

Iterate through the input string s. If the current character is 'I', that means the current element should be smaller than the next element. So, the count of valid permutations ending at position i should be added to the count of valid permutation for position (i + 1).

On the other hand, if the character is 'D', that means the current element should be greater than the next element. So, the count of valid permutations ending at position i should be added to the count of valid permutation for position i.

We use a new DP array in each iteration, which is then replaced with the original DP array. Repeating these steps, we can find the total number of valid permutations at the end. The result will be stored in the first element of the DP array: `dp[0]`.

Finally, return the result modulo 10^9 + 7, as mentioned in the problem statement.

## A solution in C++

```cpp
#include <vector>
#define MOD 1000000007

int findValidPermutations(const std::string& s) {
    int n = s.size();
    std::vector<long long> dp(n + 2, 0);
    dp[0] = 1;

    for (char c : s) {
        std::vector<long long> new_dp(n + 2, 0);
        if (c == 'I') {
            for (int i = 0; i < n; ++i) {
                new_dp[i + 1] = (new_dp[i + 1] + dp[i]) % MOD;
            }
        } else {
            for (int i = n - 1; i >= 0; --i) {
                new_dp[i] = (new_dp[i + 1] + dp[i + 1]) % MOD;
            }
        }
        dp = new_dp;
    }
    return dp[0];
}
```
The problem can be solved using dynamic programming. The main idea is to store the number of valid permutations at each position, for increasing and decreasing subsequences, based on the character in the input string. The DP array consists of n + 2 elements.

Iterate through the input string s. If the current character is 'I', that means the current element should be smaller than the next element. So, the count of valid permutations ending at position i should be added to the count of valid permutation for position (i + 1).

On the other hand, if the character is 'D', that means the current element should be greater than the next element. So, the count of valid permutations ending at position i should be added to the count of valid permutation for position i.

We use a new DP array in each iteration, which is then replaced with the original DP array. Repeating these steps, we can find the total number of valid permutations at the end. The result will be stored in the first element of the DP array: `dp[0]`.

Finally, return the result modulo 10^9 + 7, as mentioned in the problem statement.

## A solution in Python

```python
def find_valid_permutations(s: str) -> int:
    n = len(s)
    MOD = 1000000007
    dp = [0] * (n + 2)
    dp[0] = 1

    for c in s:
        new_dp = [0] * (n + 2)
        if c == 'I':
            for i in range(n):
                new_dp[i + 1] = (new_dp[i + 1] + dp[i]) % MOD
        else:
            for i in range(n - 1, -1, -1):
                new_dp[i] = (new_dp[i + 1] + dp[i + 1]) % MOD
        dp = new_dp

    return dp[0]
```
The problem can be solved using dynamic programming. The main idea is to store the number of valid permutations at each position, for increasing and decreasing subsequences, based on the character in the input string. The DP array consists of n + 2 elements.

Iterate through the input string s. If the current character is 'I', that means the current element should be smaller than the next element. So, the count of valid permutations ending at position i should be added to the count of valid permutation for position (i + 1).

On the other hand, if the character is 'D', that means the current element should be greater than the next element. So, the count of valid permutations ending at position i should be added to the count of valid permutation for position i.

We use a new DP array in each iteration, which is then replaced with the original DP array. Repeating these steps, we can find the total number of valid permutations at the end. The result will be stored in the first element of the DP array: `dp[0]`.

Finally, return the result modulo 10^9 + 7, as mentioned in the problem statement.

## A solution in Javascript

```javascript
function findValidPermutations(s) {
    const n = s.length;
    const MOD = 1000000007;
    let dp = new Array(n + 2).fill(0);
    dp[0] = 1;

    for (const c of s) {
        let new_dp = new Array(n + 2).fill(0);
        if (c === 'I') {
            for (let i = 0; i < n; ++i) {
                new_dp[i + 1] = (new_dp[i + 1] + dp[i]) % MOD;
            }
        } else {
            for (let i = n - 1; i >= 0; --i) {
                new_dp[i] = (new_dp[i + 1] + dp[i + 1]) % MOD;
            }
        }
        dp = new_dp;
    }
    return dp[0];
}
```
The problem can be solved using dynamic programming. The main idea is to store the number of valid permutations at each position, for increasing and decreasing subsequences, based on the character in the input string. The DP array consists of n + 2 elements.

Iterate through the input string s. If the current character is 'I', that means the current element should be smaller than the next element. So, the count of valid permutations ending at position i should be added to the count of valid permutation for position (i + 1).

On the other hand, if the character is 'D', that means the current element should be greater than the next element. So, the count of valid permutations ending at position i should be added to the count of valid permutation for position i.

We use a new DP array in each iteration, which is then replaced with the original DP array. Repeating these steps, we can find the total number of valid permutations at the end. The result will be stored in the first element of the DP array: `dp[0]`.

Finally, return the result modulo 10^9 + 7, as mentioned in the problem statement.


# Distinct Subsequences II

- slug: distinct-subsequences-ii
- difficulty: Hard

Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`.

A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not.

**Example 1:**

**Input:** s =  "abc "
**Output:** 7
**Explanation:** The 7 distinct subsequences are  "a ",  "b ",  "c ",  "ab ",  "ac ",  "bc ", and  "abc ".

**Example 2:**

**Input:** s =  "aba "
**Output:** 6
**Explanation:** The 6 distinct subsequences are  "a ",  "b ",  "ab ",  "aa ",  "ba ", and  "aba ".

**Example 3:**

**Input:** s =  "aaa "
**Output:** 3
**Explanation:** The 3 distinct subsequences are  "a ",  "aa " and  "aaa ".

**Constraints:**

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

## A solution in Java

```java
import java.util.HashMap;

public int totalFruit(int[] fruits) {
    int left = 0, right = 0, max_count = 0, n = fruits.length;
    HashMap<Integer, Integer> count = new HashMap<>();

    while (right < n) {
        count.put(fruits[right], count.getOrDefault(fruits[right], 0) + 1);
        while (count.size() > 2) {
            count.put(fruits[left], count.get(fruits[left]) - 1);
            if (count.get(fruits[left]) == 0) {
                count.remove(fruits[left]);
            }
            left++;
        }
        max_count = Math.max(max_count, right - left + 1);
        right++;
    }
    return max_count;
}
```
The algorithm uses a sliding window approach where two pointers "left" and "right" traverse through the `fruits` array while maintaining a frequency "count" hashmap (or map in JavaScript) to count the occurrences of different fruits in the current window.

1. First, initialize `left`, `right`, and `max_count` to 0, and an empty hashmap for `count`.
2. Perform a while loop where the condition is `right < length of fruits`.
3. Update the hashmap `count` with the fruit at the right index, incrementing the count by 1.
4. If the hashmap size is greater than 2, it means more than two types of fruits are in the current window, so we need to remove the leftmost fruit from the hashmap and increment the left pointer.
5. Calculate the maximum collected fruit count (`max_count`) by getting the max of the current `max_count` and the number of fruits in the current window (i.e., `right - left + 1`).
6. Increment the right pointer to move the window.
7. When the while loop finishes, return the `max_count`.

## A solution in C++

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

int totalFruit(vector<int>& fruits) {
    int left = 0, right = 0, max_count = 0, n = fruits.size();
    unordered_map<int, int> count;

    while (right < n) {
        count[fruits[right]]++;
        while (count.size() > 2) {
            count[fruits[left]]--;
            if (count[fruits[left]] == 0) {
                count.erase(fruits[left]);
            }
            left++;
        }
        max_count = max(max_count, right - left + 1);
        right++;
    }
    return max_count;
}
```
The algorithm uses a sliding window approach where two pointers "left" and "right" traverse through the `fruits` array while maintaining a frequency "count" hashmap (or map in JavaScript) to count the occurrences of different fruits in the current window.

1. First, initialize `left`, `right`, and `max_count` to 0, and an empty hashmap for `count`.
2. Perform a while loop where the condition is `right < length of fruits`.
3. Update the hashmap `count` with the fruit at the right index, incrementing the count by 1.
4. If the hashmap size is greater than 2, it means more than two types of fruits are in the current window, so we need to remove the leftmost fruit from the hashmap and increment the left pointer.
5. Calculate the maximum collected fruit count (`max_count`) by getting the max of the current `max_count` and the number of fruits in the current window (i.e., `right - left + 1`).
6. Increment the right pointer to move the window.
7. When the while loop finishes, return the `max_count`.

## A solution in Python

```python
def totalFruit(fruits):
    left, right, max_count = 0, 0, 0
    count = {}

    while right < len(fruits):
        count[fruits[right]] = count.get(fruits[right], 0) + 1
        while len(count) > 2:
            count[fruits[left]] -= 1
            if count[fruits[left]] == 0:
                del count[fruits[left]]
            left += 1
        max_count = max(max_count, right - left + 1)
        right += 1

    return max_count
```
The algorithm uses a sliding window approach where two pointers "left" and "right" traverse through the `fruits` array while maintaining a frequency "count" hashmap (or map in JavaScript) to count the occurrences of different fruits in the current window.

1. First, initialize `left`, `right`, and `max_count` to 0, and an empty hashmap for `count`.
2. Perform a while loop where the condition is `right < length of fruits`.
3. Update the hashmap `count` with the fruit at the right index, incrementing the count by 1.
4. If the hashmap size is greater than 2, it means more than two types of fruits are in the current window, so we need to remove the leftmost fruit from the hashmap and increment the left pointer.
5. Calculate the maximum collected fruit count (`max_count`) by getting the max of the current `max_count` and the number of fruits in the current window (i.e., `right - left + 1`).
6. Increment the right pointer to move the window.
7. When the while loop finishes, return the `max_count`.

## A solution in Javascript

```javascript
function totalFruit(fruits) {
    let left = 0, right = 0, max_count = 0;
    const count = new Map();

    while (right < fruits.length) {
        count.set(fruits[right], (count.get(fruits[right]) || 0) + 1);
        while (count.size > 2) {
            count.set(fruits[left], count.get(fruits[left]) - 1);
            if (count.get(fruits[left]) === 0) {
                count.delete(fruits[left]);
            }
            left++;
        }
        max_count = Math.max(max_count, right - left + 1);
        right++;
    }
    return max_count;
}
```
The algorithm uses a sliding window approach where two pointers "left" and "right" traverse through the `fruits` array while maintaining a frequency "count" hashmap (or map in JavaScript) to count the occurrences of different fruits in the current window.

1. First, initialize `left`, `right`, and `max_count` to 0, and an empty hashmap for `count`.
2. Perform a while loop where the condition is `right < length of fruits`.
3. Update the hashmap `count` with the fruit at the right index, incrementing the count by 1.
4. If the hashmap size is greater than 2, it means more than two types of fruits are in the current window, so we need to remove the leftmost fruit from the hashmap and increment the left pointer.
5. Calculate the maximum collected fruit count (`max_count`) by getting the max of the current `max_count` and the number of fruits in the current window (i.e., `right - left + 1`).
6. Increment the right pointer to move the window.
7. When the while loop finishes, return the `max_count`.


# Valid Mountain Array

- slug: valid-mountain-array
- difficulty: Easy

Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_.

Recall that arr is a mountain array if and only if:

*   `arr.length >= 3`
*   There exists some `i` with `0 < i < arr.length - 1` such that:
    *   `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
    *   `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`

**Example 1:**

**Input:** arr = \[2,1\]
**Output:** false

**Example 2:**

**Input:** arr = \[3,5,5\]
**Output:** false

**Example 3:**

**Input:** arr = \[0,3,2,1\]
**Output:** true

**Constraints:**

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

## A solution in Java

```java
public void moveEvenOdd(int[] nums) {
    int evenIndex = 0;
    int oddIndex = nums.length - 1;

    while (evenIndex < oddIndex) {
        if (nums[evenIndex] % 2 == 0) {
            evenIndex++;
        } else {
            int temp = nums[evenIndex];
            nums[evenIndex] = nums[oddIndex];
            nums[oddIndex] = temp;
            oddIndex--;
        }
    }
}
```
The algorithm uses two pointers, `evenIndex` and `oddIndex`. `evenIndex` starts from the beginning of the array, whereas `oddIndex` starts from the end. We iterate through the array until `evenIndex` is greater than or equal to `oddIndex`. Inside the loop, if `nums[evenIndex]` is even, we increment `evenIndex` because it's already in the correct position. If `nums[evenIndex]` is odd, we swap it with `nums[oddIndex]` and decrement `oddIndex`. Thus, we move even numbers to the beginning and odd numbers to the end of the array.

## A solution in C++

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

void moveEvenOdd(vector<int>& nums) {
    int evenIndex = 0;
    int oddIndex = nums.size() - 1;

    while (evenIndex < oddIndex) {
        if (nums[evenIndex] % 2 == 0) {
            evenIndex++;
        } else {
            swap(nums[evenIndex], nums[oddIndex]);
            oddIndex--;
        }
    }
}
```
The algorithm uses two pointers, `evenIndex` and `oddIndex`. `evenIndex` starts from the beginning of the array, whereas `oddIndex` starts from the end. We iterate through the array until `evenIndex` is greater than or equal to `oddIndex`. Inside the loop, if `nums[evenIndex]` is even, we increment `evenIndex` because it's already in the correct position. If `nums[evenIndex]` is odd, we swap it with `nums[oddIndex]` and decrement `oddIndex`. Thus, we move even numbers to the beginning and odd numbers to the end of the array.

## A solution in Python

```python
def move_even_odd(nums):
    even_index = 0
    odd_index = len(nums) - 1

    while even_index < odd_index:
        if nums[even_index] % 2 == 0:
            even_index += 1
        else:
            nums[even_index], nums[odd_index] = nums[odd_index], nums[even_index]
            odd_index -= 1

    return nums
```
The algorithm uses two pointers, `evenIndex` and `oddIndex`. `evenIndex` starts from the beginning of the array, whereas `oddIndex` starts from the end. We iterate through the array until `evenIndex` is greater than or equal to `oddIndex`. Inside the loop, if `nums[evenIndex]` is even, we increment `evenIndex` because it's already in the correct position. If `nums[evenIndex]` is odd, we swap it with `nums[oddIndex]` and decrement `oddIndex`. Thus, we move even numbers to the beginning and odd numbers to the end of the array.

## A solution in Javascript

```javascript
function moveEvenOdd(nums) {
    let evenIndex = 0;
    let oddIndex = nums.length - 1;

    while (evenIndex < oddIndex) {
        if (nums[evenIndex] % 2 === 0) {
            evenIndex++;
        } else {
            [nums[evenIndex], nums[oddIndex]] = [nums[oddIndex], nums[evenIndex]];
            oddIndex--;
        }
    }
}
```
The algorithm uses two pointers, `evenIndex` and `oddIndex`. `evenIndex` starts from the beginning of the array, whereas `oddIndex` starts from the end. We iterate through the array until `evenIndex` is greater than or equal to `oddIndex`. Inside the loop, if `nums[evenIndex]` is even, we increment `evenIndex` because it's already in the correct position. If `nums[evenIndex]` is odd, we swap it with `nums[oddIndex]` and decrement `oddIndex`. Thus, we move even numbers to the beginning and odd numbers to the end of the array.


# DI String Match

- slug: di-string-match
- difficulty: Easy

A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where:

*   `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and
*   `s[i] == 'D'` if `perm[i] > perm[i + 1]`.

Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**.

**Example 1:**

**Input:** s = "IDID"
**Output:** \[0,4,1,3,2\]

**Example 2:**

**Input:** s = "III"
**Output:** \[0,1,2,3\]

**Example 3:**

**Input:** s = "DDI"
**Output:** \[3,2,0,1\]

**Constraints:**

*   `1 <= s.length <= 105`
*   `s[i]` is either `'I'` or `'D'`.

## A solution in Java

```java
boolean isPalindrome(long num) {
    String str = Long.toString(num);
    String revStr = new StringBuilder(str).reverse().toString();
    return str.equals(revStr);
}

int superpalindromesInRange(String left, String right) {
    long l = Long.parseLong(left);
    long r = Long.parseLong(right);
    int cnt = 0;
    for (long base = 1; base * base <= r; ++base) {
        if (isPalindrome(base) && isPalindrome(base * base)) {
            if (base * base >= l) {
                cnt++;
            }
        }
    }
    return cnt;
}
```
To solve the problem, we will do the following steps:
1. Create a helper function `isPalindrome` to check if a given number is a palindrome.
2. Iterate over all the possible palindrome base numbers. For each base, check if the base and the square of the base are both palindromes. If they are, check if the square of the base is within the range [l, r] and increment a counter for each valid super-palindrome found.
3. Return the counter as the final result.

## A solution in C++

```cpp
bool isPalindrome(long num) {
    string str = to_string(num);
    string revStr = str;
    reverse(revStr.begin(), revStr.end());
    return str == revStr;
}

int superpalindromesInRange(string left, string right) {
    long l = stol(left);
    long r = stol(right);
    int cnt = 0;
    for (long base = 1; base * base <= r; ++base) {
        if (isPalindrome(base) && isPalindrome(base * base)) {
            if (base * base >= l) {
                cnt++;
            }
        }
    }
    return cnt;
}
```
To solve the problem, we will do the following steps:
1. Create a helper function `isPalindrome` to check if a given number is a palindrome.
2. Iterate over all the possible palindrome base numbers. For each base, check if the base and the square of the base are both palindromes. If they are, check if the square of the base is within the range [l, r] and increment a counter for each valid super-palindrome found.
3. Return the counter as the final result.

## A solution in Python

```python
def isPalindrome(num):
    return str(num) == str(num)[::-1]

def superpalindromesInRange(left: str, right: str) -> int:
    l = int(left)
    r = int(right)
    cnt = 0
    base = 1
    while base * base <= r:
        if isPalindrome(base) and isPalindrome(base * base):
            if base * base >= l:
                cnt += 1
        base += 1
    return cnt
```
To solve the problem, we will do the following steps:
1. Create a helper function `isPalindrome` to check if a given number is a palindrome.
2. Iterate over all the possible palindrome base numbers. For each base, check if the base and the square of the base are both palindromes. If they are, check if the square of the base is within the range [l, r] and increment a counter for each valid super-palindrome found.
3. Return the counter as the final result.

## A solution in Javascript

```javascript
function isPalindrome(num) {
    const str = num.toString();
    const revStr = str.split('').reverse().join('');
    return str === revStr;
}

function superpalindromesInRange(left, right) {
    const l = parseInt(left);
    const r = parseInt(right);
    let cnt = 0;
    for (let base = 1; base * base <= r; ++base) {
        if (isPalindrome(base) && isPalindrome(base * base)) {
            if (base * base >= l) {
                cnt++;
            }
        }
    }
    return cnt;
}
```
To solve the problem, we will do the following steps:
1. Create a helper function `isPalindrome` to check if a given number is a palindrome.
2. Iterate over all the possible palindrome base numbers. For each base, check if the base and the square of the base are both palindromes. If they are, check if the square of the base is within the range [l, r] and increment a counter for each valid super-palindrome found.
3. Return the counter as the final result.


# Find the Shortest Superstring

- slug: find-the-shortest-superstring
- difficulty: Hard

Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**.

You may assume that no string in `words` is a substring of another string in `words`.

**Example 1:**

**Input:** words = \[ "alex ", "loves ", "leetcode "\]
**Output:**  "alexlovesleetcode "
**Explanation:** All permutations of  "alex ", "loves ", "leetcode " would also be accepted.

**Example 2:**

**Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\]
**Output:**  "gctaagttcatgcatc "

**Constraints:**

*   `1 <= words.length <= 12`
*   `1 <= words[i].length <= 20`
*   `words[i]` consists of lowercase English letters.
*   All the strings of `words` are **unique**.

## A solution in Java

```java
public int sumOfMins(int[] arr) {
    int mod = (int)1e9 + 7;
    int n = arr.length;
    int[] left = new int[n], right = new int[n];
    Stack<Integer> st = new Stack<>();

    for (int i = 0; i < n; i++) {
        while (!st.isEmpty() && arr[st.peek()] > arr[i]) {
            st.pop();
        }
        left[i] = st.isEmpty() ? -1 : st.peek();
        st.push(i);
    }

    st.clear();
    for (int i = n - 1; i >= 0; i--) {
        while (!st.isEmpty() && arr[st.peek()] > arr[i]) {
            st.pop();
        }
        right[i] = st.isEmpty() ? n : st.peek();
        st.push(i);
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
        ans = (int)((ans + (long)arr[i] * (i - left[i]) * (right[i] - i)) % mod);
    }
    return ans;
}
```
To find the sum of minimum elements in all subarrays, we first find two auxiliary arrays, 'left' and 'right', which store the index of the closest smaller element for each element in the input array from left and right respectively.

We then iterate over the array and for each element, we find the product of the element, its distance to the previous smaller element (stored in 'left') and its distance to the next smaller element (stored in 'right'). The sum of these products for all elements in the array gives us the sum of minimums in all subarrays.

Finally, we return the total sum of minimums modulo 10^9 + 7.

## A solution in C++

```cpp
int sumOfMins(vector<int>& arr) {
    int mod = 1e9 + 7;
    int n = arr.size();
    vector<int> left(n), right(n);
    stack<int> st;

    for (int i = 0; i < n; i++) {
        while (!st.empty() && arr[st.top()] > arr[i]) {
            st.pop();
        }
        left[i] = st.empty() ? -1 : st.top();
        st.push(i);
    }

    while (!st.empty()) st.pop();
    for (int i = n - 1; i >= 0; i--) {
        while (!st.empty() && arr[st.top()] > arr[i]) {
            st.pop();
        }
        right[i] = st.empty() ? n : st.top();
        st.push(i);
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
        ans = (ans + arr[i] * (i - left[i]) * (right[i] - i)) % mod;
    }
    return ans;
}
```
To find the sum of minimum elements in all subarrays, we first find two auxiliary arrays, 'left' and 'right', which store the index of the closest smaller element for each element in the input array from left and right respectively.

We then iterate over the array and for each element, we find the product of the element, its distance to the previous smaller element (stored in 'left') and its distance to the next smaller element (stored in 'right'). The sum of these products for all elements in the array gives us the sum of minimums in all subarrays.

Finally, we return the total sum of minimums modulo 10^9 + 7.

## A solution in Python

```python
def sum_of_mins(arr):
    mod = 10**9 + 7
    n = len(arr)
    left, right = [0] * n, [0] * n
    st = []

    for i in range(n):
        while st and arr[st[-1]] > arr[i]:
            st.pop()
        left[i] = st[-1] if st else -1
        st.append(i)

    st.clear()
    for i in range(n - 1, -1, -1):
        while st and arr[st[-1]] > arr[i]:
            st.pop()
        right[i] = st[-1] if st else n
        st.append(i)

    ans = 0
    for i in range(n):
        ans = (ans + arr[i] * (i - left[i]) * (right[i] - i)) % mod
    return ans
```
To find the sum of minimum elements in all subarrays, we first find two auxiliary arrays, 'left' and 'right', which store the index of the closest smaller element for each element in the input array from left and right respectively.

We then iterate over the array and for each element, we find the product of the element, its distance to the previous smaller element (stored in 'left') and its distance to the next smaller element (stored in 'right'). The sum of these products for all elements in the array gives us the sum of minimums in all subarrays.

Finally, we return the total sum of minimums modulo 10^9 + 7.

## A solution in Javascript

```javascript
function sumOfMins(arr) {
    let mod = 1e9 + 7;
    let n = arr.length;
    let left = new Array(n), right = new Array(n);
    let st = [];

    for (let i = 0; i < n; i++) {
        while (st.length && arr[st[st.length - 1]] > arr[i]) {
            st.pop();
        }
        left[i] = st.length === 0 ? -1 : st[st.length - 1];
        st.push(i);
    }

    st = [];
    for (let i = n - 1; i >= 0; i--) {
        while (st.length && arr[st[st.length - 1]] > arr[i]) {
            st.pop();
        }
        right[i] = st.length === 0 ? n : st[st.length - 1];
        st.push(i);
    }

    let ans = 0;
    for (let i = 0; i < n; i++) {
        ans = (ans + arr[i] * (i - left[i]) * (right[i] - i)) % mod;
    }
    return ans;
}
```
To find the sum of minimum elements in all subarrays, we first find two auxiliary arrays, 'left' and 'right', which store the index of the closest smaller element for each element in the input array from left and right respectively.

We then iterate over the array and for each element, we find the product of the element, its distance to the previous smaller element (stored in 'left') and its distance to the next smaller element (stored in 'right'). The sum of these products for all elements in the array gives us the sum of minimums in all subarrays.

Finally, we return the total sum of minimums modulo 10^9 + 7.


# Delete Columns to Make Sorted

- slug: delete-columns-to-make-sorted
- difficulty: Easy

You are given an array of `n` strings `strs`, all of the same length.

The strings can be arranged such that there is one on each line, making a grid.

*   For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows:

abc
bce
cae

You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1.

Return _the number of columns that you will delete_.

**Example 1:**

**Input:** strs = \[ "cba ", "daf ", "ghi "\]
**Output:** 1
**Explanation:** The grid looks as follows:
  cba
  daf
  ghi
Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.

**Example 2:**

**Input:** strs = \[ "a ", "b "\]
**Output:** 0
**Explanation:** The grid looks as follows:
  a
  b
Column 0 is the only column and is sorted, so you will not delete any columns.

**Example 3:**

**Input:** strs = \[ "zyx ", "wvu ", "tsr "\]
**Output:** 3
**Explanation:** The grid looks as follows:
  zyx
  wvu
  tsr
All 3 columns are not sorted, so you will delete all 3.

**Constraints:**

*   `n == strs.length`
*   `1 <= n <= 100`
*   `1 <= strs[i].length <= 1000`
*   `strs[i]` consists of lowercase English letters.

## A solution in Java

```java
public int minDifference(int[] nums, int k) {
    if(nums.length <= 1) return 0;
    Arrays.sort(nums);
    int min_diff = nums[nums.length - 1] - nums[0];
    for(int i = 1; i < nums.length; i++) {
        int high = Math.max(nums[i - 1] + k, nums[nums.length - 1] - k);
        int low = Math.min(nums[i] - k, nums[0] + k);
        min_diff = Math.min(min_diff, high - low);
    }
    return min_diff;
}
```
The algorithm first sorts the input array nums. If there is only 1 element or no element in the array, then the minimum difference becomes 0. Otherwise, the algorithm initializes the minimum difference as the difference between the maximum and minimum elements. Then, it iterates through the nums array and for each element, selects the highest and lowest values after applying the operation with k. Update the minimum difference as necessary by comparing the current high-low value difference with the minimum difference calculated so far. The algorithm does not modify the original nums array but rather focuses on updating the minimum difference variable. After finishing the iteration, the minimum difference is returned.

## A solution in C++

```cpp
int minDifference(vector<int>& nums, int k) {
    if(nums.size() <= 1) return 0;
    sort(nums.begin(), nums.end());
    int min_diff = nums.back() - nums.front();
    for(int i=1; i<nums.size(); i++) {
        int high = max(nums[i-1] + k, nums.back() - k);
        int low = min(nums[i] - k, nums.front() + k);
        min_diff = min(min_diff, high - low);
    }
    return min_diff;
}
```
The algorithm first sorts the input array nums. If there is only 1 element or no element in the array, then the minimum difference becomes 0. Otherwise, the algorithm initializes the minimum difference as the difference between the maximum and minimum elements. Then, it iterates through the nums array and for each element, selects the highest and lowest values after applying the operation with k. Update the minimum difference as necessary by comparing the current high-low value difference with the minimum difference calculated so far. The algorithm does not modify the original nums array but rather focuses on updating the minimum difference variable. After finishing the iteration, the minimum difference is returned.

## A solution in Python

```python
def minDifference(nums, k):
    if len(nums) <= 1: return 0
    nums.sort()
    min_diff = nums[-1] - nums[0]
    for i in range(1, len(nums)):
        high = max(nums[i-1] + k, nums[-1] - k)
        low = min(nums[i] - k, nums[0] + k)
        min_diff = min(min_diff, high - low)
    return min_diff
```
The algorithm first sorts the input array nums. If there is only 1 element or no element in the array, then the minimum difference becomes 0. Otherwise, the algorithm initializes the minimum difference as the difference between the maximum and minimum elements. Then, it iterates through the nums array and for each element, selects the highest and lowest values after applying the operation with k. Update the minimum difference as necessary by comparing the current high-low value difference with the minimum difference calculated so far. The algorithm does not modify the original nums array but rather focuses on updating the minimum difference variable. After finishing the iteration, the minimum difference is returned.

## A solution in Javascript

```javascript
function minDifference(nums, k) {
    if(nums.length <= 1) return 0;
    nums.sort((a, b) => a - b);
    let min_diff = nums[nums.length - 1] - nums[0];
    for(let i = 1; i < nums.length; i++) {
        let high = Math.max(nums[i - 1] + k, nums[nums.length - 1] - k);
        let low = Math.min(nums[i] - k, nums[0] + k);
        min_diff = Math.min(min_diff, high - low);
    }
    return min_diff;
}
```
The algorithm first sorts the input array nums. If there is only 1 element or no element in the array, then the minimum difference becomes 0. Otherwise, the algorithm initializes the minimum difference as the difference between the maximum and minimum elements. Then, it iterates through the nums array and for each element, selects the highest and lowest values after applying the operation with k. Update the minimum difference as necessary by comparing the current high-low value difference with the minimum difference calculated so far. The algorithm does not modify the original nums array but rather focuses on updating the minimum difference variable. After finishing the iteration, the minimum difference is returned.


# Minimum Increment to Make Array Unique

- slug: minimum-increment-to-make-array-unique
- difficulty: Medium

You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`.

Return _the minimum number of moves to make every value in_ `nums` _**unique**_.

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

**Example 1:**

**Input:** nums = \[1,2,2\]
**Output:** 1
**Explanation:** After 1 move, the array could be \[1, 2, 3\].

**Example 2:**

**Input:** nums = \[3,2,1,2,1,7\]
**Output:** 6
**Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\].
It can be shown with 5 or less moves that it is impossible for the array to have all unique values.

**Constraints:**

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

## A solution in Java

```java
public int snakesAndLadders(int[][] board) {
    int n = board.length;
    int[] flattenedBoard = new int[n * n + 1];
    boolean isRight = true;
    int idx = 1;
    for (int i = n - 1; i >= 0; i--) {
        if (isRight) {
            for (int j = 0; j < n; j++) {
                flattenedBoard[idx++] = board[i][j];
            }
        } else {
            for (int j = n - 1; j >= 0; j--) {
                flattenedBoard[idx++] = board[i][j];
            }
        }
        isRight = !isRight;
    }

    int[] moves = new int[n * n + 1];
    Arrays.fill(moves, -1);
    moves[1] = 0;
    for (int i = 0; i < moves.length; i++) {
        if (moves[i] != -1) {
            for (int j = 1; j <= 6 && i + j < moves.length; j++) {
                int nextPos = i + j;
                int value = flattenedBoard[nextPos];
                if (value == -1) {
                    value = nextPos;
                }
                if (moves[value] == -1) {
                    moves[value] = moves[i] + 1;
                }
            }
        }
    }
    return moves[n * n];
}
```
1. First, initialize a visited array to keep track of the visited squares.
2. Use a queue for the BFS traversal, starting from square 1 with the initial number of steps as 0.
3. Write a helper function `getPosition` to get the row and column indices of a given square position in the Boustrophedon style.
4. While there are still squares left in the queue, perform BFS by checking all possible 1 to 6 steps from the current position.
5. If the destination square has a snake or ladder (i.e., != -1), move to the corresponding index on the board.
6. If the next position to visit is the target square (n^2), return the steps taken.
7. If the next position has not been visited yet, add it to the queue and mark it as visited.
8. If no path is found to reach the target square, return -1.

## A solution in C++

```cpp
int snakesAndLadders(vector<vector<int>> &board) {
    int n = board.size();
    auto getRowCol = [&](int x) {
        int r = (x - 1) / n, c = (x - 1) % n;
        if (r % 2) c = n - 1 - c;
        return make_pair(n - 1 - r, c);
    };

    vector<bool> visited(n * n + 1, false);
    queue<pair<int, int>> q;
    q.push({1, 0});
    visited[1] = true;

    while (!q.empty()) {
        auto cur = q.front(); q.pop();
        int x = cur.first;
        int steps = cur.second;
        for (int jump = 1; jump <= 6; jump++) {
            int next_x = x + jump;
            if (next_x > n * n) break;
            auto nextRC = getRowCol(next_x);
            if (board[nextRC.first][nextRC.second] != -1) {
                next_x = board[nextRC.first][nextRC.second];
            }
            if (next_x == n * n) return steps + 1;
            if (!visited[next_x]) {
                visited[next_x] = true;
                q.push({next_x, steps + 1});
            }
        }
    }
    return -1;
}
```
1. First, initialize a visited array to keep track of the visited squares.
2. Use a queue for the BFS traversal, starting from square 1 with the initial number of steps as 0.
3. Write a helper function `getPosition` to get the row and column indices of a given square position in the Boustrophedon style.
4. While there are still squares left in the queue, perform BFS by checking all possible 1 to 6 steps from the current position.
5. If the destination square has a snake or ladder (i.e., != -1), move to the corresponding index on the board.
6. If the next position to visit is the target square (n^2), return the steps taken.
7. If the next position has not been visited yet, add it to the queue and mark it as visited.
8. If no path is found to reach the target square, return -1.

## A solution in Python

```python
def snakesAndLadders(board):
    n = len(board)
    visited = [False] * (n*n + 1)
    queue = [(1, 0)]  # starting at position 1
    visited[1] = True

    def get_position(pos):
        r = (pos - 1) // n
        c = (pos - 1) % n
        if r % 2 == 1:
            c = n - 1 - c
        r = n - r - 1
        return r, c

    while queue:
        pos, steps = queue.pop(0)
        for jump in range(1, 7):
            next_pos = pos + jump
            if next_pos > n*n:
                break
            r, c = get_position(next_pos)
            if board[r][c] != -1:
                next_pos = board[r][c]
            if next_pos == n*n:
                return steps + 1
            if not visited[next_pos]:
                visited[next_pos] = True
                queue.append((next_pos, steps + 1))

    return -1
```
1. First, initialize a visited array to keep track of the visited squares.
2. Use a queue for the BFS traversal, starting from square 1 with the initial number of steps as 0.
3. Write a helper function `getPosition` to get the row and column indices of a given square position in the Boustrophedon style.
4. While there are still squares left in the queue, perform BFS by checking all possible 1 to 6 steps from the current position.
5. If the destination square has a snake or ladder (i.e., != -1), move to the corresponding index on the board.
6. If the next position to visit is the target square (n^2), return the steps taken.
7. If the next position has not been visited yet, add it to the queue and mark it as visited.
8. If no path is found to reach the target square, return -1.

## A solution in Javascript

```javascript
function snakesAndLadders(board) {
  const n = board.length;
  const visited = new Array(n * n + 1).fill(false);
  const queue = [{ pos: 1, steps: 0 }];
  visited[1] = true;

  function getPosition(pos) {
    const row = Math.ceil(pos / n);
    let col = ((row % 2) === 0) ? n - (pos % n) : (pos % n) + 1;
    if (col === n + 1) {
      col = 1;
    }
    return [n - row, col - 1];
  }

  while (queue.length) {
    const { pos, steps } = queue.shift();

    for (let jump = 1; jump <= 6; jump++) {
      let nextPos = pos + jump;
      if (nextPos > n * n) break;
      const [r, c] = getPosition(nextPos);
      if (board[r][c] !== -1) {
        nextPos = board[r][c];
      }
      if (nextPos === n * n) return steps + 1;
      if (!visited[nextPos]) {
        visited[nextPos] = true;
        queue.push({ pos: nextPos, steps: steps + 1 });
      }
    }
  }
  return -1;
}
```
1. First, initialize a visited array to keep track of the visited squares.
2. Use a queue for the BFS traversal, starting from square 1 with the initial number of steps as 0.
3. Write a helper function `getPosition` to get the row and column indices of a given square position in the Boustrophedon style.
4. While there are still squares left in the queue, perform BFS by checking all possible 1 to 6 steps from the current position.
5. If the destination square has a snake or ladder (i.e., != -1), move to the corresponding index on the board.
6. If the next position to visit is the target square (n^2), return the steps taken.
7. If the next position has not been visited yet, add it to the queue and mark it as visited.
8. If no path is found to reach the target square, return -1.


# Validate Stack Sequences

- slug: validate-stack-sequences
- difficulty: Medium

Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._

**Example 1:**

**Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\]
**Output:** true
**Explanation:** We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

**Example 2:**

**Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\]
**Output:** false
**Explanation:** 1 cannot be popped before 2.

**Constraints:**

*   `1 <= pushed.length <= 1000`
*   `0 <= pushed[i] <= 1000`
*   All the elements of `pushed` are **unique**.
*   `popped.length == pushed.length`
*   `popped` is a permutation of `pushed`.

## A solution in Java

```java
public int minimumScore(int[] nums, int k) {
    Arrays.sort(nums);
    int n = nums.length;
    int res = nums[n - 1] - nums[0];

    for (int i = 0; i < n - 1; i++) {
        int high = Math.max(nums[i] + k, nums[n - 1] - k);
        int low = Math.min(nums[i + 1] - k, nums[0] + k);
        res = Math.min(res, high - low);
    }

    return res;
}
```
1. First, sort the given integer array `nums` in ascending order.
2. Initialize the result `res` to the initial difference between the maximum and the minimum elements in the array.
3. Iterate through the array, from index 0 to index `nums.length - 2`. For each index `i`, do the following:
   - Calculate `high` as the maximum of `(nums[i] + k)` and `(nums[nums.length - 1] - k)`.
   - Calculate `low` as the minimum of `(nums[i + 1] - k)` and `(nums[0] + k)`.
   - Update the result `res` to the minimum of itself and the difference between `high` and `low`.
4. Return the final result `res` as the minimum score of nums after changing the values at each index.

## A solution in C++

```cpp
int minimumScore(vector<int>& nums, int k) {
    sort(nums.begin(), nums.end());
    int n = nums.size();
    int res = nums[n - 1] - nums[0];

    for (int i = 0; i < n - 1; ++i) {
        int high = max(nums[i] + k, nums[n - 1] - k);
        int low = min(nums[i + 1] - k, nums[0] + k);
        res = min(res, high - low);
    }

    return res;
}
```
1. First, sort the given integer array `nums` in ascending order.
2. Initialize the result `res` to the initial difference between the maximum and the minimum elements in the array.
3. Iterate through the array, from index 0 to index `nums.length - 2`. For each index `i`, do the following:
   - Calculate `high` as the maximum of `(nums[i] + k)` and `(nums[nums.length - 1] - k)`.
   - Calculate `low` as the minimum of `(nums[i + 1] - k)` and `(nums[0] + k)`.
   - Update the result `res` to the minimum of itself and the difference between `high` and `low`.
4. Return the final result `res` as the minimum score of nums after changing the values at each index.

## A solution in Python

```python
def minimum_score(nums, k):
    nums.sort()
    n = len(nums)
    res = nums[n - 1] - nums[0]

    for i in range(n - 1):
        high = max(nums[i] + k, nums[n - 1] - k)
        low = min(nums[i + 1] - k, nums[0] + k)
        res = min(res, high - low)

    return res
```
1. First, sort the given integer array `nums` in ascending order.
2. Initialize the result `res` to the initial difference between the maximum and the minimum elements in the array.
3. Iterate through the array, from index 0 to index `nums.length - 2`. For each index `i`, do the following:
   - Calculate `high` as the maximum of `(nums[i] + k)` and `(nums[nums.length - 1] - k)`.
   - Calculate `low` as the minimum of `(nums[i + 1] - k)` and `(nums[0] + k)`.
   - Update the result `res` to the minimum of itself and the difference between `high` and `low`.
4. Return the final result `res` as the minimum score of nums after changing the values at each index.

## A solution in Javascript

```javascript
function minimumScore(nums, k) {
    nums.sort((a, b) => a - b);
    const n = nums.length;
    let res = nums[n - 1] - nums[0];

    for (let i = 0; i < n - 1; i++) {
        const high = Math.max(nums[i] + k, nums[n - 1] - k);
        const low = Math.min(nums[i + 1] - k, nums[0] + k);
        res = Math.min(res, high - low);
    }

    return res;
}
```
1. First, sort the given integer array `nums` in ascending order.
2. Initialize the result `res` to the initial difference between the maximum and the minimum elements in the array.
3. Iterate through the array, from index 0 to index `nums.length - 2`. For each index `i`, do the following:
   - Calculate `high` as the maximum of `(nums[i] + k)` and `(nums[nums.length - 1] - k)`.
   - Calculate `low` as the minimum of `(nums[i + 1] - k)` and `(nums[0] + k)`.
   - Update the result `res` to the minimum of itself and the difference between `high` and `low`.
4. Return the final result `res` as the minimum score of nums after changing the values at each index.


# Most Stones Removed with Same Row or Column

- slug: most-stones-removed-with-same-row-or-column
- difficulty: Medium

On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone.

A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed.

Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_.

**Example 1:**

**Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 5
**Explanation:** One way to remove 5 stones is as follows:
1. Remove stone \[2,2\] because it shares the same row as \[2,1\].
2. Remove stone \[2,1\] because it shares the same column as \[0,1\].
3. Remove stone \[1,2\] because it shares the same row as \[1,0\].
4. Remove stone \[1,0\] because it shares the same column as \[0,0\].
5. Remove stone \[0,1\] because it shares the same row as \[0,0\].
Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane.

**Example 2:**

**Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\]
**Output:** 3
**Explanation:** One way to make 3 moves is as follows:
1. Remove stone \[2,2\] because it shares the same row as \[2,0\].
2. Remove stone \[2,0\] because it shares the same column as \[0,0\].
3. Remove stone \[0,2\] because it shares the same row as \[0,0\].
Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane.

**Example 3:**

**Input:** stones = \[\[0,0\]\]
**Output:** 0
**Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it.

**Constraints:**

*   `1 <= stones.length <= 1000`
*   `0 <= xi, yi <= 104`
*   No two stones are at the same coordinate point.

## A solution in Java

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

class TopVotedCandidate {
    TreeMap<Integer, Integer> leaderMap;

    public TopVotedCandidate(int[] persons, int[] times) {
        leaderMap = new TreeMap<>();
        Map<Integer, Integer> votes = new HashMap<>();
        int leader = -1;
        for (int i = 0; i < times.length; i++) {
            votes.put(persons[i], votes.getOrDefault(persons[i], 0) + 1);
            if (votes.get(persons[i]) >= votes.getOrDefault(leader, 0)) {
                leader = persons[i];
            }
            leaderMap.put(times[i], leader);
        }
    }

    public int q(int t) {
        return leaderMap.floorEntry(t).getValue();
    }
}
```
1. We maintain a leader_map, which maps the time of the new leader to the leader itself. We fill it while iterating through the given arrays persons and times.
2. For each person and time, we increment the vote count for the specified person.
3. If the number of votes for the current person is greater than or equal to the votes of the current leader, we update the leader and map the current time to the current leader in the leader_map.
4. For each query, we find the 1st smaller time index of the given time 't', using upper_bound in C++ or floorEntry in Java or bisect.bisect in Python or findIndex in JavaScript.
5. We return the leader associated with that 1st smaller time index.

## A solution in C++

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

class TopVotedCandidate {
public:
    map<int, int> leaderMap;

    TopVotedCandidate(vector<int> persons, vector<int> times) {
        int leader = -1;
        map<int, int> votes;
        for (int i = 0; i < times.size(); ++i){
            votes[persons[i]]++;
            if (votes[persons[i]] >= votes[leader]){
                leader = persons[i];
            }
            leaderMap[times[i]] = leader;
        }
    }

    int q(int t){
        auto it = leaderMap.upper_bound(t);
        return prev(it)->second;
    }
};
```
1. We maintain a leader_map, which maps the time of the new leader to the leader itself. We fill it while iterating through the given arrays persons and times.
2. For each person and time, we increment the vote count for the specified person.
3. If the number of votes for the current person is greater than or equal to the votes of the current leader, we update the leader and map the current time to the current leader in the leader_map.
4. For each query, we find the 1st smaller time index of the given time 't', using upper_bound in C++ or floorEntry in Java or bisect.bisect in Python or findIndex in JavaScript.
5. We return the leader associated with that 1st smaller time index.

## A solution in Python

```python
from collections import defaultdict
from bisect import bisect

class TopVotedCandidate:

    def __init__(self, persons, times):
        self.leader_map = {}
        self.times = times
        votes = defaultdict(int)
        leader = -1
        for i, t in enumerate(times):
            votes[persons[i]] += 1
            if votes[persons[i]] >= votes[leader]:
                leader = persons[i]
            self.leader_map[t] = leader

    def q(self, t):
        idx = bisect.bisect(self.times, t)
        return self.times[idx - 1]
```
1. We maintain a leader_map, which maps the time of the new leader to the leader itself. We fill it while iterating through the given arrays persons and times.
2. For each person and time, we increment the vote count for the specified person.
3. If the number of votes for the current person is greater than or equal to the votes of the current leader, we update the leader and map the current time to the current leader in the leader_map.
4. For each query, we find the 1st smaller time index of the given time 't', using upper_bound in C++ or floorEntry in Java or bisect.bisect in Python or findIndex in JavaScript.
5. We return the leader associated with that 1st smaller time index.

## A solution in Javascript

```javascript
class TopVotedCandidate {
    constructor(persons, times) {
        this.leaderMap = new Map();
        this.times = times;
        let votes = new Map();
        let leader = -1;
        for (let i = 0; i < times.length; i++) {
            votes.set(persons[i], (votes.get(persons[i]) || 0) + 1);
            if (votes.get(persons[i]) >= (votes.get(leader) || 0)) {
                leader = persons[i];
            }
            this.leaderMap.set(times[i], leader);
        }
    }

    q(t) {
        let idx = this.times.findIndex(time => time > t);
        if (idx == -1) idx = this.times.length;
        return this.leaderMap.get(this.times[idx - 1]);
    }
}
```
1. We maintain a leader_map, which maps the time of the new leader to the leader itself. We fill it while iterating through the given arrays persons and times.
2. For each person and time, we increment the vote count for the specified person.
3. If the number of votes for the current person is greater than or equal to the votes of the current leader, we update the leader and map the current time to the current leader in the leader_map.
4. For each query, we find the 1st smaller time index of the given time 't', using upper_bound in C++ or floorEntry in Java or bisect.bisect in Python or findIndex in JavaScript.
5. We return the leader associated with that 1st smaller time index.


# Bag of Tokens

- slug: bag-of-tokens
- difficulty: Medium

You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed).

Your goal is to maximize your total **score** by potentially playing each token in one of two ways:

*   If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**.
*   If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**.

Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens.

Return _the largest possible **score** you can achieve after playing any number of tokens_.

**Example 1:**

**Input:** tokens = \[100\], power = 50
**Output:** 0
**Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score.

**Example 2:**

**Input:** tokens = \[100,200\], power = 150
**Output:** 1
**Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1.
There is no need to play the 1st token since you cannot play it face up to add to your score.

**Example 3:**

**Input:** tokens = \[100,200,300,400\], power = 200
**Output:** 2
**Explanation:** Play the tokens in this order to get a score of 2:
1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1.
2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0.
3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1.
4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.

**Constraints:**

*   `0 <= tokens.length <= 1000`
*   `0 <= tokens[i], power < 104`

## A solution in Java

```java
import java.util.Arrays;

public void sortArray(int[] nums) {
    Arrays.sort(nums);
}
```
The algorithm for each language uses the built-in sorting function provided by the language's standard library to sort the given array of integers in ascending order.

- In C++, the `std::sort` function from the `<algorithm>` library is used.
- In Java, the `Arrays.sort` method from the `java.util` package is used.
- In Python, the in-built `sort` method of the list object (nums) is used.
- In JavaScript, the `Array.prototype.sort` method is used with a custom comparator function `(a, b) => a - b` to ensure numeric sorting instead of lexicographic sorting (the default behavior of JavaScript's sort).

All these built-in methods use efficient sorting algorithms underneath, with average-case complexity of O(n log n).

## A solution in C++

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

void sortArray(std::vector<int>& nums) {
    std::sort(nums.begin(), nums.end());
}
```
The algorithm for each language uses the built-in sorting function provided by the language's standard library to sort the given array of integers in ascending order.

- In C++, the `std::sort` function from the `<algorithm>` library is used.
- In Java, the `Arrays.sort` method from the `java.util` package is used.
- In Python, the in-built `sort` method of the list object (nums) is used.
- In JavaScript, the `Array.prototype.sort` method is used with a custom comparator function `(a, b) => a - b` to ensure numeric sorting instead of lexicographic sorting (the default behavior of JavaScript's sort).

All these built-in methods use efficient sorting algorithms underneath, with average-case complexity of O(n log n).

## A solution in Python

```python
def sortArray(nums):
    nums.sort()
```
The algorithm for each language uses the built-in sorting function provided by the language's standard library to sort the given array of integers in ascending order.

- In C++, the `std::sort` function from the `<algorithm>` library is used.
- In Java, the `Arrays.sort` method from the `java.util` package is used.
- In Python, the in-built `sort` method of the list object (nums) is used.
- In JavaScript, the `Array.prototype.sort` method is used with a custom comparator function `(a, b) => a - b` to ensure numeric sorting instead of lexicographic sorting (the default behavior of JavaScript's sort).

All these built-in methods use efficient sorting algorithms underneath, with average-case complexity of O(n log n).

## A solution in Javascript

```javascript
function sortArray(nums) {
    nums.sort((a, b) => a - b);
}
```
The algorithm for each language uses the built-in sorting function provided by the language's standard library to sort the given array of integers in ascending order.

- In C++, the `std::sort` function from the `<algorithm>` library is used.
- In Java, the `Arrays.sort` method from the `java.util` package is used.
- In Python, the in-built `sort` method of the list object (nums) is used.
- In JavaScript, the `Array.prototype.sort` method is used with a custom comparator function `(a, b) => a - b` to ensure numeric sorting instead of lexicographic sorting (the default behavior of JavaScript's sort).

All these built-in methods use efficient sorting algorithms underneath, with average-case complexity of O(n log n).


# Largest Time for Given Digits

- slug: largest-time-for-given-digits
- difficulty: Medium

Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**.

24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`.

Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string.

**Example 1:**

**Input:** arr = \[1,2,3,4\]
**Output:**  "23:41 "
**Explanation:** The valid 24-hour times are  "12:34 ",  "12:43 ",  "13:24 ",  "13:42 ",  "14:23 ",  "14:32 ",  "21:34 ",  "21:43 ",  "23:14 ", and  "23:41 ". Of these times,  "23:41 " is the latest.

**Example 2:**

**Input:** arr = \[5,5,5,5\]
**Output:**  " "
**Explanation:** There are no valid 24-hour times as  "55:55 " is not valid.

**Constraints:**

*   `arr.length == 4`
*   `0 <= arr[i] <= 9`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int catMouseGame(int[][] graph) {
        int n = graph.length;
        int[][][] status = new int[n][n][3];
        Queue<Status> queue = new LinkedList<>();

        for (int i = 1; i < n; ++i) {
            Arrays.fill(status[i][i], 2);
            queue.add(new Status(i, i, 2, 2));
            queue.add(new Status(i, i, 1, 2));
        }

        while (!queue.isEmpty()) {
            Status t = queue.poll();
            int pos_m = t.mouse, pos_c = t.cat, t_type = t.type, t_result = t.result;

            for (int prev : t_type == 1 ? graph[pos_m] : graph[pos_c]) {
                if (t_type == 2 && prev == 0 || t_result == 2 && status[prev][pos_c][3 - t_type] != 0) continue;
                if (status[prev][pos_c][3 - t_type] != 0) continue;
                queue.add(new Status(pos_c, prev, 3 - t_type, 3 - t_result));
                status[prev][pos_c][3 - t_type] = 3 - t_result;
            }
        }
        return status[1][2][1];
    }

    private class Status {
        int mouse, cat, type, result;
        Status(int mouse, int cat, int type, int result) {
            this.mouse = mouse;
            this.cat = cat;
            this.type = type;
            this.result = result;
        }
    }
}
```
1. Initialize a 3D array `status` to track game state, representing the positions of the cat and mouse, and if it's the cat's or mouse's turn (state can also include whether the game has ended and who wins).
2. Fill in the base game state where cat and mouse are in the same position (cat catches the mouse) and push such states to a queue.
3. Perform a breadth-first search on the queue, where we visit each situation based on the current game state and the type of next move. If the cat's turn, don't allow the cat to go to the hole (node 0). If the mouse's turn, ignore mouse moves to a state which the cat wins. If there's a feasible move, update the status array and push it to the queue.
4. At the end, `status[1][2][1]` denotes the result of the game (1 for the mouse escapes, 2 for the cat catches the mouse, otherwise 0 for a draw).

## A solution in C++

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

int catMouseGame(vector<vector<int>>& graph) {
    int n = graph.size();
    vector<vector<vector<int>>> status(n, vector<vector<int>>(n, vector<int>(3, -1)));
    queue<tuple<int, int, int, int>> q;
    for (int i = 1; i < n; ++i) {
        status[i][i][1] = 2;
        status[i][i][2] = 2;
        q.push({i, i, 2, 2});
        q.push({i, i, 1, 2});
    }
    while (!q.empty()) {
        tuple<int, int, int, int> t = q.front();
        q.pop();
        int pos_m = get<0>(t), pos_c = get<1>(t), t_type = get<2>(t), t_result = get<3>(t);
        for (int prev : t_type == 1 ? graph[pos_m] : graph[pos_c]) {
            if (t_type == 2 && prev == 0 || t_result == 2 && status[prev][pos_c][3 - t_type] != -1) continue;
            if (status[prev][pos_c][3 - t_type] != -1) continue;
            q.push({pos_c, prev, 3 - t_type, 3 - t_result});
            status[prev][pos_c][3 - t_type] = 3 - t_result;
        }
    }
    return status[1][2][1];
}
```
1. Initialize a 3D array `status` to track game state, representing the positions of the cat and mouse, and if it's the cat's or mouse's turn (state can also include whether the game has ended and who wins).
2. Fill in the base game state where cat and mouse are in the same position (cat catches the mouse) and push such states to a queue.
3. Perform a breadth-first search on the queue, where we visit each situation based on the current game state and the type of next move. If the cat's turn, don't allow the cat to go to the hole (node 0). If the mouse's turn, ignore mouse moves to a state which the cat wins. If there's a feasible move, update the status array and push it to the queue.
4. At the end, `status[1][2][1]` denotes the result of the game (1 for the mouse escapes, 2 for the cat catches the mouse, otherwise 0 for a draw).

## A solution in Python

```python
from collections import deque

def catMouseGame(graph):
    n = len(graph)
    status = [[[0]*3 for _ in range(n)] for _ in range(n)]

    for i in range(1, n):
        status[i][i][1] = 2
        status[i][i][2] = 2
    queue = deque([(i, i, t, 2) for i in range(1, n) for t in (1, 2)])

    while queue:
        pos_m, pos_c, t_type, t_result = queue.popleft()

        for prev in graph[pos_m if t_type == 1 else pos_c]:
            if (t_type == 2 and prev == 0) or (t_result == 2 and status[prev][pos_c][3 - t_type]):
                continue
            if status[prev][pos_c][3 - t_type]:
                continue
            queue.append((pos_c, prev, 3 - t_type, 3 - t_result))
            status[prev][pos_c][3 - t_type] = 3 - t_result

    return status[1][2][1]
```
1. Initialize a 3D array `status` to track game state, representing the positions of the cat and mouse, and if it's the cat's or mouse's turn (state can also include whether the game has ended and who wins).
2. Fill in the base game state where cat and mouse are in the same position (cat catches the mouse) and push such states to a queue.
3. Perform a breadth-first search on the queue, where we visit each situation based on the current game state and the type of next move. If the cat's turn, don't allow the cat to go to the hole (node 0). If the mouse's turn, ignore mouse moves to a state which the cat wins. If there's a feasible move, update the status array and push it to the queue.
4. At the end, `status[1][2][1]` denotes the result of the game (1 for the mouse escapes, 2 for the cat catches the mouse, otherwise 0 for a draw).

## A solution in Javascript

```javascript
function catMouseGame(graph) {
    const n = graph.length;
    const status = [...Array(n)].map(() => [...Array(n)].map(() => Array(3).fill(-1)));
    const queue = [];

    for (let i = 1; i < n; ++i) {
        status[i][i][1] = 2;
        status[i][i][2] = 2;
        queue.push([i, i, 2, 2]);
        queue.push([i, i, 1, 2]);
    }

    while (queue.length) {
        const [pos_m, pos_c, t_type, t_result] = queue.shift();

        for (const prev of t_type === 1 ? graph[pos_m] : graph[pos_c]) {
            if ((t_type === 2 && prev === 0) || (t_result === 2 && status[prev][pos_c][3 - t_type] !== -1)) continue;
            if (status[prev][pos_c][3 - t_type] !== -1) continue;
            queue.push([pos_c, prev, 3 - t_type, 3 - t_result]);
            status[prev][pos_c][3 - t_type] = 3 - t_result;
        }
    }
    return status[1][2][1];
}
```
1. Initialize a 3D array `status` to track game state, representing the positions of the cat and mouse, and if it's the cat's or mouse's turn (state can also include whether the game has ended and who wins).
2. Fill in the base game state where cat and mouse are in the same position (cat catches the mouse) and push such states to a queue.
3. Perform a breadth-first search on the queue, where we visit each situation based on the current game state and the type of next move. If the cat's turn, don't allow the cat to go to the hole (node 0). If the mouse's turn, ignore mouse moves to a state which the cat wins. If there's a feasible move, update the status array and push it to the queue.
4. At the end, `status[1][2][1]` denotes the result of the game (1 for the mouse escapes, 2 for the cat catches the mouse, otherwise 0 for a draw).


# Reveal Cards In Increasing Order

- slug: reveal-cards-in-increasing-order
- difficulty: Medium

You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`.

You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.

You will do the following steps repeatedly until all cards are revealed:

1.  Take the top card of the deck, reveal it, and take it out of the deck.
2.  If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
3.  If there are still unrevealed cards, go back to step 1. Otherwise, stop.

Return _an ordering of the deck that would reveal the cards in increasing order_.

**Note** that the first entry in the answer is considered to be the top of the deck.

**Example 1:**

**Input:** deck = \[17,13,11,2,3,5,7\]
**Output:** \[2,13,3,11,5,17,7\]
**Explanation:**
We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it.
After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom.  The deck is now \[3,11,5,17,7,13\].
We reveal 3, and move 11 to the bottom.  The deck is now \[5,17,7,13,11\].
We reveal 5, and move 17 to the bottom.  The deck is now \[7,13,11,17\].
We reveal 7, and move 13 to the bottom.  The deck is now \[11,17,13\].
We reveal 11, and move 17 to the bottom.  The deck is now \[13,17\].
We reveal 13, and move 17 to the bottom.  The deck is now \[17\].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.

**Example 2:**

**Input:** deck = \[1,1000\]
**Output:** \[1,1000\]

**Constraints:**

*   `1 <= deck.length <= 1000`
*   `1 <= deck[i] <= 106`
*   All the values of `deck` are **unique**.

## A solution in Java

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

class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        HashMap<Integer, Integer> counts = new HashMap<>();
        for (int card : deck) {
            counts.put(card, counts.getOrDefault(card, 0) + 1);
        }
        int gcd_result = 0;
        for (Map.Entry<Integer, Integer> count : counts.entrySet()) {
            gcd_result = gcd(gcd_result, count.getValue());
        }
        return gcd_result > 1;
    }
    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}
```
1. Count the occurrences of each card using a hash map (in C++ and Java), a counter (in Python), or an object (in JavaScript).
2. Initialize a variable `gcd_result` to store the greatest common divisor (GCD) of the counts, initially set to 0.
3. Iterate through the counts and calculate the GCD of the current `gcd_result` and each count. In Python, `reduce()` is used to perform this operation more easily.
4. Return true if the final `gcd_result` is greater than 1, otherwise return false.

## A solution in C++

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

bool hasGroupsSizeX(vector<int>& deck) {
    unordered_map<int, int> counts;
    for (int card : deck) {
        counts[card]++;
    }
    int gcd_result = 0;
    for (auto& count : counts) {
        gcd_result = gcd(gcd_result, count.second);
    }
    return gcd_result > 1;
}
```
1. Count the occurrences of each card using a hash map (in C++ and Java), a counter (in Python), or an object (in JavaScript).
2. Initialize a variable `gcd_result` to store the greatest common divisor (GCD) of the counts, initially set to 0.
3. Iterate through the counts and calculate the GCD of the current `gcd_result` and each count. In Python, `reduce()` is used to perform this operation more easily.
4. Return true if the final `gcd_result` is greater than 1, otherwise return false.

## A solution in Python

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

def hasGroupsSizeX(deck):
    counts = Counter(deck)
    gcd_result = reduce(gcd, counts.values())
    return gcd_result > 1
```
1. Count the occurrences of each card using a hash map (in C++ and Java), a counter (in Python), or an object (in JavaScript).
2. Initialize a variable `gcd_result` to store the greatest common divisor (GCD) of the counts, initially set to 0.
3. Iterate through the counts and calculate the GCD of the current `gcd_result` and each count. In Python, `reduce()` is used to perform this operation more easily.
4. Return true if the final `gcd_result` is greater than 1, otherwise return false.

## A solution in Javascript

```javascript
function gcd(a, b) {
   if (b === 0) return a;
   return gcd(b, a % b);
}

function hasGroupsSizeX(deck) {
    const counts = {};
    for (const card of deck) {
        if (card in counts) {
            counts[card]++;
        } else {
            counts[card] = 1;
        }
    }
    let gcd_result = 0;
    for (const count in counts) {
        gcd_result = gcd(gcd_result, counts[count]);
    }
    return gcd_result > 1;
}
```
1. Count the occurrences of each card using a hash map (in C++ and Java), a counter (in Python), or an object (in JavaScript).
2. Initialize a variable `gcd_result` to store the greatest common divisor (GCD) of the counts, initially set to 0.
3. Iterate through the counts and calculate the GCD of the current `gcd_result` and each count. In Python, `reduce()` is used to perform this operation more easily.
4. Return true if the final `gcd_result` is greater than 1, otherwise return false.


# Flip Equivalent Binary Trees

- slug: flip-equivalent-binary-trees
- difficulty: Medium

For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees.

A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations.

Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise.

**Example 1:**

**Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\]
**Output:** true
**Explanation:** We flipped at nodes with values 1, 3, and 5.

**Example 2:**

**Input:** root1 = \[\], root2 = \[\]
**Output:** true

**Example 3:**

**Input:** root1 = \[\], root2 = \[1\]
**Output:** false

**Constraints:**

*   The number of nodes in each tree is in the range `[0, 100]`.
*   Each tree will have **unique node values** in the range `[0, 99]`.

## A solution in Java

```java
public int partitionDisjoint(int[] nums) {
    int leftMax = nums[0], globalMax = nums[0], leftLength = 1;
    for (int i = 1; i < nums.length; ++i) {
        if (nums[i] < leftMax) {
            leftMax = globalMax;
            leftLength = i + 1;
        } else {
            globalMax = Math.max(globalMax, nums[i]);
        }
    }
    return leftLength;
}
```
The algorithm iterates through the `nums` array and maintains two values, `leftMax` and `globalMax`. `leftMax` represents the maximum element on the left side of the partition, while `globalMax` is the overall maximum element encountered so far.

At each step, if the current element is smaller than `leftMax`, it updates the `leftMax` to the current `globalMax` and extends the left partition by one element (i.e., increases `left_length`). If the current value is greater than or equal to `leftMax`, it updates `globalMax` to the maximum between `globalMax` and the current element. This ensures that the partition remains valid.

Once the loop is finished, `leftLength` represents the length of the left partition.

## A solution in C++

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

int partitionDisjoint(vector<int>& nums) {
    int leftMax = nums[0], globalMax = nums[0], leftLength = 1;
    for (int i = 1; i < nums.size(); ++i) {
        if (nums[i] < leftMax) {
            leftMax = globalMax;
            leftLength = i + 1;
        } else {
            globalMax = max(globalMax, nums[i]);
        }
    }
    return leftLength;
}
```
The algorithm iterates through the `nums` array and maintains two values, `leftMax` and `globalMax`. `leftMax` represents the maximum element on the left side of the partition, while `globalMax` is the overall maximum element encountered so far.

At each step, if the current element is smaller than `leftMax`, it updates the `leftMax` to the current `globalMax` and extends the left partition by one element (i.e., increases `left_length`). If the current value is greater than or equal to `leftMax`, it updates `globalMax` to the maximum between `globalMax` and the current element. This ensures that the partition remains valid.

Once the loop is finished, `leftLength` represents the length of the left partition.

## A solution in Python

```python
def partitionDisjoint(nums):
    left_max, global_max, left_length = nums[0], nums[0], 1
    for i in range(1, len(nums)):
        if nums[i] < left_max:
            left_max = global_max
            left_length = i + 1
        else:
            global_max = max(global_max, nums[i])
    return left_length
```
The algorithm iterates through the `nums` array and maintains two values, `leftMax` and `globalMax`. `leftMax` represents the maximum element on the left side of the partition, while `globalMax` is the overall maximum element encountered so far.

At each step, if the current element is smaller than `leftMax`, it updates the `leftMax` to the current `globalMax` and extends the left partition by one element (i.e., increases `left_length`). If the current value is greater than or equal to `leftMax`, it updates `globalMax` to the maximum between `globalMax` and the current element. This ensures that the partition remains valid.

Once the loop is finished, `leftLength` represents the length of the left partition.

## A solution in Javascript

```javascript
function partitionDisjoint(nums) {
    let leftMax = nums[0], globalMax = nums[0], leftLength = 1;
    for (let i = 1; i < nums.length; ++i) {
        if (nums[i] < leftMax) {
            leftMax = globalMax;
            leftLength = i + 1;
        } else {
            globalMax = Math.max(globalMax, nums[i]);
        }
    }
    return leftLength;
}
```
The algorithm iterates through the `nums` array and maintains two values, `leftMax` and `globalMax`. `leftMax` represents the maximum element on the left side of the partition, while `globalMax` is the overall maximum element encountered so far.

At each step, if the current element is smaller than `leftMax`, it updates the `leftMax` to the current `globalMax` and extends the left partition by one element (i.e., increases `left_length`). If the current value is greater than or equal to `leftMax`, it updates `globalMax` to the maximum between `globalMax` and the current element. This ensures that the partition remains valid.

Once the loop is finished, `leftLength` represents the length of the left partition.


# Largest Component Size by Common Factor

- slug: largest-component-size-by-common-factor
- difficulty: Hard

You are given an integer array of unique positive integers `nums`. Consider the following graph:

*   There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,
*   There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`.

Return _the size of the largest connected component in the graph_.

**Example 1:**

**Input:** nums = \[4,6,15,35\]
**Output:** 4

**Example 2:**

**Input:** nums = \[20,50,9,63\]
**Output:** 2

**Example 3:**

**Input:** nums = \[2,3,6,7,4,12,21,39\]
**Output:** 8

**Constraints:**

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

## A solution in Java

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

public List<String> wordSubsets(String[] words1, String[] words2) {
    Map<Character, Integer> maxChars = new HashMap<>();
    for (String word : words2) {
        Map<Character, Integer> chars = new HashMap<>();
        for (char c : word.toCharArray()) {
            chars.put(c, chars.getOrDefault(c, 0) + 1);
        }
        for (Map.Entry<Character, Integer> entry : chars.entrySet()) {
            maxChars.put(entry.getKey(), Math.max(maxChars.getOrDefault(entry.getKey(), 0), entry.getValue()));
        }
    }

    List<String> result = new ArrayList<>();
    for (String word : words1) {
        Map<Character, Integer> wordChars = new HashMap<>();
        for (char c : word.toCharArray()) {
            wordChars.put(c, wordChars.getOrDefault(c, 0) + 1);
        }

        boolean universal = true;
        for (Map.Entry<Character, Integer> entry : maxChars.entrySet()) {
            if (wordChars.getOrDefault(entry.getKey(), 0) < entry.getValue()) {
                universal = false;
                break;
            }
        }

        if (universal) {
            result.add(word);
        }
    }

    return result;
}
```
1. Create a hashmap that contains the maximum frequency of each character across all words in `words2`. We will call this hashmap `max_chars`.
2. Iterate through every word in `words1` and for each word, create another hashmap `word_chars` that counts the frequency of each character in that word.
3. Check if every character in `max_chars` is present in `word_chars` with a frequency equal to or greater than its frequency in `max_chars`. If this is true for every character, the word is considered universal and we add it to the list of results.
4. Return the list of results.

## A solution in C++

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

std::vector<std::string> wordSubsets(std::vector<std::string>& words1, std::vector<std::string>& words2) {
    std::unordered_map<char, int> max_chars;
    for (const auto& word : words2) {
        std::unordered_map<char, int> chars;
        for (char c : word) {
            chars[c]++;
        }
        for (const auto& entry : chars) {
            max_chars[entry.first] = std::max(max_chars[entry.first], entry.second);
        }
    }

    std::vector<std::string> result;
    for (const auto& word : words1) {
        std::unordered_map<char, int> word_chars;
        for (char c : word) {
            word_chars[c]++;
        }

        bool universal = true;
        for (const auto& entry : max_chars) {
            if (word_chars[entry.first] < entry.second) {
                universal = false;
                break;
            }
        }

        if (universal) {
            result.push_back(word);
        }
    }

    return result;
}
```
1. Create a hashmap that contains the maximum frequency of each character across all words in `words2`. We will call this hashmap `max_chars`.
2. Iterate through every word in `words1` and for each word, create another hashmap `word_chars` that counts the frequency of each character in that word.
3. Check if every character in `max_chars` is present in `word_chars` with a frequency equal to or greater than its frequency in `max_chars`. If this is true for every character, the word is considered universal and we add it to the list of results.
4. Return the list of results.

## A solution in Python

```python
from collections import Counter

def word_subsets(words1, words2):
    max_chars = Counter()
    for word in words2:
        chars = Counter(word)
        for c, count in chars.items():
            max_chars[c] = max(max_chars[c], count)

    result = []
    for word in words1:
        word_chars = Counter(word)
        universal = all(word_chars[c] >= max_chars[c] for c in max_chars)
        if universal:
            result.append(word)

    return result
```
1. Create a hashmap that contains the maximum frequency of each character across all words in `words2`. We will call this hashmap `max_chars`.
2. Iterate through every word in `words1` and for each word, create another hashmap `word_chars` that counts the frequency of each character in that word.
3. Check if every character in `max_chars` is present in `word_chars` with a frequency equal to or greater than its frequency in `max_chars`. If this is true for every character, the word is considered universal and we add it to the list of results.
4. Return the list of results.

## A solution in Javascript

```javascript
function wordSubsets(words1, words2) {
    const maxChars = {};
    for (const word of words2) {
        const chars = {};
        for (const c of word) {
            chars[c] = (chars[c] || 0) + 1;
        }
        for (const c in chars) {
            maxChars[c] = Math.max(maxChars[c] || 0, chars[c]);
        }
    }

    const result = [];
    for (const word of words1) {
        const wordChars = {};
        for (const c of word) {
            wordChars[c] = (wordChars[c] || 0) + 1;
        }

        let universal = true;
        for (const c in maxChars) {
            if ((wordChars[c] || 0) < maxChars[c]) {
                universal = false;
                break;
            }
        }

        if (universal) {
            result.push(word);
        }
    }

    return result;
}
```
1. Create a hashmap that contains the maximum frequency of each character across all words in `words2`. We will call this hashmap `max_chars`.
2. Iterate through every word in `words1` and for each word, create another hashmap `word_chars` that counts the frequency of each character in that word.
3. Check if every character in `max_chars` is present in `word_chars` with a frequency equal to or greater than its frequency in `max_chars`. If this is true for every character, the word is considered universal and we add it to the list of results.
4. Return the list of results.


# Verifying an Alien Dictionary

- slug: verifying-an-alien-dictionary
- difficulty: Easy

In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters.

Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language.

**Example 1:**

**Input:** words = \[ "hello ", "leetcode "\], order =  "hlabcdefgijkmnopqrstuvwxyz "
**Output:** true
**Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted.

**Example 2:**

**Input:** words = \[ "word ", "world ", "row "\], order =  "worldabcefghijkmnpqstuvxyz "
**Output:** false
**Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted.

**Example 3:**

**Input:** words = \[ "apple ", "app "\], order =  "abcdefghijklmnopqrstuvwxyz "
**Output:** false
**Explanation:** The first three characters  "app " match, and the second string is shorter (in size.) According to lexicographical rules  "apple " >  "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)).

**Constraints:**

*   `1 <= words.length <= 100`
*   `1 <= words[i].length <= 20`
*   `order.length == 26`
*   All characters in `words[i]` and `order` are English lowercase letters.

## A solution in Java

```java
public String reverseString(String s) {
    StringBuilder result = new StringBuilder(s);
    return result.reverse().toString();
}
```
The algorithm to reverse a string is simple. It takes the input string, iterates from the last character to the first, and appends each character to a new string, which is then returned.

In each of the provided implementations, the language's standard library, or a built-in method, is utilized to achieve the goal, rather than manually writing a loop to iterate over the string.

In C++, the `std::reverse` function from the `<algorithm>` library is used to reverse the input string.

In Java, a `StringBuilder` is created from the input string, and then its built-in `reverse` method is called. Finally, the reversed `StringBuilder` is converted back to a `String`.

In Python, slicing is used to reverse the string with the syntax `s[::-1]`.

In JavaScript, the `split` method is used to convert the string into an array of characters. Then, the `reverse` method is called on the array, which reverses the order of the elements. Finally, the `join` method is called on the reversed array to convert it back to a string.

## A solution in C++

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

std::string reverseString(const std::string& s) {
    std::string result = s;
    std::reverse(result.begin(), result.end());
    return result;
}
```
The algorithm to reverse a string is simple. It takes the input string, iterates from the last character to the first, and appends each character to a new string, which is then returned.

In each of the provided implementations, the language's standard library, or a built-in method, is utilized to achieve the goal, rather than manually writing a loop to iterate over the string.

In C++, the `std::reverse` function from the `<algorithm>` library is used to reverse the input string.

In Java, a `StringBuilder` is created from the input string, and then its built-in `reverse` method is called. Finally, the reversed `StringBuilder` is converted back to a `String`.

In Python, slicing is used to reverse the string with the syntax `s[::-1]`.

In JavaScript, the `split` method is used to convert the string into an array of characters. Then, the `reverse` method is called on the array, which reverses the order of the elements. Finally, the `join` method is called on the reversed array to convert it back to a string.

## A solution in Python

```python
def reverse_string(s):
    return s[::-1]
```
The algorithm to reverse a string is simple. It takes the input string, iterates from the last character to the first, and appends each character to a new string, which is then returned.

In each of the provided implementations, the language's standard library, or a built-in method, is utilized to achieve the goal, rather than manually writing a loop to iterate over the string.

In C++, the `std::reverse` function from the `<algorithm>` library is used to reverse the input string.

In Java, a `StringBuilder` is created from the input string, and then its built-in `reverse` method is called. Finally, the reversed `StringBuilder` is converted back to a `String`.

In Python, slicing is used to reverse the string with the syntax `s[::-1]`.

In JavaScript, the `split` method is used to convert the string into an array of characters. Then, the `reverse` method is called on the array, which reverses the order of the elements. Finally, the `join` method is called on the reversed array to convert it back to a string.

## A solution in Javascript

```javascript
function reverseString(s) {
    return s.split('').reverse().join('');
}
```
The algorithm to reverse a string is simple. It takes the input string, iterates from the last character to the first, and appends each character to a new string, which is then returned.

In each of the provided implementations, the language's standard library, or a built-in method, is utilized to achieve the goal, rather than manually writing a loop to iterate over the string.

In C++, the `std::reverse` function from the `<algorithm>` library is used to reverse the input string.

In Java, a `StringBuilder` is created from the input string, and then its built-in `reverse` method is called. Finally, the reversed `StringBuilder` is converted back to a `String`.

In Python, slicing is used to reverse the string with the syntax `s[::-1]`.

In JavaScript, the `split` method is used to convert the string into an array of characters. Then, the `reverse` method is called on the array, which reverses the order of the elements. Finally, the `join` method is called on the reversed array to convert it back to a string.


# Array of Doubled Pairs

- slug: array-of-doubled-pairs
- difficulty: Medium

Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_.

**Example 1:**

**Input:** arr = \[3,1,3,6\]
**Output:** false

**Example 2:**

**Input:** arr = \[2,1,2,6\]
**Output:** false

**Example 3:**

**Input:** arr = \[4,-2,2,-4\]
**Output:** true
**Explanation:** We can take two groups, \[-2,-4\] and \[2,4\] to form \[-2,-4,2,4\] or \[2,4,-2,-4\].

**Constraints:**

*   `2 <= arr.length <= 3 * 104`
*   `arr.length` is even.
*   `-105 <= arr[i] <= 105`

## A solution in Java

```java
public boolean canReorderDoubled(int[] arr) {
    Map<Integer, Integer> count = new TreeMap<>();
    for (int a : arr) {
        count.put(a, count.getOrDefault(a, 0) + 1);
    }

    for (int a : count.keySet()) {
        if (count.get(a) > 0) {
            int target = a < 0 ? a / 2 : a * 2;
            if (count.getOrDefault(target, 0) < count.get(a)) return false;
            count.put(target, count.get(target) - count.get(a));
        }
    }

    return true;
}
```
1. Count values in the dataArray using a map / dictionary / counter.
2. For each value in the dataArray, in ascending order of magnitude (Take care of negative values properly):
     - Check if we have sufficient values to match the count.
     - If we do, remove the required count and continue. Else, return False.
3. If our loop encounters no issues, return True.

## A solution in C++

```cpp
bool canReorderDoubled(vector<int>& arr) {
    map<int, int> count;
    for (int a : arr) {
        count[a]++;
    }

    for (const auto& [a, c] : count) {
        if (c > 0) {
            int target = a < 0 ? a / 2 : a * 2;
            if (count[target] < c) return false;
            count[target] -= c;
        }
    }

    return true;
}
```
1. Count values in the dataArray using a map / dictionary / counter.
2. For each value in the dataArray, in ascending order of magnitude (Take care of negative values properly):
     - Check if we have sufficient values to match the count.
     - If we do, remove the required count and continue. Else, return False.
3. If our loop encounters no issues, return True.

## A solution in Python

```python
def canReorderDoubled(arr):
    count = collections.Counter(arr)

    for a in sorted(count, key=abs):
        if count[a] > 0:
            target = a * 2
            if count[target] < count[a]:
                return False
            count[target] -= count[a]

    return True
```
1. Count values in the dataArray using a map / dictionary / counter.
2. For each value in the dataArray, in ascending order of magnitude (Take care of negative values properly):
     - Check if we have sufficient values to match the count.
     - If we do, remove the required count and continue. Else, return False.
3. If our loop encounters no issues, return True.

## A solution in Javascript

```javascript
var canReorderDoubled = function(arr) {
    const count = new Map();
    arr.sort((a, b) => Math.abs(a) - Math.abs(b));

    for (const a of arr) {
        if (!count.has(a)) {
            count.set(a, 0);
        }
        count.set(a, count.get(a) + 1);
    }

    for (const a of count.keys()) {
        if (count.get(a) > 0) {
            const target = a < 0 ? a / 2 : a * 2;
            if (!count.has(target) || count.get(target) < count.get(a)) {
                return false;
            }
            count.set(target, count.get(target) - count.get(a));
        }
    }

    return true;
};
```
1. Count values in the dataArray using a map / dictionary / counter.
2. For each value in the dataArray, in ascending order of magnitude (Take care of negative values properly):
     - Check if we have sufficient values to match the count.
     - If we do, remove the required count and continue. Else, return False.
3. If our loop encounters no issues, return True.