# Find All Possible Recipes from Given Supplies

- slug: find-all-possible-recipes-from-given-supplies
- difficulty: Medium

You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can **create** it if you have **all** the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from **other** recipes, i.e., `ingredients[i]` may contain a string that is in `recipes`.

You are also given a string array `supplies` containing all the ingredients that you initially have, and you have an infinite supply of all of them.

Return _a list of all the recipes that you can create._ You may return the answer in **any order**.

Note that two recipes may contain each other in their ingredients.

**Example 1:**

**Input:** recipes = \[ "bread "\], ingredients = \[\[ "yeast ", "flour "\]\], supplies = \[ "yeast ", "flour ", "corn "\]
**Output:** \[ "bread "\]
**Explanation:**
We can create  "bread " since we have the ingredients  "yeast " and  "flour ".

**Example 2:**

**Input:** recipes = \[ "bread ", "sandwich "\], ingredients = \[\[ "yeast ", "flour "\],\[ "bread ", "meat "\]\], supplies = \[ "yeast ", "flour ", "meat "\]
**Output:** \[ "bread ", "sandwich "\]
**Explanation:**
We can create  "bread " since we have the ingredients  "yeast " and  "flour ".
We can create  "sandwich " since we have the ingredient  "meat " and can create the ingredient  "bread ".

**Example 3:**

**Input:** recipes = \[ "bread ", "sandwich ", "burger "\], ingredients = \[\[ "yeast ", "flour "\],\[ "bread ", "meat "\],\[ "sandwich ", "meat ", "bread "\]\], supplies = \[ "yeast ", "flour ", "meat "\]
**Output:** \[ "bread ", "sandwich ", "burger "\]
**Explanation:**
We can create  "bread " since we have the ingredients  "yeast " and  "flour ".
We can create  "sandwich " since we have the ingredient  "meat " and can create the ingredient  "bread ".
We can create  "burger " since we have the ingredient  "meat " and can create the ingredients  "bread " and  "sandwich ".

**Constraints:**

*   `n == recipes.length == ingredients.length`
*   `1 <= n <= 100`
*   `1 <= ingredients[i].length, supplies.length <= 100`
*   `1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10`
*   `recipes[i], ingredients[i][j]`, and `supplies[k]` consist only of lowercase English letters.
*   All the values of `recipes` and `supplies` combined are unique.
*   Each `ingredients[i]` does not contain any duplicate values.

## A solution in Java

```java
public int numDistinct(String binary) {
    int mod = 1000000007;
    int zero_count = 0, ones_count = 0;

    for (char c : binary.toCharArray()) {
        if (c == '0') {
            zero_count = (zero_count + ones_count) % mod;
        } else {
            ones_count = (ones_count * 2 + 1) % mod;
        }
    }
    return zero_count;
}
```
The algorithm proceeds by iterating through the given binary string. For each character in the string, we increment the counts for zeros and ones accordingly. The zero count is incremented by the current ones count whenever a '0' is encountered in the binary string. The ones count is incremented by the current ones count plus 1 whenever a '1' is encountered in the binary string, and the count is multiplied by 2 to account for the fact that we can use the ones in combination with the zeros. Finally, we return the zero count which represents the count of non-leading-zero subsequences. To keep the result within the given range, we use modulo 109 + 7 after each update to the counts.

## A solution in C++

```cpp
int numDistinct(string binary) {
    int mod = 1e9 + 7;
    int zero_count = 0, ones_count = 0;

    for (char c : binary) {
        if (c == '0') {
            zero_count = (zero_count + ones_count) % mod;
        } else {
            ones_count = (ones_count * 2 + 1) % mod;
        }
    }
    return zero_count;
}
```
The algorithm proceeds by iterating through the given binary string. For each character in the string, we increment the counts for zeros and ones accordingly. The zero count is incremented by the current ones count whenever a '0' is encountered in the binary string. The ones count is incremented by the current ones count plus 1 whenever a '1' is encountered in the binary string, and the count is multiplied by 2 to account for the fact that we can use the ones in combination with the zeros. Finally, we return the zero count which represents the count of non-leading-zero subsequences. To keep the result within the given range, we use modulo 109 + 7 after each update to the counts.

## A solution in Python

```python
def numDistinct(binary):
    mod = 10**9 + 7
    zero_count, ones_count = 0, 0

    for c in binary:
        if c == '0':
            zero_count = (zero_count + ones_count) % mod
        else:
            ones_count = (ones_count * 2 + 1) % mod

    return zero_count
```
The algorithm proceeds by iterating through the given binary string. For each character in the string, we increment the counts for zeros and ones accordingly. The zero count is incremented by the current ones count whenever a '0' is encountered in the binary string. The ones count is incremented by the current ones count plus 1 whenever a '1' is encountered in the binary string, and the count is multiplied by 2 to account for the fact that we can use the ones in combination with the zeros. Finally, we return the zero count which represents the count of non-leading-zero subsequences. To keep the result within the given range, we use modulo 109 + 7 after each update to the counts.

## A solution in Javascript

```javascript
function numDistinct(binary) {
    const mod = 1e9 + 7;
    let zero_count = 0, ones_count = 0;

    for (const c of binary) {
        if (c === '0') {
            zero_count = (zero_count + ones_count) % mod;
        } else {
            ones_count = (ones_count * 2 + 1) % mod;
        }
    }
    return zero_count;
}
```
The algorithm proceeds by iterating through the given binary string. For each character in the string, we increment the counts for zeros and ones accordingly. The zero count is incremented by the current ones count whenever a '0' is encountered in the binary string. The ones count is incremented by the current ones count plus 1 whenever a '1' is encountered in the binary string, and the count is multiplied by 2 to account for the fact that we can use the ones in combination with the zeros. Finally, we return the zero count which represents the count of non-leading-zero subsequences. To keep the result within the given range, we use modulo 109 + 7 after each update to the counts.


# Check if a Parentheses String Can Be Valid

- slug: check-if-a-parentheses-string-can-be-valid
- difficulty: Medium

A parentheses string is a **non-empty** string consisting only of `'('` and `')'`. It is valid if **any** of the following conditions is **true**:

*   It is `()`.
*   It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid parentheses strings.
*   It can be written as `(A)`, where `A` is a valid parentheses string.

You are given a parentheses string `s` and a string `locked`, both of length `n`. `locked` is a binary string consisting only of `'0'`s and `'1'`s. For **each** index `i` of `locked`,

*   If `locked[i]` is `'1'`, you **cannot** change `s[i]`.
*   But if `locked[i]` is `'0'`, you **can** change `s[i]` to either `'('` or `')'`.

Return `true` _if you can make `s` a valid parentheses string_. Otherwise, return `false`.

**Example 1:**

**Input:** s =  "))())) ", locked =  "010100 "
**Output:** true
**Explanation:** locked\[1\] == '1' and locked\[3\] == '1', so we cannot change s\[1\] or s\[3\].
We change s\[0\] and s\[4\] to '(' while leaving s\[2\] and s\[5\] unchanged to make s valid.

**Example 2:**

**Input:** s =  "()() ", locked =  "0000 "
**Output:** true
**Explanation:** We do not need to make any changes because s is already valid.

**Example 3:**

**Input:** s =  ") ", locked =  "0 "
**Output:** false
**Explanation:** locked permits us to change s\[0\].
Changing s\[0\] to either '(' or ')' will not make s valid.

**Constraints:**

*   `n == s.length == locked.length`
*   `1 <= n <= 105`
*   `s[i]` is either `'('` or `')'`.
*   `locked[i]` is either `'0'` or `'1'`.

x if x >= 0, or -x if x < 0.

## A solution in Java

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

public int countPairsWithDifferenceK(int[] nums, int k) {
    Map<Integer, Integer> freqMap = new HashMap<>();
    int count = 0;

    for (int num : nums) {
        count += freqMap.getOrDefault(num - k, 0) + freqMap.getOrDefault(num + k, 0);
        freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
    }

    return count;
}
```
The algorithm iterates through the input array `nums`. For each number `num`, it increments the counter by the frequency of the values `num - k` and `num + k` in the input array. This is because either of them must have a difference of `k` with the current `num`. To achieve that, the algorithm keeps track of the frequency of each number in a hashmap called `freq_map`. In the end, it returns the count of all these pairs.

In each language implementation, the function follows the same logic but is adjusted to fit the specific syntax and data structure usage of each programming language. All implementations use a dictionary/hashmap data structure to store the frequency of the numbers.

## A solution in C++

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

int countPairsWithDifferenceK(const std::vector<int>& nums, int k) {
    std::unordered_map<int, int> freq_map;
    int count = 0;

    for (int num : nums) {
        count += freq_map[num - k] + freq_map[num + k];
        freq_map[num]++;
    }

    return count;
}
```
The algorithm iterates through the input array `nums`. For each number `num`, it increments the counter by the frequency of the values `num - k` and `num + k` in the input array. This is because either of them must have a difference of `k` with the current `num`. To achieve that, the algorithm keeps track of the frequency of each number in a hashmap called `freq_map`. In the end, it returns the count of all these pairs.

In each language implementation, the function follows the same logic but is adjusted to fit the specific syntax and data structure usage of each programming language. All implementations use a dictionary/hashmap data structure to store the frequency of the numbers.

## A solution in Python

```python
def count_pairs_with_difference_k(nums, k):
    freq_map = {}
    count = 0

    for num in nums:
        count += freq_map.get(num - k, 0) + freq_map.get(num + k, 0)
        freq_map[num] = freq_map.get(num, 0) + 1

    return count
```
The algorithm iterates through the input array `nums`. For each number `num`, it increments the counter by the frequency of the values `num - k` and `num + k` in the input array. This is because either of them must have a difference of `k` with the current `num`. To achieve that, the algorithm keeps track of the frequency of each number in a hashmap called `freq_map`. In the end, it returns the count of all these pairs.

In each language implementation, the function follows the same logic but is adjusted to fit the specific syntax and data structure usage of each programming language. All implementations use a dictionary/hashmap data structure to store the frequency of the numbers.

## A solution in Javascript

```javascript
function countPairsWithDifferenceK(nums, k) {
    const freqMap = new Map();
    let count = 0;

    for (const num of nums) {
        count += (freqMap.get(num - k) || 0) + (freqMap.get(num + k) || 0);
        freqMap.set(num, (freqMap.get(num) || 0) + 1);
    }

    return count;
}
```
The algorithm iterates through the input array `nums`. For each number `num`, it increments the counter by the frequency of the values `num - k` and `num + k` in the input array. This is because either of them must have a difference of `k` with the current `num`. To achieve that, the algorithm keeps track of the frequency of each number in a hashmap called `freq_map`. In the end, it returns the count of all these pairs.

In each language implementation, the function follows the same logic but is adjusted to fit the specific syntax and data structure usage of each programming language. All implementations use a dictionary/hashmap data structure to store the frequency of the numbers.


# Abbreviating the Product of a Range

- slug: abbreviating-the-product-of-a-range
- difficulty: Hard

You are given two positive integers `left` and `right` with `left <= right`. Calculate the **product** of all integers in the **inclusive** range `[left, right]`.

Since the product may be very large, you will **abbreviate** it following these steps:

1.  Count all **trailing** zeros in the product and **remove** them. Let us denote this count as `C`.
    *   For example, there are `3` trailing zeros in `1000`, and there are `0` trailing zeros in `546`.
2.  Denote the remaining number of digits in the product as `d`. If `d > 10`, then express the product as

        ...

3.  Finally, represent the product as a **string** `"`

        ...eC "

Return _a string denoting the **abbreviated product** of all integers in the **inclusive** range_ `[left, right]`.

**Example 1:**

**Input:** left = 1, right = 4
**Output:**  "24e0 "
**Explanation:** The product is 1 \* 2 \* 3 \* 4 = 24.
There are no trailing zeros, so 24 remains the same. The abbreviation will end with  "e0 ".
Since the number of digits is 2, which is less than 10, we do not have to abbreviate it further.
Thus, the final representation is  "24e0 ".

**Example 2:**

**Input:** left = 2, right = 11
**Output:**  "399168e2 "
**Explanation:** The product is 39916800.
There are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with  "e2 ".
The number of digits after removing the trailing zeros is 6, so we do not abbreviate it further.
Hence, the abbreviated product is  "399168e2 ".

**Example 3:**

**Input:** left = 371, right = 375
**Output:**  "7219856259e3 "
**Explanation:** The product is 7219856259000.

**Constraints:**

*   `1 <= left <= right <= 104`

## A solution in Java

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

public int[] findOriginalArray(int[] changed) {
    Map<Integer, Integer> count = new HashMap<>();
    for (int num : changed)
        count.put(num, count.getOrDefault(num, 0) + 1);

    List<Integer> sorted_values = new ArrayList<>(count.keySet());
    Collections.sort(sorted_values);

    List<Integer> original = new ArrayList<>();
    for (int num : sorted_values) {
        while (count.get(num) != null && count.get(num) > 0 && count.get(num * 2) != null && count.get(num * 2) > 0) {
            original.add(num);
            count.put(num, count.get(num) - 1);
            count.put(num * 2, count.get(num * 2) - 1);
        }
        if (count.get(num) != null && count.get(num) > 0)
            return new int[0];
    }
    return original.stream().mapToInt(Integer::intValue).toArray();
}
```
The algorithm works as follows:

1. Create a `count` map to store the frequency of each number in the `changed` array.
2. Add all unique keys from the `count` map into an array `sorted_values` and sort it.
3. Create an empty result `original` array.
4. Iterate through the sorted_values:
    - While the current number `num` and its double (`num * 2`) have positive counts in the map:
        - Add the current `num` to the `original` array.
        - Decrement the count of `num` and its double.
    - If the count of `num` is positive after processing its double, return an empty array as it means the given array is not a valid doubled array.
5. Return the `original` array.

## A solution in C++

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

vector<int> findOriginalArray(vector<int>& changed) {
    unordered_map<int, int> count;
    for (const int& num : changed)
        count[num]++;

    vector<int> sorted_values;
    for (const auto& c : count)
        sorted_values.push_back(c.first);
    sort(sorted_values.begin(), sorted_values.end());

    vector<int> original;
    for (const int& num : sorted_values) {
        while (count[num] > 0 && count[num * 2] > 0) {
            original.push_back(num);
            count[num]--;
            count[num * 2]--;
        }
        if (count[num] > 0)
            return {};
    }
    return original;
}
```
The algorithm works as follows:

1. Create a `count` map to store the frequency of each number in the `changed` array.
2. Add all unique keys from the `count` map into an array `sorted_values` and sort it.
3. Create an empty result `original` array.
4. Iterate through the sorted_values:
    - While the current number `num` and its double (`num * 2`) have positive counts in the map:
        - Add the current `num` to the `original` array.
        - Decrement the count of `num` and its double.
    - If the count of `num` is positive after processing its double, return an empty array as it means the given array is not a valid doubled array.
5. Return the `original` array.

## A solution in Python

```python
def findOriginalArray(changed):
    count = {}
    for num in changed:
        count[num] = count.get(num, 0) + 1

    sorted_values = sorted(count.keys())

    original = []
    for num in sorted_values:
        while count[num] > 0 and count.get(num * 2, 0) > 0:
            original.append(num)
            count[num] -= 1
            count[num * 2] -= 1
        if count[num] > 0:
            return []

    return original
```
The algorithm works as follows:

1. Create a `count` map to store the frequency of each number in the `changed` array.
2. Add all unique keys from the `count` map into an array `sorted_values` and sort it.
3. Create an empty result `original` array.
4. Iterate through the sorted_values:
    - While the current number `num` and its double (`num * 2`) have positive counts in the map:
        - Add the current `num` to the `original` array.
        - Decrement the count of `num` and its double.
    - If the count of `num` is positive after processing its double, return an empty array as it means the given array is not a valid doubled array.
5. Return the `original` array.

## A solution in Javascript

```javascript
function findOriginalArray(changed) {
    const count = new Map();
    for (const num of changed)
        count.set(num, (count.get(num) || 0) + 1);

    const sorted_values = Array.from(count.keys()).sort((a, b) => a - b);

    const original = [];
    for (const num of sorted_values) {
        while (count.get(num) > 0 && count.get(num * 2) > 0) {
            original.push(num);
            count.set(num, count.get(num) - 1);
            count.set(num * 2, count.get(num * 2) - 1);
        }
        if (count.get(num) > 0)
            return [];
    }
    return original;
}
```
The algorithm works as follows:

1. Create a `count` map to store the frequency of each number in the `changed` array.
2. Add all unique keys from the `count` map into an array `sorted_values` and sort it.
3. Create an empty result `original` array.
4. Iterate through the sorted_values:
    - While the current number `num` and its double (`num * 2`) have positive counts in the map:
        - Add the current `num` to the `original` array.
        - Decrement the count of `num` and its double.
    - If the count of `num` is positive after processing its double, return an empty array as it means the given array is not a valid doubled array.
5. Return the `original` array.


# A Number After a Double Reversal

- slug: a-number-after-a-double-reversal
- difficulty: Easy

**Reversing** an integer means to reverse all its digits.

*   For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**.

Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` to get `reversed2`. Return `true` _if_ `reversed2` _equals_ `num`. Otherwise return `false`.

**Example 1:**

**Input:** num = 526
**Output:** true
**Explanation:** Reverse num to get 625, then reverse 625 to get 526, which equals num.

**Example 2:**

**Input:** num = 1800
**Output:** false
**Explanation:** Reverse num to get 81, then reverse 81 to get 18, which does not equal num.

**Example 3:**

**Input:** num = 0
**Output:** true
**Explanation:** Reverse num to get 0, then reverse 0 to get 0, which equals num.

**Constraints:**

*   `0 <= num <= 106`

## A solution in Java

```java
import java.util.Arrays;
import java.util.stream.Collectors;

public int minOperations(int[] nums) {
    int[] sortedNums = Arrays.stream(nums).distinct().sorted().toArray();
    int n = sortedNums.length;
    int ans = n;
    for (int i = 0; i < n; ++i) {
        int j = 0;
        while (j < n && sortedNums[j] <= sortedNums[i] + n - 1) {
            ++j;
        }
        ans = Math.min(ans, n - (j - i));
    }
    return ans;
}
```
The algorithm first sorts the input array `nums` and removes duplicates. Then, for each element in the sorted array, it calculates the upper bound position (`j`) of the elements that can be included in a continuous range with the given element. The difference between the positions `j` and `i` is the number of elements in the continuous range. Subtracting this difference from the total number of unique elements in `nums` gives the number of operations required for this particular range. The final answer is the minimum number of operations required for all possible ranges.

## A solution in C++

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

int minOperations(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    nums.erase(unique(nums.begin(), nums.end()), nums.end());
    int n = nums.size();
    int ans = n;
    for (int i = 0; i < n; ++i) {
        int j = upper_bound(nums.begin() + i, nums.end(), nums[i] + n - 1) - nums.begin();
        ans = min(ans, n - (j - i));
    }
    return ans;
}
```
The algorithm first sorts the input array `nums` and removes duplicates. Then, for each element in the sorted array, it calculates the upper bound position (`j`) of the elements that can be included in a continuous range with the given element. The difference between the positions `j` and `i` is the number of elements in the continuous range. Subtracting this difference from the total number of unique elements in `nums` gives the number of operations required for this particular range. The final answer is the minimum number of operations required for all possible ranges.

## A solution in Python

```python
def minOperations(nums):
    nums = sorted(set(nums))
    n = len(nums)
    ans = n
    for i in range(n):
        j = 0
        while j < n and nums[j] <= nums[i] + n - 1:
            j += 1
        ans = min(ans, n - (j - i))
    return ans
```
The algorithm first sorts the input array `nums` and removes duplicates. Then, for each element in the sorted array, it calculates the upper bound position (`j`) of the elements that can be included in a continuous range with the given element. The difference between the positions `j` and `i` is the number of elements in the continuous range. Subtracting this difference from the total number of unique elements in `nums` gives the number of operations required for this particular range. The final answer is the minimum number of operations required for all possible ranges.

## A solution in Javascript

```javascript
function minOperations(nums) {
    const sortedNums = [...new Set(nums)].sort((a, b) => a - b);
    const n = sortedNums.length;
    let ans = n;
    for (let i = 0; i < n; ++i) {
        let j = 0;
        while (j < n && sortedNums[j] <= sortedNums[i] + n - 1) {
            ++j;
        }
        ans = Math.min(ans, n - (j - i));
    }
    return ans;
}
```
The algorithm first sorts the input array `nums` and removes duplicates. Then, for each element in the sorted array, it calculates the upper bound position (`j`) of the elements that can be included in a continuous range with the given element. The difference between the positions `j` and `i` is the number of elements in the continuous range. Subtracting this difference from the total number of unique elements in `nums` gives the number of operations required for this particular range. The final answer is the minimum number of operations required for all possible ranges.


# Execution of All Suffix Instructions Staying in a Grid

- slug: execution-of-all-suffix-instructions-staying-in-a-grid
- difficulty: Medium

There is an `n x n` grid, with the top-left cell at `(0, 0)` and the bottom-right cell at `(n - 1, n - 1)`. You are given the integer `n` and an integer array `startPos` where `startPos = [startrow, startcol]` indicates that a robot is initially at cell `(startrow, startcol)`.

You are also given a **0-indexed** string `s` of length `m` where `s[i]` is the `ith` instruction for the robot: `'L'` (move left), `'R'` (move right), `'U'` (move up), and `'D'` (move down).

The robot can begin executing from any `ith` instruction in `s`. It executes the instructions one by one towards the end of `s` but it stops if either of these conditions is met:

*   The next instruction will move the robot off the grid.
*   There are no more instructions left to execute.

Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is **the number of instructions** the robot can execute if the robot **begins executing from** the_ `ith` _instruction in_ `s`.

**Example 1:**

**Input:** n = 3, startPos = \[0,1\], s =  "RRDDLU "
**Output:** \[1,5,4,3,1,0\]
**Explanation:** Starting from startPos and beginning execution from the ith instruction:
- 0th:  "**R**RDDLU ". Only one instruction  "R " can be executed before it moves off the grid.
- 1st:   "**RDDLU** ". All five instructions can be executed while it stays in the grid and ends at (1, 1).
- 2nd:    "**DDLU** ". All four instructions can be executed while it stays in the grid and ends at (1, 0).
- 3rd:     "**DLU** ". All three instructions can be executed while it stays in the grid and ends at (0, 0).
- 4th:      "**L**U ". Only one instruction  "L " can be executed before it moves off the grid.
- 5th:       "U ". If moving up, it would move off the grid.

**Example 2:**

**Input:** n = 2, startPos = \[1,1\], s =  "LURD "
**Output:** \[4,1,0,0\]
**Explanation:**
- 0th:  "**LURD** ".
- 1st:   "**U**RD ".
- 2nd:    "RD ".
- 3rd:     "D ".

**Example 3:**

**Input:** n = 1, startPos = \[0,0\], s =  "LRUD "
**Output:** \[0,0,0,0\]
**Explanation:** No matter which instruction the robot begins execution from, it would move off the grid.

**Constraints:**

*   `m == s.length`
*   `1 <= n, m <= 500`
*   `startPos.length == 2`
*   `0 <= startrow, startcol < n`
*   `s` consists of `'L'`, `'R'`, `'U'`, and `'D'`.

## A solution in Java

```java
public int[] findNoOfInstructions(int n, int[] startPos, String s) {
    int[] answer = new int[s.length()];
    int x = startPos[0];
    int y = startPos[1];

    for (int i = 0; i < s.length(); ++i) {
        int cnt = 0;
        int cx = x;
        int cy = y;
        for (int j = i; j < s.length(); ++j) {
            char step = s.charAt(j);
            if (step == 'L') {
                if (cy == 0) break;
                cy -= 1;
            }
            else if (step == 'R') {
                if (cy == n - 1) break;
                cy += 1;
            }
            else if (step == 'U') {
                if (cx == 0) break;
                cx -= 1;
            }
            else {
                if (cx == n - 1) break;
                cx += 1;
            }
            cnt++;
            if (j == s.length() - 1) break;
        }
        answer[i] = cnt;
    }

    return answer;
}
```
Iterate through the string `s` considering each index as the starting point for execution. In each step, try executing instructions without going out of the grid boundary from that starting point.

In a nested loop, keep track of the robot position `cx` and `cy`, and for each step, check if the robot would go out-of-bounds on executing the instruction. If it goes out-of-bounds, break out of the loop for that starting point.

Finally, the count of instructions executed for each starting point is stored in the `answer` array.

## A solution in C++

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

std::vector<int> findNoOfInstructions(int n, std::vector<int>& startPos, std::string s) {
    std::vector<int> answer(s.size(), 0);
    int x = startPos[0];
    int y = startPos[1];

    for (int i = 0; i < s.size(); ++i) {
        int cnt = 0;
        int cx = x;
        int cy = y;
        for (int j = i; j < s.size(); ++j) {
            if (s[j] == 'L') {
                if (cy == 0) break;
                cy -= 1;
            }
            else if (s[j] == 'R') {
                if (cy == n - 1) break;
                cy += 1;
            }
            else if (s[j] == 'U') {
                if (cx == 0) break;
                cx -= 1;
            }
            else {
                if (cx == n - 1) break;
                cx += 1;
            }
            cnt++;
            if (j == s.size() - 1) break;
        }
        answer[i] = cnt;
    }

    return answer;
}
```
Iterate through the string `s` considering each index as the starting point for execution. In each step, try executing instructions without going out of the grid boundary from that starting point.

In a nested loop, keep track of the robot position `cx` and `cy`, and for each step, check if the robot would go out-of-bounds on executing the instruction. If it goes out-of-bounds, break out of the loop for that starting point.

Finally, the count of instructions executed for each starting point is stored in the `answer` array.

## A solution in Python

```python
def findNoOfInstructions(n: int, startPos: List[int], s: str) -> List[int]:
    answer = [0] * len(s)
    x, y = startPos

    for i in range(len(s)):
        cnt = 0
        cx, cy = x, y
        for j in range(i, len(s)):
            step = s[j]
            if step == 'L':
                if cy == 0: break
                cy -= 1
            elif step == 'R':
                if cy == n - 1: break
                cy += 1
            elif step == 'U':
                if cx == 0: break
                cx -= 1
            else:
                if cx == n - 1: break
                cx += 1
            cnt += 1
            if j == len(s) - 1: break
        answer[i] = cnt

    return answer
```
Iterate through the string `s` considering each index as the starting point for execution. In each step, try executing instructions without going out of the grid boundary from that starting point.

In a nested loop, keep track of the robot position `cx` and `cy`, and for each step, check if the robot would go out-of-bounds on executing the instruction. If it goes out-of-bounds, break out of the loop for that starting point.

Finally, the count of instructions executed for each starting point is stored in the `answer` array.

## A solution in Javascript

```javascript
function findNoOfInstructions(n, startPos, s) {
    const answer = Array(s.length).fill(0);
    let [x, y] = startPos;

    for (let i = 0; i < s.length; ++i) {
        let cnt = 0;
        let [cx, cy] = [x, y];
        for (let j = i; j < s.length; ++j) {
            const step = s[j];
            if (step === 'L') {
                if (cy === 0) break;
                cy -= 1;
            }
            else if (step === 'R') {
                if (cy === n - 1) break;
                cy += 1;
            }
            else if (step === 'U') {
                if (cx === 0) break;
                cx -= 1;
            }
            else {
                if (cx === n - 1) break;
                cx += 1;
            }
            cnt++;
            if (j === s.length - 1) break;
        }
        answer[i] = cnt;
    }

    return answer;
}
```
Iterate through the string `s` considering each index as the starting point for execution. In each step, try executing instructions without going out of the grid boundary from that starting point.

In a nested loop, keep track of the robot position `cx` and `cy`, and for each step, check if the robot would go out-of-bounds on executing the instruction. If it goes out-of-bounds, break out of the loop for that starting point.

Finally, the count of instructions executed for each starting point is stored in the `answer` array.


# Intervals Between Identical Elements

- slug: intervals-between-identical-elements
- difficulty: Medium

You are given a **0-indexed** array of `n` integers `arr`.

The **interval** between two elements in `arr` is defined as the **absolute difference** between their indices. More formally, the **interval** between `arr[i]` and `arr[j]` is `|i - j|`.

Return _an array_ `intervals` _of length_ `n` _where_ `intervals[i]` _is **the sum of intervals** between_ `arr[i]` _and each element in_ `arr` _with the same value as_ `arr[i]`_._

**Note:** `|x|` is the absolute value of `x`.

**Example 1:**

**Input:** arr = \[2,1,3,1,2,3,3\]
**Output:** \[4,2,7,2,4,4,5\]
**Explanation:**
- Index 0: Another 2 is found at index 4. |0 - 4| = 4
- Index 1: Another 1 is found at index 3. |1 - 3| = 2
- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7
- Index 3: Another 1 is found at index 1. |3 - 1| = 2
- Index 4: Another 2 is found at index 0. |4 - 0| = 4
- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4
- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5

**Example 2:**

**Input:** arr = \[10,5,10,10\]
**Output:** \[5,0,3,4\]
**Explanation:**
- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5
- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.
- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3
- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

class Solution {
    public boolean hasPath(int n, int[][] edges, int source, int destination) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        for (int[] edge : edges) {
            graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
            graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]);
        }
        Queue<Integer> q = new LinkedList<>();
        q.offer(source);
        boolean[] visited = new boolean[n];
        while (!q.isEmpty()) {
            int current = q.poll();
            visited[current] = true;
            if (current == destination) return true;
            for (int neighbor : graph.getOrDefault(current, Collections.emptyList())) {
                if (!visited[neighbor]) q.offer(neighbor);
            }
        }
        return false;
    }
}
```
The algorithm used here to solve the problem is Breadth-First Search (BFS). First, the given edges are used to build the undirected graph as an adjacency list using HashMap (C++, Java), defaultdict (Python) and Map (JavaScript). Then, a queue is initialized with the source vertex.

We track the visited vertex using the visited array of size n with initial values false. Next, we iterate through the vertices (level by level) in the queue. For each vertex, we mark it as visited and check if it's the same as the destination vertex. If yes, we return true. Otherwise, we add its unvisited neighbors to the queue.

If we exhaust the queue without finding the destination vertex, we return false, indicating that there is no valid path from source to destination.

## A solution in C++

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

bool hasPath(int n, std::vector<std::vector<int>>& edges, int source, int destination) {
    std::unordered_map<int, std::vector<int>> graph;
    for (const std::vector<int>& edge : edges) {
        graph[edge[0]].push_back(edge[1]);
        graph[edge[1]].push_back(edge[0]);
    }
    std::queue<int> q;
    q.push(source);
    std::vector<bool> visited(n, false);
    while (!q.empty()) {
        int current = q.front();
        q.pop();
        visited[current] = true;
        if (current == destination) return true;
        for (int neighbor : graph[current]) {
            if (!visited[neighbor]) q.push(neighbor);
        }
    }
    return false;
}
```
The algorithm used here to solve the problem is Breadth-First Search (BFS). First, the given edges are used to build the undirected graph as an adjacency list using HashMap (C++, Java), defaultdict (Python) and Map (JavaScript). Then, a queue is initialized with the source vertex.

We track the visited vertex using the visited array of size n with initial values false. Next, we iterate through the vertices (level by level) in the queue. For each vertex, we mark it as visited and check if it's the same as the destination vertex. If yes, we return true. Otherwise, we add its unvisited neighbors to the queue.

If we exhaust the queue without finding the destination vertex, we return false, indicating that there is no valid path from source to destination.

## A solution in Python

```python
from collections import defaultdict, deque

def has_path(n, edges, source, destination):
    graph = defaultdict(list)
    for u, v in edges:
        graph[u].append(v)
        graph[v].append(u)
    q = deque([source])
    visited = [False] * n
    while q:
        current = q.popleft()
        visited[current] = True
        if current == destination:
            return True
        for neighbor in graph[current]:
            if not visited[neighbor]:
                q.append(neighbor)
    return False
```
The algorithm used here to solve the problem is Breadth-First Search (BFS). First, the given edges are used to build the undirected graph as an adjacency list using HashMap (C++, Java), defaultdict (Python) and Map (JavaScript). Then, a queue is initialized with the source vertex.

We track the visited vertex using the visited array of size n with initial values false. Next, we iterate through the vertices (level by level) in the queue. For each vertex, we mark it as visited and check if it's the same as the destination vertex. If yes, we return true. Otherwise, we add its unvisited neighbors to the queue.

If we exhaust the queue without finding the destination vertex, we return false, indicating that there is no valid path from source to destination.

## A solution in Javascript

```javascript
function hasPath(n, edges, source, destination) {
    const graph = new Map();
    for (const [u, v] of edges) {
        if (!graph.has(u)) graph.set(u, []);
        if (!graph.has(v)) graph.set(v, []);
        graph.get(u).push(v);
        graph.get(v).push(u);
    }
    const q = [source];
    const visited = new Array(n).fill(false);
    while (q.length > 0) {
        const current = q.shift();
        visited[current] = true;
        if (current === destination) return true;
        for (const neighbor of graph.get(current) || []) {
            if (!visited[neighbor]) q.push(neighbor);
        }
    }
    return false;
}
```
The algorithm used here to solve the problem is Breadth-First Search (BFS). First, the given edges are used to build the undirected graph as an adjacency list using HashMap (C++, Java), defaultdict (Python) and Map (JavaScript). Then, a queue is initialized with the source vertex.

We track the visited vertex using the visited array of size n with initial values false. Next, we iterate through the vertices (level by level) in the queue. For each vertex, we mark it as visited and check if it's the same as the destination vertex. If yes, we return true. Otherwise, we add its unvisited neighbors to the queue.

If we exhaust the queue without finding the destination vertex, we return false, indicating that there is no valid path from source to destination.


# Minimum Operations to Remove Adjacent Ones in Matrix

- slug: minimum-operations-to-remove-adjacent-ones-in-matrix
- difficulty: Hard

You are given a **0-indexed** binary matrix `grid`. In one operation, you can flip any `1` in `grid` to be `0`.

A binary matrix is **well-isolated** if there is no `1` in the matrix that is **4-directionally connected** (i.e., horizontal and vertical) to another `1`.

Return _the minimum number of operations to make_ `grid` _**well-isolated**_.

**Example 1:**

**Input:** grid = \[\[1,1,0\],\[0,1,1\],\[1,1,1\]\]
**Output:** 3
**Explanation:** Use 3 operations to change grid\[0\]\[1\], grid\[1\]\[2\], and grid\[2\]\[1\] to 0.
After, no more 1's are 4-directionally connected and grid is well-isolated.

**Example 2:**

**Input:** grid = \[\[0,0,0\],\[0,0,0\],\[0,0,0\]\]
**Output:** 0
**Explanation:** There are no 1's in grid and it is well-isolated.
No operations were done so return 0.

**Example 3:**

**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 0
**Explanation:** None of the 1's are 4-directionally connected and grid is well-isolated.
No operations were done so return 0.

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int numberOfWeakCharacters(int[][] properties) {
    Arrays.sort(properties, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);

    int maxDefense = 0, weakCount = 0;
    for (int i = properties.length - 1; i >= 0; i--) {
        if (properties[i][1] < maxDefense) {
            weakCount++;
        } else {
            maxDefense = properties[i][1];
        }
    }

    return weakCount;
}
```
1. Sort the properties array based on attack values in ascending order. If there's a tie between attack values, then sort based on defense values in descending order.
2. Initialize two variables, `maxDefense` and `weakCount` to 0.
3. Iterate through the sorted properties array in reverse order.
   - If the defense value of the current character is less than the `maxDefense`, increment the `weakCount`.
   - Else, update the `maxDefense` to the defense value of the current character.
4. Return the `weakCount`.

The reason behind sorting attack values in ascending order and defense values in descending order is to process characters with higher attack values first. Doing so helps us maintain the maximum defense value found so far from characters of higher attack value, hence, allowing us to identify weak characters easily.

## A solution in C++

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

int numberOfWeakCharacters(std::vector<std::vector<int>>& properties) {
    std::sort(properties.begin(), properties.end(), [](const auto& a, const auto& b) {
        return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0];
    });

    int maxDefense = 0, weakCount = 0;
    for (int i = properties.size() - 1; i >= 0; --i) {
        if (properties[i][1] < maxDefense) {
            weakCount++;
        } else {
            maxDefense = properties[i][1];
        }
    }

    return weakCount;
}
```
1. Sort the properties array based on attack values in ascending order. If there's a tie between attack values, then sort based on defense values in descending order.
2. Initialize two variables, `maxDefense` and `weakCount` to 0.
3. Iterate through the sorted properties array in reverse order.
   - If the defense value of the current character is less than the `maxDefense`, increment the `weakCount`.
   - Else, update the `maxDefense` to the defense value of the current character.
4. Return the `weakCount`.

The reason behind sorting attack values in ascending order and defense values in descending order is to process characters with higher attack values first. Doing so helps us maintain the maximum defense value found so far from characters of higher attack value, hence, allowing us to identify weak characters easily.

## A solution in Python

```python
def numberOfWeakCharacters(properties):
    properties.sort(key=lambda x: (x[0], -x[1]))

    max_defense = 0
    weak_count = 0
    for attack, defense in reversed(properties):
        if defense < max_defense:
            weak_count += 1
        else:
            max_defense = defense

    return weak_count
```
1. Sort the properties array based on attack values in ascending order. If there's a tie between attack values, then sort based on defense values in descending order.
2. Initialize two variables, `maxDefense` and `weakCount` to 0.
3. Iterate through the sorted properties array in reverse order.
   - If the defense value of the current character is less than the `maxDefense`, increment the `weakCount`.
   - Else, update the `maxDefense` to the defense value of the current character.
4. Return the `weakCount`.

The reason behind sorting attack values in ascending order and defense values in descending order is to process characters with higher attack values first. Doing so helps us maintain the maximum defense value found so far from characters of higher attack value, hence, allowing us to identify weak characters easily.

## A solution in Javascript

```javascript
function numberOfWeakCharacters(properties) {
    properties.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]);

    let maxDefense = 0, weakCount = 0;
    for (let i = properties.length - 1; i >= 0; i--) {
        if (properties[i][1] < maxDefense) {
            weakCount++;
        } else {
            maxDefense = properties[i][1];
        }
    }

    return weakCount;
}
```
1. Sort the properties array based on attack values in ascending order. If there's a tie between attack values, then sort based on defense values in descending order.
2. Initialize two variables, `maxDefense` and `weakCount` to 0.
3. Iterate through the sorted properties array in reverse order.
   - If the defense value of the current character is less than the `maxDefense`, increment the `weakCount`.
   - Else, update the `maxDefense` to the defense value of the current character.
4. Return the `weakCount`.

The reason behind sorting attack values in ascending order and defense values in descending order is to process characters with higher attack values first. Doing so helps us maintain the maximum defense value found so far from characters of higher attack value, hence, allowing us to identify weak characters easily.


# Check if All A's Appears Before All B's

- slug: check-if-all-as-appears-before-all-bs
- difficulty: Easy

Given a string `s` consisting of **only** the characters `'a'` and `'b'`, return `true` _if **every**_ `'a'` _appears before **every**_ `'b'` _in the string_. Otherwise, return `false`.

**Example 1:**

**Input:** s =  "aaabbb "
**Output:** true
**Explanation:**
The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.
Hence, every 'a' appears before every 'b' and we return true.

**Example 2:**

**Input:** s =  "abab "
**Output:** false
**Explanation:**
There is an 'a' at index 2 and a 'b' at index 1.
Hence, not every 'a' appears before every 'b' and we return false.

**Example 3:**

**Input:** s =  "bbb "
**Output:** true
**Explanation:**
There are no 'a's, hence, every 'a' appears before every 'b' and we return true.

**Constraints:**

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

## A solution in Java

```java
public int firstDayBeenInAllRooms(int[] nextVisit) {
    int n = nextVisit.length;
    long ans = 0, MOD = 1000000007;
    long[] dp = new long[n];

    for (int i = 1; i < n; ++i) {
        dp[i] = (dp[i - 1] + 1 + dp[i - 1] - dp[nextVisit[i - 1]] + MOD) % MOD;
        ans = (ans + dp[i]) % MOD;
    }
    return (int) ans;
}
```
We can solve this problem using dynamic programming. We create an array `dp` of size n and initialize it with 0's. The `dp[i]` should represent the number of days it takes to go from room i to room i+1.

Starting from the second room (i=1), we loop through all rooms and update each `dp[i]` value. To calculate dp[i], we need to perform a cumulative summation of the days it has taken to visit the previous room (dp[i - 1]) plus 1 extra day (day i) and subtract the value at the index stored in nextVisit for the previous room (dp[nextVisit[i - 1]]).

Finally, we add the calculated value modulo 10^9 + 7 to the answer `ans`. Once we exit the loop, we return `ans` as the result.

## A solution in C++

```cpp
int firstDayBeenInAllRooms(vector<int>& nextVisit) {
    int n = nextVisit.size();
    long long ans = 0, MOD = 1e9 + 7;
    vector<long long> dp(n, 0);

    for (int i = 1; i < n; ++i) {
        dp[i] = (dp[i - 1] + 1 + dp[i - 1] - dp[nextVisit[i - 1]] + MOD) % MOD;
        ans = (ans + dp[i]) % MOD;
    }
    return ans;
}
```
We can solve this problem using dynamic programming. We create an array `dp` of size n and initialize it with 0's. The `dp[i]` should represent the number of days it takes to go from room i to room i+1.

Starting from the second room (i=1), we loop through all rooms and update each `dp[i]` value. To calculate dp[i], we need to perform a cumulative summation of the days it has taken to visit the previous room (dp[i - 1]) plus 1 extra day (day i) and subtract the value at the index stored in nextVisit for the previous room (dp[nextVisit[i - 1]]).

Finally, we add the calculated value modulo 10^9 + 7 to the answer `ans`. Once we exit the loop, we return `ans` as the result.

## A solution in Python

```python
def firstDayBeenInAllRooms(nextVisit):
    n = len(nextVisit)
    ans = 0
    MOD = 10**9 + 7
    dp = [0] * n

    for i in range(1, n):
        dp[i] = (dp[i - 1] + 1 + dp[i - 1] - dp[nextVisit[i - 1]] + MOD) % MOD
        ans = (ans + dp[i]) % MOD
    return ans
```
We can solve this problem using dynamic programming. We create an array `dp` of size n and initialize it with 0's. The `dp[i]` should represent the number of days it takes to go from room i to room i+1.

Starting from the second room (i=1), we loop through all rooms and update each `dp[i]` value. To calculate dp[i], we need to perform a cumulative summation of the days it has taken to visit the previous room (dp[i - 1]) plus 1 extra day (day i) and subtract the value at the index stored in nextVisit for the previous room (dp[nextVisit[i - 1]]).

Finally, we add the calculated value modulo 10^9 + 7 to the answer `ans`. Once we exit the loop, we return `ans` as the result.

## A solution in Javascript

```javascript
function firstDayBeenInAllRooms(nextVisit) {
    const n = nextVisit.length;
    let ans = 0, MOD = 1e9 + 7;
    const dp = Array(n).fill(0);

    for (let i = 1; i < n; ++i) {
        dp[i] = (dp[i - 1] + 1 + dp[i - 1] - dp[nextVisit[i - 1]] + MOD) % MOD;
        ans = (ans + dp[i]) % MOD;
    }
    return ans;
};
```
We can solve this problem using dynamic programming. We create an array `dp` of size n and initialize it with 0's. The `dp[i]` should represent the number of days it takes to go from room i to room i+1.

Starting from the second room (i=1), we loop through all rooms and update each `dp[i]` value. To calculate dp[i], we need to perform a cumulative summation of the days it has taken to visit the previous room (dp[i - 1]) plus 1 extra day (day i) and subtract the value at the index stored in nextVisit for the previous room (dp[nextVisit[i - 1]]).

Finally, we add the calculated value modulo 10^9 + 7 to the answer `ans`. Once we exit the loop, we return `ans` as the result.


# Number of Laser Beams in a Bank

- slug: number-of-laser-beams-in-a-bank
- difficulty: Medium

Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a security device.

There is **one** laser beam between any **two** security devices **if both** conditions are met:

*   The two devices are located on two **different rows**: `r1` and `r2`, where `r1 < r2`.
*   For **each** row `i` where `r1 < i < r2`, there are **no security devices** in the `ith` row.

Laser beams are independent, i.e., one beam does not interfere nor join with another.

Return _the total number of laser beams in the bank_.

**Example 1:**

**Input:** bank = \[ "011001 ", "000000 ", "010100 ", "001000 "\]
**Output:** 8
**Explanation:** Between each of the following device pairs, there is one beam. In total, there are 8 beams:
 \* bank\[0\]\[1\] -- bank\[2\]\[1\]
 \* bank\[0\]\[1\] -- bank\[2\]\[3\]
 \* bank\[0\]\[2\] -- bank\[2\]\[1\]
 \* bank\[0\]\[2\] -- bank\[2\]\[3\]
 \* bank\[0\]\[5\] -- bank\[2\]\[1\]
 \* bank\[0\]\[5\] -- bank\[2\]\[3\]
 \* bank\[2\]\[1\] -- bank\[3\]\[2\]
 \* bank\[2\]\[3\] -- bank\[3\]\[2\]
Note that there is no beam between any device on the 0th row with any on the 3rd row.
This is because the 2nd row contains security devices, which breaks the second condition.

**Example 2:**

**Input:** bank = \[ "000 ", "111 ", "000 "\]
**Output:** 0
**Explanation:** There does not exist two devices located on two different rows.

**Constraints:**

*   `m == bank.length`
*   `n == bank[i].length`
*   `1 <= m, n <= 500`
*   `bank[i][j]` is either `'0'` or `'1'`.

## A solution in Java

```java
public boolean canSortUsingSwap(int[] nums) {
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] < nums[i - 1]) {
            int temp = nums[i];
            nums[i] = nums[i - 1];
            nums[i - 1] = temp;
            if (isSorted(nums)) {
                return true;
            }
            temp = nums[i];
            nums[i] = nums[i - 1];
            nums[i - 1] = temp;
        }
    }
    return false;
}

private boolean isSorted(int[] nums) {
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] < nums[i - 1]) {
            return false;
        }
    }
    return true;
}
```
The algorithm starts iterating through the given array starting from the second element. It then checks if the current element is smaller than the previous one. If so, it swaps these two elements temporarily and checks if the resulting array is sorted. If the array is sorted, it returns true as it's possible to sort the array using the above swap method. If not, it swaps the elements back to their original positions and continues the iteration. If no swaps can sort the array, it returns false.

## A solution in C++

```cpp
#include <vector>

bool canSortUsingSwap(std::vector<int>& nums) {
    for (size_t i = 1; i < nums.size(); i++) {
        if (nums[i] < nums[i - 1]) {
            std::swap(nums[i], nums[i - 1]);
            if (std::is_sorted(nums.begin(), nums.end())) {
                return true;
            }
            std::swap(nums[i], nums[i - 1]);
        }
    }
    return false;
}
```
The algorithm starts iterating through the given array starting from the second element. It then checks if the current element is smaller than the previous one. If so, it swaps these two elements temporarily and checks if the resulting array is sorted. If the array is sorted, it returns true as it's possible to sort the array using the above swap method. If not, it swaps the elements back to their original positions and continues the iteration. If no swaps can sort the array, it returns false.

## A solution in Python

```python
def can_sort_using_swap(nums):
    for i in range(1, len(nums)):
        if nums[i] < nums[i - 1]:
            nums[i], nums[i - 1] = nums[i - 1], nums[i]
            if sorted(nums) == nums:
                return True
            nums[i], nums[i - 1] = nums[i - 1], nums[i]
    return False
```
The algorithm starts iterating through the given array starting from the second element. It then checks if the current element is smaller than the previous one. If so, it swaps these two elements temporarily and checks if the resulting array is sorted. If the array is sorted, it returns true as it's possible to sort the array using the above swap method. If not, it swaps the elements back to their original positions and continues the iteration. If no swaps can sort the array, it returns false.

## A solution in Javascript

```javascript
function canSortUsingSwap(nums) {
    function isSorted(arr) {
        for (let i = 1; i < arr.length; i++) {
            if (arr[i] < arr[i - 1]) {
                return false;
            }
        }
        return true;
    }

    for (let i = 1; i < nums.length; i++) {
        if (nums[i] < nums[i - 1]) {
            [nums[i], nums[i - 1]] = [nums[i - 1], nums[i]];
            if (isSorted(nums)) {
                return true;
            }
            [nums[i], nums[i - 1]] = [nums[i - 1], nums[i]];
        }
    }
    return false;
}
```
The algorithm starts iterating through the given array starting from the second element. It then checks if the current element is smaller than the previous one. If so, it swaps these two elements temporarily and checks if the resulting array is sorted. If the array is sorted, it returns true as it's possible to sort the array using the above swap method. If not, it swaps the elements back to their original positions and continues the iteration. If no swaps can sort the array, it returns false.


# Destroying Asteroids

- slug: destroying-asteroids
- difficulty: Medium

You are given an integer `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid.

You can arrange for the planet to collide with the asteroids in **any arbitrary order**. If the mass of the planet is **greater than or equal to** the mass of the asteroid, the asteroid is **destroyed** and the planet **gains** the mass of the asteroid. Otherwise, the planet is destroyed.

Return `true` _if **all** asteroids can be destroyed. Otherwise, return_ `false`_._

**Example 1:**

**Input:** mass = 10, asteroids = \[3,9,19,5,21\]
**Output:** true
**Explanation:** One way to order the asteroids is \[9,19,5,3,21\]:
- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19
- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38
- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43
- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46
- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67
All asteroids are destroyed.

**Example 2:**

**Input:** mass = 5, asteroids = \[4,9,23,4\]
**Output:** false
**Explanation:**
The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.
After the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.
This is less than 23, so a collision would not destroy the last asteroid.

**Constraints:**

*   `1 <= mass <= 105`
*   `1 <= asteroids.length <= 105`
*   `1 <= asteroids[i] <= 105`

## A solution in Java

```java
boolean canDestroyAll(int mass, int[] asteroids) {
    Arrays.sort(asteroids);
    for (int asteroid : asteroids) {
        if (mass >= asteroid) {
            mass += asteroid;
        } else {
            return false;
        }
    }
    return true;
}
```
- Sort the asteroids array in ascending order.
- Iterate through the sorted asteroids array.
- At each iteration, check if the planet's mass is greater than or equal to the asteroid's mass.
  - If it is, add the asteroid's mass to the planet's mass.
  - If it isn't, return `false` because the planet cannot destroy all asteroids.
- If the iteration completes successfully, return `true` as the planet can destroy all asteroids.

## A solution in C++

```cpp
bool canDestroyAll(int mass, vector<int>& asteroids) {
    sort(asteroids.begin(), asteroids.end());
    for (int asteroid : asteroids) {
        if (mass >= asteroid) {
            mass += asteroid;
        } else {
            return false;
        }
    }
    return true;
}
```
- Sort the asteroids array in ascending order.
- Iterate through the sorted asteroids array.
- At each iteration, check if the planet's mass is greater than or equal to the asteroid's mass.
  - If it is, add the asteroid's mass to the planet's mass.
  - If it isn't, return `false` because the planet cannot destroy all asteroids.
- If the iteration completes successfully, return `true` as the planet can destroy all asteroids.

## A solution in Python

```python
def can_destroy_all(mass: int, asteroids: List[int]) -> bool:
    asteroids.sort()
    for asteroid in asteroids:
        if mass >= asteroid:
            mass += asteroid
        else:
            return False
    return True
```
- Sort the asteroids array in ascending order.
- Iterate through the sorted asteroids array.
- At each iteration, check if the planet's mass is greater than or equal to the asteroid's mass.
  - If it is, add the asteroid's mass to the planet's mass.
  - If it isn't, return `false` because the planet cannot destroy all asteroids.
- If the iteration completes successfully, return `true` as the planet can destroy all asteroids.

## A solution in Javascript

```javascript
function canDestroyAll(mass, asteroids) {
    asteroids.sort((a, b) => a - b);
    for (const asteroid of asteroids) {
        if (mass >= asteroid) {
            mass += asteroid;
        } else {
            return false;
        }
    }
    return true;
}
```
- Sort the asteroids array in ascending order.
- Iterate through the sorted asteroids array.
- At each iteration, check if the planet's mass is greater than or equal to the asteroid's mass.
  - If it is, add the asteroid's mass to the planet's mass.
  - If it isn't, return `false` because the planet cannot destroy all asteroids.
- If the iteration completes successfully, return `true` as the planet can destroy all asteroids.


# Maximum Employees to Be Invited to a Meeting

- slug: maximum-employees-to-be-invited-to-a-meeting
- difficulty: Hard

A company is organizing a meeting and has a list of `n` employees, waiting to be invited. They have arranged for a large **circular** table, capable of seating **any number** of employees.

The employees are numbered from `0` to `n - 1`. Each employee has a **favorite** person and they will attend the meeting **only if** they can sit next to their favorite person at the table. The favorite person of an employee is **not** themself.

Given a **0-indexed** integer array `favorite`, where `favorite[i]` denotes the favorite person of the `ith` employee, return _the **maximum number of employees** that can be invited to the meeting_.

**Example 1:**

**Input:** favorite = \[2,2,1,2\]
**Output:** 3
**Explanation:**
The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.
All employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.
Note that the company can also invite employees 1, 2, and 3, and give them their desired seats.
The maximum number of employees that can be invited to the meeting is 3.

**Example 2:**

**Input:** favorite = \[1,2,0\]
**Output:** 3
**Explanation:**
Each employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.
The seating arrangement will be the same as that in the figure given in example 1:
- Employee 0 will sit between employees 2 and 1.
- Employee 1 will sit between employees 0 and 2.
- Employee 2 will sit between employees 1 and 0.
The maximum number of employees that can be invited to the meeting is 3.

**Example 3:**

**Input:** favorite = \[3,0,1,4,1\]
**Output:** 4
**Explanation:**
The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.
Employee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.
So the company leaves them out of the meeting.
The maximum number of employees that can be invited to the meeting is 4.

**Constraints:**

*   `n == favorite.length`
*   `2 <= n <= 105`
*   `0 <= favorite[i] <= n - 1`
*   `favorite[i] != i`

## A solution in Java

```java
public int maxInvited(int[] favorite) {
    int[] inDegree = new int[favorite.length];
    for (int fav : favorite) {
        inDegree[fav]++;
    }
    int result = 0;
    for (int degree : inDegree) {
        result += Math.max(degree - 1, 0);
    }
    return Math.min(result + 2, favorite.length);
}
```
The algorithm works by calculating in-degrees, which represent the number of times a person is favored by others. For each person `i`, we add all in-degrees minus one to the result (since a person only needs to be favored by one other person to be included at the table). Finally, we return the minimum of `result + 2` (to account for the first and last person added to the circle) and the total number of people. This ensures we do not invite more people than there are in the input array even if there are enough favorite relationships to do so.

## A solution in C++

```cpp
int maxInvited(vector<int>& favorite) {
    vector<int> in_degree(favorite.size(), 0);
    for (int fav : favorite) {
        in_degree[fav]++;
    }
    int result = 0;
    for (int degree : in_degree) {
        result += max(degree - 1, 0);
    }
    return min(result + 2, (int)favorite.size());
}
```
The algorithm works by calculating in-degrees, which represent the number of times a person is favored by others. For each person `i`, we add all in-degrees minus one to the result (since a person only needs to be favored by one other person to be included at the table). Finally, we return the minimum of `result + 2` (to account for the first and last person added to the circle) and the total number of people. This ensures we do not invite more people than there are in the input array even if there are enough favorite relationships to do so.

## A solution in Python

```python
def max_invited(favorite):
    in_degree = [0] * len(favorite)
    for fav in favorite:
        in_degree[fav] += 1
    result = 0
    for degree in in_degree:
        result += max(degree - 1, 0)
    return min(result + 2, len(favorite))
```
The algorithm works by calculating in-degrees, which represent the number of times a person is favored by others. For each person `i`, we add all in-degrees minus one to the result (since a person only needs to be favored by one other person to be included at the table). Finally, we return the minimum of `result + 2` (to account for the first and last person added to the circle) and the total number of people. This ensures we do not invite more people than there are in the input array even if there are enough favorite relationships to do so.

## A solution in Javascript

```javascript
function maxInvited(favorite) {
    let inDegree = new Array(favorite.length).fill(0);
    for (let fav of favorite) {
        inDegree[fav]++;
    }
    let result = 0;
    for (let degree of inDegree) {
        result += Math.max(degree - 1, 0);
    }
    return Math.min(result + 2, favorite.length);
}
```
The algorithm works by calculating in-degrees, which represent the number of times a person is favored by others. For each person `i`, we add all in-degrees minus one to the result (since a person only needs to be favored by one other person to be included at the table). Finally, we return the minimum of `result + 2` (to account for the first and last person added to the circle) and the total number of people. This ensures we do not invite more people than there are in the input array even if there are enough favorite relationships to do so.


# Remove All Ones With Row and Column Flips

- slug: remove-all-ones-with-row-and-column-flips
- difficulty: Medium

You are given an `m x n` binary matrix `grid`.

In one operation, you can choose **any** row or column and flip each value in that row or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s).

Return `true` _if it is possible to remove all_ `1`_'s from_ `grid` using **any** number of operations or `false` otherwise.

**Example 1:**

**Input:** grid = \[\[0,1,0\],\[1,0,1\],\[0,1,0\]\]
**Output:** true
**Explanation:** One possible way to remove all 1's from grid is to:
- Flip the middle row
- Flip the middle column

**Example 2:**

**Input:** grid = \[\[1,1,0\],\[0,0,0\],\[0,0,0\]\]
**Output:** false
**Explanation:** It is impossible to remove all 1's from grid.

**Example 3:**

**Input:** grid = \[\[0\]\]
**Output:** true
**Explanation:** There are no 1's in grid.

**Constraints:**

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

## A solution in Java

```java
public String reversePrefix(String word, char ch) {
    int index = word.indexOf(ch);
    if (index != -1) {
        StringBuilder sb = new StringBuilder(word.substring(0, index + 1));
        sb.reverse();
        sb.append(word.substring(index + 1));
        return sb.toString();
    }
    return word;
}
```
1. Find the index of the first occurrence of character `ch` in the given string `word`. If the character is not found, return the original string as it is.
2. If the character exists, reverse the substring starting from index 0 to this found index (inclusive).
3. Append the rest of the string after the reversed substring (if any).
4. Return the modified string as the result.

## A solution in C++

```cpp
#include <algorithm>

std::string reversePrefix(std::string word, char ch) {
    auto it = std::find(word.begin(), word.end(), ch);
    if (it != word.end()) {
        std::reverse(word.begin(), it + 1);
    }
    return word;
}
```
1. Find the index of the first occurrence of character `ch` in the given string `word`. If the character is not found, return the original string as it is.
2. If the character exists, reverse the substring starting from index 0 to this found index (inclusive).
3. Append the rest of the string after the reversed substring (if any).
4. Return the modified string as the result.

## A solution in Python

```python
def reverse_prefix(word: str, ch: str) -> str:
    try:
        index = word.index(ch)
        return word[:index+1][::-1] + word[index+1:]
    except ValueError:
        return word
```
1. Find the index of the first occurrence of character `ch` in the given string `word`. If the character is not found, return the original string as it is.
2. If the character exists, reverse the substring starting from index 0 to this found index (inclusive).
3. Append the rest of the string after the reversed substring (if any).
4. Return the modified string as the result.

## A solution in Javascript

```javascript
function reversePrefix(word, ch) {
    const index = word.indexOf(ch);
    if (index !== -1) {
        return word.slice(0, index + 1).split('').reverse().join('') + word.slice(index + 1);
    }
    return word;
}
```
1. Find the index of the first occurrence of character `ch` in the given string `word`. If the character is not found, return the original string as it is.
2. If the character exists, reverse the substring starting from index 0 to this found index (inclusive).
3. Append the rest of the string after the reversed substring (if any).
4. Return the modified string as the result.


# Capitalize the Title

- slug: capitalize-the-title
- difficulty: Easy

You are given a string `title` consisting of one or more words separated by a single space, where each word consists of English letters. **Capitalize** the string by changing the capitalization of each word such that:

*   If the length of the word is `1` or `2` letters, change all letters to lowercase.
*   Otherwise, change the first letter to uppercase and the remaining letters to lowercase.

Return _the **capitalized**_ `title`.

**Example 1:**

**Input:** title =  "capiTalIze tHe titLe "
**Output:**  "Capitalize The Title "
**Explanation:**
Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.

**Example 2:**

**Input:** title =  "First leTTeR of EACH Word "
**Output:**  "First Letter of Each Word "
**Explanation:**
The word  "of " has length 2, so it is all lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.

**Example 3:**

**Input:** title =  "i lOve leetcode "
**Output:**  "i Love Leetcode "
**Explanation:**
The word  "i " has length 1, so it is lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.

**Constraints:**

*   `1 <= title.length <= 100`
*   `title` consists of words separated by a single space without any leading or trailing spaces.
*   Each word consists of uppercase and lowercase English letters and is **non-empty**.

## A solution in Java

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

public int interchangeableRectangles(int[][] rectangles) {
    Map<Double, Integer> ratioCount = new HashMap<>();
    int count = 0;

    for (int[] r : rectangles) {
        double ratio = (double) r[0] / r[1];
        count += ratioCount.getOrDefault(ratio, 0);
        ratioCount.put(ratio, ratioCount.getOrDefault(ratio, 0) + 1);
    }

    return count;
}
```
For each rectangle, we calculate the width-to-height ratio by dividing the width by the height as a floating-point number. We use a hash map called `ratioCount` to maintain the counts of each unique ratio found so far. If the current ratio is already in the hash map, we increment the count of the current ratio by 1 and add the current count of the ratio to our result. In this way, we count the pairs of interchangeable rectangles that can be created with the current rectangle for each ratio.

For example, if the input array is `rectangles = [[4, 8], [3, 6], [10, 20], [12, 24], [12, 16]]`, then we calculate the following width-to-height ratios: `[1/2, 1/2, 1/2, 1/2, 3/4]`. The count of the ratio `1/2` is 4, so the result will be `1 + 2 + 3 = 6`, as these are the number of pairs that can be formed with the 4 rectangles with this ratio.

## A solution in C++

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

int interchangeableRectangles(std::vector<std::vector<int>>& rectangles) {
    std::unordered_map<double, int> ratioCount;
    int count = 0;

    for (const auto& r : rectangles) {
        double ratio = static_cast<double>(r[0]) / r[1];
        count += ratioCount[ratio];
        ratioCount[ratio]++;
    }

    return count;
}
```
For each rectangle, we calculate the width-to-height ratio by dividing the width by the height as a floating-point number. We use a hash map called `ratioCount` to maintain the counts of each unique ratio found so far. If the current ratio is already in the hash map, we increment the count of the current ratio by 1 and add the current count of the ratio to our result. In this way, we count the pairs of interchangeable rectangles that can be created with the current rectangle for each ratio.

For example, if the input array is `rectangles = [[4, 8], [3, 6], [10, 20], [12, 24], [12, 16]]`, then we calculate the following width-to-height ratios: `[1/2, 1/2, 1/2, 1/2, 3/4]`. The count of the ratio `1/2` is 4, so the result will be `1 + 2 + 3 = 6`, as these are the number of pairs that can be formed with the 4 rectangles with this ratio.

## A solution in Python

```python
def interchangeable_rectangles(rectangles):
    ratio_count = {}
    count = 0

    for r in rectangles:
        ratio = r[0] / r[1]
        count += ratio_count.get(ratio, 0)
        ratio_count[ratio] = ratio_count.get(ratio, 0) + 1

    return count
```
For each rectangle, we calculate the width-to-height ratio by dividing the width by the height as a floating-point number. We use a hash map called `ratioCount` to maintain the counts of each unique ratio found so far. If the current ratio is already in the hash map, we increment the count of the current ratio by 1 and add the current count of the ratio to our result. In this way, we count the pairs of interchangeable rectangles that can be created with the current rectangle for each ratio.

For example, if the input array is `rectangles = [[4, 8], [3, 6], [10, 20], [12, 24], [12, 16]]`, then we calculate the following width-to-height ratios: `[1/2, 1/2, 1/2, 1/2, 3/4]`. The count of the ratio `1/2` is 4, so the result will be `1 + 2 + 3 = 6`, as these are the number of pairs that can be formed with the 4 rectangles with this ratio.

## A solution in Javascript

```javascript
function interchangeableRectangles(rectangles) {
    const ratioCount = {};
    let count = 0;

    for (const r of rectangles) {
        const ratio = r[0] / r[1];
        count += ratioCount[ratio] ? ratioCount[ratio] : 0;
        ratioCount[ratio] = (ratioCount[ratio] || 0) + 1;
    }

    return count;
}
```
For each rectangle, we calculate the width-to-height ratio by dividing the width by the height as a floating-point number. We use a hash map called `ratioCount` to maintain the counts of each unique ratio found so far. If the current ratio is already in the hash map, we increment the count of the current ratio by 1 and add the current count of the ratio to our result. In this way, we count the pairs of interchangeable rectangles that can be created with the current rectangle for each ratio.

For example, if the input array is `rectangles = [[4, 8], [3, 6], [10, 20], [12, 24], [12, 16]]`, then we calculate the following width-to-height ratios: `[1/2, 1/2, 1/2, 1/2, 3/4]`. The count of the ratio `1/2` is 4, so the result will be `1 + 2 + 3 = 6`, as these are the number of pairs that can be formed with the 4 rectangles with this ratio.


# Maximum Twin Sum of a Linked List

- slug: maximum-twin-sum-of-a-linked-list
- difficulty: Medium

In a linked list of size `n`, where `n` is **even**, the `ith` node (**0-indexed**) of the linked list is known as the **twin** of the `(n-1-i)th` node, if `0 <= i <= (n / 2) - 1`.

*   For example, if `n = 4`, then node `0` is the twin of node `3`, and node `1` is the twin of node `2`. These are the only nodes with twins for `n = 4`.

The **twin sum** is defined as the sum of a node and its twin.

Given the `head` of a linked list with even length, return _the **maximum twin sum** of the linked list_.

**Example 1:**

**Input:** head = \[5,4,2,1\]
**Output:** 6
**Explanation:**
Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
There are no other nodes with twins in the linked list.
Thus, the maximum twin sum of the linked list is 6.

**Example 2:**

**Input:** head = \[4,2,2,3\]
**Output:** 7
**Explanation:**
The nodes with twins present in this linked list are:
- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
Thus, the maximum twin sum of the linked list is max(7, 4) = 7.

**Example 3:**

**Input:** head = \[1,100000\]
**Output:** 100001
**Explanation:**
There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.

**Constraints:**

*   The number of nodes in the list is an **even** integer in the range `[2, 105]`.
*   `1 <= Node.val <= 105`

## A solution in Java

```java
public int maxProduct(String s) {
    int n = s.length();
    int[][] dp = new int[n][n];

    for (int i = 0; i < n; i++) dp[i][i] = 1;

    for (int len = 2; len <= n; len++) {
        for (int i = 0; i <= n - len; i++) {
            int j = i + len - 1;

            if (s.charAt(i) == s.charAt(j))
                dp[i][j] = dp[i + 1][j - 1] + 2;
            else
                dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
        }
    }

    int max_product = 0;
    for (int i = 1; i < n; i++) {
        max_product = Math.max(max_product, dp[0][i - 1] * dp[i][n - 1]);
    }

    return max_product;
}
```
The main idea of the algorithm is to use dynamic programming to calculate the longest palindromic subsequence length for each possible substring. The 2D matrix `dp` is used to store the longest palindromic subsequence length for each substring in s, where `dp[i][j]` represents the longest palindromic subsequence of the substring s[i...j].

We start by initializing the diagonal of the dp matrix because single characters are always palindromic. Then we iterate through all the possible lengths of substrings (from 2 to n) and calculate the length of the longest palindromic subsequence for each substring. If the first and last characters of the substring are the same, the length increases by 2; otherwise, we take the maximum between the length without the first character and the length without the last character.

Finally, we iterate through all the possible split points in the string and calculate the product of the two non-overlapping palindromic subsequences formed by the split. We return the maximum product obtained.

## A solution in C++

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

int maxProduct(std::string s) {
    int n = s.length();
    std::vector<std::vector<int>> dp(n, std::vector<int>(n, 0));

    for (int i = 0; i < n; i++) dp[i][i] = 1;

    for (int len = 2; len <= n; len++) {
        for (int i = 0; i <= n - len; i++) {
            int j = i + len - 1;

            if (s[i] == s[j])
                dp[i][j] = dp[i + 1][j - 1] + 2;
            else
                dp[i][j] = std::max(dp[i + 1][j], dp[i][j - 1]);
        }
    }

    int max_product = 0;
    for (int i = 1; i < n; i++) {
        max_product = std::max(max_product, dp[0][i - 1] * dp[i][n - 1]);
    }

    return max_product;
}
```
The main idea of the algorithm is to use dynamic programming to calculate the longest palindromic subsequence length for each possible substring. The 2D matrix `dp` is used to store the longest palindromic subsequence length for each substring in s, where `dp[i][j]` represents the longest palindromic subsequence of the substring s[i...j].

We start by initializing the diagonal of the dp matrix because single characters are always palindromic. Then we iterate through all the possible lengths of substrings (from 2 to n) and calculate the length of the longest palindromic subsequence for each substring. If the first and last characters of the substring are the same, the length increases by 2; otherwise, we take the maximum between the length without the first character and the length without the last character.

Finally, we iterate through all the possible split points in the string and calculate the product of the two non-overlapping palindromic subsequences formed by the split. We return the maximum product obtained.

## A solution in Python

```python
def maxProduct(s: str) -> int:
    n = len(s)
    dp = [[0] * n for _ in range(n)]

    for i in range(n):
        dp[i][i] = 1

    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1

            if s[i] == s[j]:
                dp[i][j] = dp[i + 1][j - 1] + 2
            else:
                dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])

    max_product = 0
    for i in range(1, n):
        max_product = max(max_product, dp[0][i - 1] * dp[i][n - 1])

    return max_product
```
The main idea of the algorithm is to use dynamic programming to calculate the longest palindromic subsequence length for each possible substring. The 2D matrix `dp` is used to store the longest palindromic subsequence length for each substring in s, where `dp[i][j]` represents the longest palindromic subsequence of the substring s[i...j].

We start by initializing the diagonal of the dp matrix because single characters are always palindromic. Then we iterate through all the possible lengths of substrings (from 2 to n) and calculate the length of the longest palindromic subsequence for each substring. If the first and last characters of the substring are the same, the length increases by 2; otherwise, we take the maximum between the length without the first character and the length without the last character.

Finally, we iterate through all the possible split points in the string and calculate the product of the two non-overlapping palindromic subsequences formed by the split. We return the maximum product obtained.

## A solution in Javascript

```javascript
function maxProduct(s) {
    const n = s.length;
    const dp = new Array(n).fill(null).map(() => new Array(n).fill(0));

    for (let i = 0; i < n; i++) dp[i][i] = 1;

    for (let length = 2; length <= n; length++) {
        for (let i = 0; i <= n - length; i++) {
            const j = i + length - 1;

            if (s[i] === s[j])
                dp[i][j] = dp[i + 1][j - 1] + 2;
            else
                dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
        }
    }

    let max_product = 0;
    for (let i = 1; i < n; i++) {
        max_product = Math.max(max_product, dp[0][i - 1] * dp[i][n - 1]);
    }

    return max_product;
}
```
The main idea of the algorithm is to use dynamic programming to calculate the longest palindromic subsequence length for each possible substring. The 2D matrix `dp` is used to store the longest palindromic subsequence length for each substring in s, where `dp[i][j]` represents the longest palindromic subsequence of the substring s[i...j].

We start by initializing the diagonal of the dp matrix because single characters are always palindromic. Then we iterate through all the possible lengths of substrings (from 2 to n) and calculate the length of the longest palindromic subsequence for each substring. If the first and last characters of the substring are the same, the length increases by 2; otherwise, we take the maximum between the length without the first character and the length without the last character.

Finally, we iterate through all the possible split points in the string and calculate the product of the two non-overlapping palindromic subsequences formed by the split. We return the maximum product obtained.


# Longest Palindrome by Concatenating Two Letter Words

- slug: longest-palindrome-by-concatenating-two-letter-words
- difficulty: Medium

You are given an array of strings `words`. Each element of `words` consists of **two** lowercase English letters.

Create the **longest possible palindrome** by selecting some elements from `words` and concatenating them in **any order**. Each element can be selected **at most once**.

Return _the **length** of the longest palindrome that you can create_. If it is impossible to create any palindrome, return `0`.

A **palindrome** is a string that reads the same forward and backward.

**Example 1:**

**Input:** words = \[ "lc ", "cl ", "gg "\]
**Output:** 6
**Explanation:** One longest palindrome is  "lc " +  "gg " +  "cl " =  "lcggcl ", of length 6.
Note that  "clgglc " is another longest palindrome that can be created.

**Example 2:**

**Input:** words = \[ "ab ", "ty ", "yt ", "lc ", "cl ", "ab "\]
**Output:** 8
**Explanation:** One longest palindrome is  "ty " +  "lc " +  "cl " +  "yt " =  "tylcclyt ", of length 8.
Note that  "lcyttycl " is another longest palindrome that can be created.

**Example 3:**

**Input:** words = \[ "cc ", "ll ", "xx "\]
**Output:** 2
**Explanation:** One longest palindrome is  "cc ", of length 2.
Note that  "ll " is another longest palindrome that can be created, and so is  "xx ".

**Constraints:**

*   `1 <= words.length <= 105`
*   `words[i].length == 2`
*   `words[i]` consists of lowercase English letters.

## A solution in Java

```java
import java.util.*;

class Solution {
    public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {
        int n = parents.length;
        int[] ans = new int[n];
        List<Set<Integer>> tree = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            tree.add(new HashSet<Integer>());
        }

        dfs(0, parents, nums, tree, ans);
        return ans;
    }

    private void dfs(int node, int[] parents, int[] nums, List<Set<Integer>> tree, int[] ans) {
        tree.get(node).add(nums[node]);
        for (int i = 1; i < parents.length; ++i) {
            if (parents[i] == node) {
                dfs(i, parents, nums, tree, ans);
                tree.get(node).addAll(tree.get(i));
            }
...
        }
        int missing = 1;
        while (tree.get(node).contains(missing)) ++missing;
        ans[node] = missing;
    }
}
```
The algorithm first initializes an empty tree structure and the resulting array `ans`. Each subtree is represented by a set that will store the genetic values of the nodes in the subtree.

The `dfs` function performs a depth-first search on the tree, starting from the root node (node 0). For each node in the tree, it first adds the node's genetic value to its subtree set. Then, for each child of the current node, the `dfs` function is called recursively to explore the descendant nodes. The sets of the child nodes are then merged into the set of the current node.

To find the smallest missing genetic value, an integer `missing` is initialized to 1. A while loop is used to iterate through the values in the current node's subtree set. If a value equal to `missing` is found in the set, `missing` is incremented. If not, the iteration is stopped, and the value of `missing` is assigned to the corresponding position in the resulting array `ans`.

Once the DFS is completed, the function returns the array `ans`.

## A solution in C++

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

void dfs(int node, const vector<int>& parents, const vector<int>& nums, vector<set<int>>& tree, vector<int>& ans) {
    tree[node].insert(nums[node]);
    for (int i = 1; i < (int)parents.size(); ++i) {
        if (parents[i] == node) {
            dfs(i, parents, nums, tree, ans);
            tree[node].insert(tree[i].begin(), tree[i].end());
        }
    }
    int missing = 1;
    while (tree[node].count(missing)) ++missing;
    ans[node] = missing;
}

vector<int> smallestMissingValueSubtree(vector<int>& parents, vector<int>& nums) {
    int n = parents.size();
    vector<int> ans(n);
    vector<set<int>> tree(n);

    dfs(0, parents, nums, tree, ans);
    return ans;
}
```
The algorithm first initializes an empty tree structure and the resulting array `ans`. Each subtree is represented by a set that will store the genetic values of the nodes in the subtree.

The `dfs` function performs a depth-first search on the tree, starting from the root node (node 0). For each node in the tree, it first adds the node's genetic value to its subtree set. Then, for each child of the current node, the `dfs` function is called recursively to explore the descendant nodes. The sets of the child nodes are then merged into the set of the current node.

To find the smallest missing genetic value, an integer `missing` is initialized to 1. A while loop is used to iterate through the values in the current node's subtree set. If a value equal to `missing` is found in the set, `missing` is incremented. If not, the iteration is stopped, and the value of `missing` is assigned to the corresponding position in the resulting array `ans`.

Once the DFS is completed, the function returns the array `ans`.

## A solution in Python

```python
def smallest_missing_value_subtree(parents, nums):
    def dfs(node, parents, nums, tree, ans):
        tree[node].add(nums[node])
        for i in range(1, len(parents)):
            if parents[i] == node:
                dfs(i, parents, nums, tree, ans)
                tree[node].update(tree[i])
        missing = 1
        while missing in tree[node]:
            missing += 1
        ans[node] = missing

    n = len(parents)
    ans = [0] * n
    tree = [set() for _ in range(n)]

    dfs(0, parents, nums, tree, ans)
    return ans
```
The algorithm first initializes an empty tree structure and the resulting array `ans`. Each subtree is represented by a set that will store the genetic values of the nodes in the subtree.

The `dfs` function performs a depth-first search on the tree, starting from the root node (node 0). For each node in the tree, it first adds the node's genetic value to its subtree set. Then, for each child of the current node, the `dfs` function is called recursively to explore the descendant nodes. The sets of the child nodes are then merged into the set of the current node.

To find the smallest missing genetic value, an integer `missing` is initialized to 1. A while loop is used to iterate through the values in the current node's subtree set. If a value equal to `missing` is found in the set, `missing` is incremented. If not, the iteration is stopped, and the value of `missing` is assigned to the corresponding position in the resulting array `ans`.

Once the DFS is completed, the function returns the array `ans`.

## A solution in Javascript

```javascript
function smallestMissingValueSubtree(parents, nums) {
    const n = parents.length;
    const ans = new Array(n).fill(0);
    const tree = Array.from({ length: n }, () => new Set());

    function dfs(node, parents, nums, tree, ans) {
        tree[node].add(nums[node]);
        for (let i = 1; i < parents.length; ++i) {
            if (parents[i] === node) {
                dfs(i, parents, nums, tree, ans);
                tree[node] = new Set([...tree[node], ...tree[i]]);
            }
        }
        let missing = 1;
        while (tree[node].has(missing)) ++missing;
        ans[node] = missing;
    }

    dfs(0, parents, nums, tree, ans);
    return ans;
}
```
The algorithm first initializes an empty tree structure and the resulting array `ans`. Each subtree is represented by a set that will store the genetic values of the nodes in the subtree.

The `dfs` function performs a depth-first search on the tree, starting from the root node (node 0). For each node in the tree, it first adds the node's genetic value to its subtree set. Then, for each child of the current node, the `dfs` function is called recursively to explore the descendant nodes. The sets of the child nodes are then merged into the set of the current node.

To find the smallest missing genetic value, an integer `missing` is initialized to 1. A while loop is used to iterate through the values in the current node's subtree set. If a value equal to `missing` is found in the set, `missing` is incremented. If not, the iteration is stopped, and the value of `missing` is assigned to the corresponding position in the resulting array `ans`.

Once the DFS is completed, the function returns the array `ans`.


# Stamping the Grid

- slug: stamping-the-grid
- difficulty: Hard

You are given an `m x n` binary matrix `grid` where each cell is either `0` (empty) or `1` (occupied).

You are then given stamps of size `stampHeight x stampWidth`. We want to fit the stamps such that they follow the given **restrictions** and **requirements**:

1.  Cover all the **empty** cells.
2.  Do not cover any of the **occupied** cells.
3.  We can put as **many** stamps as we want.
4.  Stamps can **overlap** with each other.
5.  Stamps are not allowed to be **rotated**.
6.  Stamps must stay completely **inside** the grid.

Return `true` _if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return_ `false`.

**Example 1:**

**Input:** grid = \[\[1,0,0,0\],\[1,0,0,0\],\[1,0,0,0\],\[1,0,0,0\],\[1,0,0,0\]\], stampHeight = 4, stampWidth = 3
**Output:** true
**Explanation:** We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells.

**Example 2:**

**Input:** grid = \[\[1,0,0,0\],\[0,1,0,0\],\[0,0,1,0\],\[0,0,0,1\]\], stampHeight = 2, stampWidth = 2
**Output:** false
**Explanation:** There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.

**Constraints:**

*   `m == grid.length`
*   `n == grid[r].length`
*   `1 <= m, n <= 105`
*   `1 <= m * n <= 2 * 105`
*   `grid[r][c]` is either `0` or `1`.
*   `1 <= stampHeight, stampWidth <= 105`

## A solution in Java

```java
public int[][] construct2DArray(int[] original, int m, int n) {
    if (m * n != original.length) return new int[][]{};
    int[][] res = new int[m][n];
    for (int i = 0; i < original.length; ++i) {
        res[i / n][i % n] = original[i];
    }
    return res;
}
```
1. Check if the dimensions (m * n) match the size of the input array. If not, return an empty 2D array.
2. Create an m x n 2D array initialized with zeros.
3. Iterate through the input array elements and assign them to the corresponding row and column of the 2D array using integer division and modulo operations.
4. Return the constructed 2D array.

## A solution in C++

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

vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
    if (m * n != original.size()) return {};
    vector<vector<int>> res(m, vector<int>(n));
    for (int i = 0; i < original.size(); ++i) {
        res[i / n][i % n] = original[i];
    }
    return res;
}
```
1. Check if the dimensions (m * n) match the size of the input array. If not, return an empty 2D array.
2. Create an m x n 2D array initialized with zeros.
3. Iterate through the input array elements and assign them to the corresponding row and column of the 2D array using integer division and modulo operations.
4. Return the constructed 2D array.

## A solution in Python

```python
def construct2DArray(original, m, n):
    if m * n != len(original): return []
    res = [[0] * n for _ in range(m)]
    for i in range(len(original)):
        res[i // n][i % n] = original[i]
    return res
```
1. Check if the dimensions (m * n) match the size of the input array. If not, return an empty 2D array.
2. Create an m x n 2D array initialized with zeros.
3. Iterate through the input array elements and assign them to the corresponding row and column of the 2D array using integer division and modulo operations.
4. Return the constructed 2D array.

## A solution in Javascript

```javascript
function construct2DArray(original, m, n) {
    if (m * n !== original.length) return [];
    const res = new Array(m).fill(0).map(() => new Array(n).fill(0));
    for (let i = 0; i < original.length; ++i) {
        res[Math.floor(i / n)][i % n] = original[i];
    }
    return res;
}
```
1. Check if the dimensions (m * n) match the size of the input array. If not, return an empty 2D array.
2. Create an m x n 2D array initialized with zeros.
3. Iterate through the input array elements and assign them to the corresponding row and column of the 2D array using integer division and modulo operations.
4. Return the constructed 2D array.