# Minimum Number of Food Buckets to Feed the Hamsters

- slug: minimum-number-of-food-buckets-to-feed-the-hamsters
- difficulty: Medium

You are given a **0-indexed** string `hamsters` where `hamsters[i]` is either:

*   `'H'` indicating that there is a hamster at index `i`, or
*   `'.'` indicating that index `i` is empty.

You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at least one food bucket to its left or to its right. More formally, a hamster at index `i` can be fed if you place a food bucket at index `i - 1` **and/or** at index `i + 1`.

Return _the minimum number of food buckets you should **place at empty indices** to feed all the hamsters or_ `-1` _if it is impossible to feed all of them_.

**Example 1:**

**Input:** hamsters =  "H..H "
**Output:** 2
**Explanation:** We place two food buckets at indices 1 and 2.
It can be shown that if we place only one food bucket, one of the hamsters will not be fed.

**Example 2:**

**Input:** hamsters =  ".H.H. "
**Output:** 1
**Explanation:** We place one food bucket at index 2.

**Example 3:**

**Input:** hamsters =  ".HHH. "
**Output:** -1
**Explanation:** If we place a food bucket at every empty index as shown, the hamster at index 2 will not be able to eat.

**Constraints:**

*   `1 <= hamsters.length <= 105`
*   `hamsters[i]` is either`'H'` or `'.'`.

## A solution in Java

```java
public int num_special_subsequences(int[] nums) {
    long zeros = 0, ones = 0, twos = 0;
    int mod = 1000000007;
    for (int num : nums) {
        if (num == 0) {
            zeros = (zeros + 1) % mod;
        } else if (num == 1) {
            ones = (ones + zeros) % mod;
        } else {
            twos = (twos + ones) % mod;
        }
    }
    return (int) twos;
}
```
The algorithm involves counting the number of subsequences that are special. Initialize three counters, `zeros`, `ones`, and `twos`, to count the special subsequences ending with those values. Iterate the array and for each element, update the respective counter. If the element is 0, increment the `zeros` counter, if it is 1, add the number of `zeros` to the `ones` counter, and if it is 2, add the number of `ones` to the `twos` counter. All operations must be performed modulo 109 + 7 to keep the result within required bounds. Finally, return the value of `twos`, which represents the number of special subsequences. ###

## A solution in C++

```cpp
int num_special_subsequences(vector<int>& nums) {
    long long zeros = 0, ones = 0, twos = 0;
    long long mod = 1000000007;
    for (int num : nums) {
        if (num == 0) {
            zeros = (zeros + 1) % mod;
        } else if (num == 1) {
            ones = (ones + zeros) % mod;
        } else {
            twos = (twos + ones) % mod;
        }
    }
    return twos;
}
```
The algorithm involves counting the number of subsequences that are special. Initialize three counters, `zeros`, `ones`, and `twos`, to count the special subsequences ending with those values. Iterate the array and for each element, update the respective counter. If the element is 0, increment the `zeros` counter, if it is 1, add the number of `zeros` to the `ones` counter, and if it is 2, add the number of `ones` to the `twos` counter. All operations must be performed modulo 109 + 7 to keep the result within required bounds. Finally, return the value of `twos`, which represents the number of special subsequences. ###

## A solution in Python

```python
def num_special_subsequences(nums):
    zeros, ones, twos = 0, 0, 0
    mod = 1000000007
    for num in nums:
        if num == 0:
            zeros = (zeros + 1) % mod
        elif num == 1:
            ones = (ones + zeros) % mod
        else:
            twos = (twos + ones) % mod
    return twos
```
The algorithm involves counting the number of subsequences that are special. Initialize three counters, `zeros`, `ones`, and `twos`, to count the special subsequences ending with those values. Iterate the array and for each element, update the respective counter. If the element is 0, increment the `zeros` counter, if it is 1, add the number of `zeros` to the `ones` counter, and if it is 2, add the number of `ones` to the `twos` counter. All operations must be performed modulo 109 + 7 to keep the result within required bounds. Finally, return the value of `twos`, which represents the number of special subsequences. ###

## A solution in Javascript

```javascript
function num_special_subsequences(nums) {
    let zeros = 0, ones = 0, twos = 0;
    const mod = 1000000007;
    for (const num of nums) {
        if (num === 0) {
            zeros = (zeros + 1) % mod;
        } else if (num === 1) {
            ones = (ones + zeros) % mod;
        } else {
            twos = (twos + ones) % mod;
        }
    }
    return twos;
}
```
The algorithm involves counting the number of subsequences that are special. Initialize three counters, `zeros`, `ones`, and `twos`, to count the special subsequences ending with those values. Iterate the array and for each element, update the respective counter. If the element is 0, increment the `zeros` counter, if it is 1, add the number of `zeros` to the `ones` counter, and if it is 2, add the number of `ones` to the `twos` counter. All operations must be performed modulo 109 + 7 to keep the result within required bounds. Finally, return the value of `twos`, which represents the number of special subsequences. ###


# Minimum Cost Homecoming of a Robot in a Grid

- slug: minimum-cost-homecoming-of-a-robot-in-a-grid
- difficulty: Medium

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

The robot needs to go to its home. It can move one cell in four directions: **left**, **right**, **up**, or **down**, and it can not move outside the boundary. Every move incurs some cost. You are further given two **0-indexed** integer arrays: `rowCosts` of length `m` and `colCosts` of length `n`.

*   If the robot moves **up** or **down** into a cell whose **row** is `r`, then this move costs `rowCosts[r]`.
*   If the robot moves **left** or **right** into a cell whose **column** is `c`, then this move costs `colCosts[c]`.

Return _the **minimum total cost** for this robot to return home_.

**Example 1:**

**Input:** startPos = \[1, 0\], homePos = \[2, 3\], rowCosts = \[5, 4, 3\], colCosts = \[8, 2, 6, 7\]
**Output:** 18
**Explanation:** One optimal path is that:
Starting from (1, 0)
-> It goes down to (**2**, 0). This move costs rowCosts\[2\] = 3.
-> It goes right to (2, **1**). This move costs colCosts\[1\] = 2.
-> It goes right to (2, **2**). This move costs colCosts\[2\] = 6.
-> It goes right to (2, **3**). This move costs colCosts\[3\] = 7.
The total cost is 3 + 2 + 6 + 7 = 18

**Example 2:**

**Input:** startPos = \[0, 0\], homePos = \[0, 0\], rowCosts = \[5\], colCosts = \[26\]
**Output:** 0
**Explanation:** The robot is already at its home. Since no moves occur, the total cost is 0.

**Constraints:**

*   `m == rowCosts.length`
*   `n == colCosts.length`
*   `1 <= m, n <= 105`
*   `0 <= rowCosts[r], colCosts[c] <= 104`
*   `startPos.length == 2`
*   `homePos.length == 2`
*   `0 <= startrow, homerow < m`
*   `0 <= startcol, homecol < n`

## A solution in Java

```java
public int minTotalCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {
    int rowDifference = Math.abs(startPos[0] - homePos[0]);
    int colDifference = Math.abs(startPos[1] - homePos[1]);

    int rowCost = 0, colCost = 0;
    for (int i = 0; i < rowDifference; i++)
        rowCost += rowCosts[i + Math.min(startPos[0], homePos[0])];
    for (int i = 0; i < colDifference; i++)
        colCost += colCosts[i + Math.min(startPos[1], homePos[1])];

    return rowCost + colCost;
}
```
The algorithm tries to solve the problem by first calculating the absolute differences in rows and columns of the `startPos` and `homePos` arrays. Then, it calculates the respective costs for rows and columns by summing up the values in the `rowCosts` and `colCosts` arrays starting from the minimum row and column position of `startPos` and `homePos` up to the row and column difference. Finally, the algorithm returns the sum of the row and column costs.

## A solution in C++

```cpp
int minTotalCost(vector<int>& startPos, vector<int>& homePos, vector<int>& rowCosts, vector<int>& colCosts) {
    int rowDifference = abs(startPos[0] - homePos[0]);
    int colDifference = abs(startPos[1] - homePos[1]);

    int rowCost = 0, colCost = 0;
    for (int i = 0; i < rowDifference; i++)
        rowCost += rowCosts[i + min(startPos[0], homePos[0])];
    for (int i = 0; i < colDifference; i++)
        colCost += colCosts[i + min(startPos[1], homePos[1])];

    return rowCost + colCost;
}
```
The algorithm tries to solve the problem by first calculating the absolute differences in rows and columns of the `startPos` and `homePos` arrays. Then, it calculates the respective costs for rows and columns by summing up the values in the `rowCosts` and `colCosts` arrays starting from the minimum row and column position of `startPos` and `homePos` up to the row and column difference. Finally, the algorithm returns the sum of the row and column costs.

## A solution in Python

```python
def minTotalCost(startPos, homePos, rowCosts, colCosts):
    row_difference = abs(startPos[0] - homePos[0])
    col_difference = abs(startPos[1] - homePos[1])

    row_cost = sum(rowCosts[min(startPos[0], homePos[0]):min(startPos[0], homePos[0]) + row_difference])
    col_cost = sum(colCosts[min(startPos[1], homePos[1]):min(startPos[1], homePos[1]) + col_difference])

    return row_cost + col_cost
```
The algorithm tries to solve the problem by first calculating the absolute differences in rows and columns of the `startPos` and `homePos` arrays. Then, it calculates the respective costs for rows and columns by summing up the values in the `rowCosts` and `colCosts` arrays starting from the minimum row and column position of `startPos` and `homePos` up to the row and column difference. Finally, the algorithm returns the sum of the row and column costs.

## A solution in Javascript

```javascript
function minTotalCost(startPos, homePos, rowCosts, colCosts) {
    const rowDifference = Math.abs(startPos[0] - homePos[0]);
    const colDifference = Math.abs(startPos[1] - homePos[1]);

    let rowCost = 0, colCost = 0;
    for (let i = 0; i < rowDifference; i++)
        rowCost += rowCosts[i + Math.min(startPos[0], homePos[0])];
    for (let i = 0; i < colDifference; i++)
        colCost += colCosts[i + Math.min(startPos[1], homePos[1])];

    return rowCost + colCost;
}
```
The algorithm tries to solve the problem by first calculating the absolute differences in rows and columns of the `startPos` and `homePos` arrays. Then, it calculates the respective costs for rows and columns by summing up the values in the `rowCosts` and `colCosts` arrays starting from the minimum row and column position of `startPos` and `homePos` up to the row and column difference. Finally, the algorithm returns the sum of the row and column costs.


# Count Fertile Pyramids in a Land

- slug: count-fertile-pyramids-in-a-land
- difficulty: Hard

A farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are considered barren.

A **pyramidal plot** of land can be defined as a set of cells with the following criteria:

1.  The number of cells in the set has to be **greater than** `1` and all cells must be **fertile**.
2.  The **apex** of a pyramid is the **topmost** cell of the pyramid. The **height** of a pyramid is the number of rows it covers. Let `(r, c)` be the apex of the pyramid, and its height be `h`. Then, the plot comprises of cells `(i, j)` where `r <= i <= r + h - 1` **and** `c - (i - r) <= j <= c + (i - r)`.

An **inverse pyramidal plot** of land can be defined as a set of cells with similar criteria:

1.  The number of cells in the set has to be **greater than** `1` and all cells must be **fertile**.
2.  The **apex** of an inverse pyramid is the **bottommost** cell of the inverse pyramid. The **height** of an inverse pyramid is the number of rows it covers. Let `(r, c)` be the apex of the pyramid, and its height be `h`. Then, the plot comprises of cells `(i, j)` where `r - h + 1 <= i <= r` **and** `c - (r - i) <= j <= c + (r - i)`.

Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells.

Given a **0-indexed** `m x n` binary matrix `grid` representing the farmland, return _the **total number** of pyramidal and inverse pyramidal plots that can be found in_ `grid`.

**Example 1:**

**Input:** grid = \[\[0,1,1,0\],\[1,1,1,1\]\]
**Output:** 2
**Explanation:** The 2 possible pyramidal plots are shown in blue and red respectively.
There are no inverse pyramidal plots in this grid.
Hence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.

**Example 2:**

**Input:** grid = \[\[1,1,1\],\[1,1,1\]\]
**Output:** 2
**Explanation:** The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red.
Hence the total number of plots is 1 + 1 = 2.

**Example 3:**

**Input:** grid = \[\[1,1,1,1,0\],\[1,1,1,1,1\],\[1,1,1,1,1\],\[0,1,0,0,1\]\]
**Output:** 13
**Explanation:** There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.
There are 6 inverse pyramidal plots, 2 of which are shown in the last figure.
The total number of plots is 7 + 6 = 13.

**Constraints:**

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

## A solution in Java

```java
public int minTimeToType(String word) {
    int time = 0, prev = 0;
    for (char c : word.toCharArray()) {
        int pos = c - 'a';
        time += Math.min(Math.abs(pos - prev), 26 - Math.abs(pos - prev)) + 1;
        prev = pos;
    }
    return time;
}
```
The algorithm calculates the minimum time to type the characters in the given word. We initialize time and previous character position to 0. We then loop through each character in the word and calculate their position in alphabet by subtracting 'a'.

To find the time to move the pointer from the previous character to the current character, we use the minimum of the absolute difference between the positions and 26 - absolute difference between positions (because at max distance is 13 letters). We add 1 to the total time because typing the character would take 1 second as well.

Update the previous position variable to the current character position and continue this process for all the characters in the word. The resulting total time is the minimum number of seconds required to type the given word.

## A solution in C++

```cpp
int minTimeToType(string word) {
    int time = 0, prev = 0;
    for (char c : word) {
        int pos = c - 'a';
        time += min(abs(pos - prev), 26 - abs(pos - prev)) + 1;
        prev = pos;
    }
    return time;
}
```
The algorithm calculates the minimum time to type the characters in the given word. We initialize time and previous character position to 0. We then loop through each character in the word and calculate their position in alphabet by subtracting 'a'.

To find the time to move the pointer from the previous character to the current character, we use the minimum of the absolute difference between the positions and 26 - absolute difference between positions (because at max distance is 13 letters). We add 1 to the total time because typing the character would take 1 second as well.

Update the previous position variable to the current character position and continue this process for all the characters in the word. The resulting total time is the minimum number of seconds required to type the given word.

## A solution in Python

```python
def min_time_to_type(word: str) -> int:
    time, prev = 0, 0
    for c in word:
        pos = ord(c) - ord('a')
        time += min(abs(pos - prev), 26 - abs(pos - prev)) + 1
        prev = pos
    return time
```
The algorithm calculates the minimum time to type the characters in the given word. We initialize time and previous character position to 0. We then loop through each character in the word and calculate their position in alphabet by subtracting 'a'.

To find the time to move the pointer from the previous character to the current character, we use the minimum of the absolute difference between the positions and 26 - absolute difference between positions (because at max distance is 13 letters). We add 1 to the total time because typing the character would take 1 second as well.

Update the previous position variable to the current character position and continue this process for all the characters in the word. The resulting total time is the minimum number of seconds required to type the given word.

## A solution in Javascript

```javascript
function minTimeToType(word) {
    let time = 0, prev = 0;
    for (let c of word) {
        let pos = c.charCodeAt(0) - 'a'.charCodeAt(0);
        time += Math.min(Math.abs(pos - prev), 26 - Math.abs(pos - prev)) + 1;
        prev = pos;
    }
    return time;
}
```
The algorithm calculates the minimum time to type the characters in the given word. We initialize time and previous character position to 0. We then loop through each character in the word and calculate their position in alphabet by subtracting 'a'.

To find the time to move the pointer from the previous character to the current character, we use the minimum of the absolute difference between the positions and 26 - absolute difference between positions (because at max distance is 13 letters). We add 1 to the total time because typing the character would take 1 second as well.

Update the previous position variable to the current character position and continue this process for all the characters in the word. The resulting total time is the minimum number of seconds required to type the given word.


# Find Target Indices After Sorting Array

- slug: find-target-indices-after-sorting-array
- difficulty: Easy

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

A **target index** is an index `i` such that `nums[i] == target`.

Return _a list of the target indices of_ `nums` after _sorting_ `nums` _in **non-decreasing** order_. If there are no target indices, return _an **empty** list_. The returned list must be sorted in **increasing** order.

**Example 1:**

**Input:** nums = \[1,2,5,2,3\], target = 2
**Output:** \[1,2\]
**Explanation:** After sorting, nums is \[1,**2**,**2**,3,5\].
The indices where nums\[i\] == 2 are 1 and 2.

**Example 2:**

**Input:** nums = \[1,2,5,2,3\], target = 3
**Output:** \[3\]
**Explanation:** After sorting, nums is \[1,2,2,**3**,5\].
The index where nums\[i\] == 3 is 3.

**Example 3:**

**Input:** nums = \[1,2,5,2,3\], target = 5
**Output:** \[4\]
**Explanation:** After sorting, nums is \[1,2,2,3,**5**\].
The index where nums\[i\] == 5 is 4.

**Constraints:**

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

## A solution in Java

```java
public int maxMatrixSum(int[][] matrix) {
    int n = matrix.length;
    int minValue = Integer.MAX_VALUE, negativeCount = 0, sum = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            sum += Math.abs(matrix[i][j]);
            minValue = Math.min(minValue, Math.abs(matrix[i][j]));
            if (matrix[i][j] < 0) {
                negativeCount++;
            }
        }
    }

    if (negativeCount % 2 == 0) {
        return sum;
    } else {
        return sum - 2 * minValue;
    }
}
```
To maximize the summation of the matrix's elements, we can follow these steps:
1. Calculate the sum of the absolute values of all elements.
2. Count the number of negative elements in the matrix.
3. Determine the minimum absolute value of all elements in the matrix.
4. If the number of negative values is even, the sum remains the same.
5. If the number of negative values is odd, subtract twice the minimum absolute value from the sum, which accounts for turning an adjacent element from positive to negative, thereby increasing the overall sum.

In each language implementation, we create a function called `maxMatrixSum` that takes an n x n integer matrix as input and loops through the matrix to calculate the values described in the steps above. The function then returns either the sum of elements or the sum minus twice the minimum absolute value depending on the number of negative values. This way, we maximize the summation of the matrix's elements.

## A solution in C++

```cpp
int maxMatrixSum(vector<vector<int>>& matrix) {
    int n = matrix.size();
    int minValue = INT_MAX, negativeCount = 0, sum = 0;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            sum += abs(matrix[i][j]);
            minValue = min(minValue, abs(matrix[i][j]));
            if (matrix[i][j] < 0) {
                negativeCount++;
            }
        }
    }

    if (negativeCount % 2 == 0) {
        return sum;
    } else {
        return sum - 2 * minValue;
    }
}
```
To maximize the summation of the matrix's elements, we can follow these steps:
1. Calculate the sum of the absolute values of all elements.
2. Count the number of negative elements in the matrix.
3. Determine the minimum absolute value of all elements in the matrix.
4. If the number of negative values is even, the sum remains the same.
5. If the number of negative values is odd, subtract twice the minimum absolute value from the sum, which accounts for turning an adjacent element from positive to negative, thereby increasing the overall sum.

In each language implementation, we create a function called `maxMatrixSum` that takes an n x n integer matrix as input and loops through the matrix to calculate the values described in the steps above. The function then returns either the sum of elements or the sum minus twice the minimum absolute value depending on the number of negative values. This way, we maximize the summation of the matrix's elements.

## A solution in Python

```python
def maxMatrixSum(matrix):
    n = len(matrix)
    minValue, negativeCount, total = float('inf'), 0, 0

    for i in range(n):
        for j in range(n):
            total += abs(matrix[i][j])
            minValue = min(minValue, abs(matrix[i][j]))
            if matrix[i][j] < 0:
                negativeCount += 1

    if negativeCount % 2 == 0:
        return total
    else:
        return total - 2 * minValue
```
To maximize the summation of the matrix's elements, we can follow these steps:
1. Calculate the sum of the absolute values of all elements.
2. Count the number of negative elements in the matrix.
3. Determine the minimum absolute value of all elements in the matrix.
4. If the number of negative values is even, the sum remains the same.
5. If the number of negative values is odd, subtract twice the minimum absolute value from the sum, which accounts for turning an adjacent element from positive to negative, thereby increasing the overall sum.

In each language implementation, we create a function called `maxMatrixSum` that takes an n x n integer matrix as input and loops through the matrix to calculate the values described in the steps above. The function then returns either the sum of elements or the sum minus twice the minimum absolute value depending on the number of negative values. This way, we maximize the summation of the matrix's elements.

## A solution in Javascript

```javascript
function maxMatrixSum(matrix) {
    const n = matrix.length;
    let minValue = Infinity, negativeCount = 0, sum = 0;

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            sum += Math.abs(matrix[i][j]);
            minValue = Math.min(minValue, Math.abs(matrix[i][j]));
            if (matrix[i][j] < 0) {
                negativeCount++;
            }
        }
    }

    if (negativeCount % 2 === 0) {
        return sum;
    } else {
        return sum - 2 * minValue;
    }
}
```
To maximize the summation of the matrix's elements, we can follow these steps:
1. Calculate the sum of the absolute values of all elements.
2. Count the number of negative elements in the matrix.
3. Determine the minimum absolute value of all elements in the matrix.
4. If the number of negative values is even, the sum remains the same.
5. If the number of negative values is odd, subtract twice the minimum absolute value from the sum, which accounts for turning an adjacent element from positive to negative, thereby increasing the overall sum.

In each language implementation, we create a function called `maxMatrixSum` that takes an n x n integer matrix as input and loops through the matrix to calculate the values described in the steps above. The function then returns either the sum of elements or the sum minus twice the minimum absolute value depending on the number of negative values. This way, we maximize the summation of the matrix's elements.


# K Radius Subarray Averages

- slug: k-radius-subarray-averages
- difficulty: Medium

You are given a **0-indexed** array `nums` of `n` integers, and an integer `k`.

The **k-radius average** for a subarray of `nums` **centered** at some index `i` with the **radius** `k` is the average of **all** elements in `nums` between the indices `i - k` and `i + k` (**inclusive**). If there are less than `k` elements before **or** after the index `i`, then the **k-radius average** is `-1`.

Build and return _an array_ `avgs` _of length_ `n` _where_ `avgs[i]` _is the **k-radius average** for the subarray centered at index_ `i`.

The **average** of `x` elements is the sum of the `x` elements divided by `x`, using **integer division**. The integer division truncates toward zero, which means losing its fractional part.

*   For example, the average of four elements `2`, `3`, `1`, and `5` is `(2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75`, which truncates to `2`.

**Example 1:**

**Input:** nums = \[7,4,3,9,1,8,5,2,6\], k = 3
**Output:** \[-1,-1,-1,5,4,4,-1,-1,-1\]
**Explanation:**
- avg\[0\], avg\[1\], and avg\[2\] are -1 because there are less than k elements **before** each index.
- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.
  Using **integer division**, avg\[3\] = 37 / 7 = 5.
- For the subarray centered at index 4, avg\[4\] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.
- For the subarray centered at index 5, avg\[5\] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.
- avg\[6\], avg\[7\], and avg\[8\] are -1 because there are less than k elements **after** each index.

**Example 2:**

**Input:** nums = \[100000\], k = 0
**Output:** \[100000\]
**Explanation:**
- The sum of the subarray centered at index 0 with radius 0 is: 100000.
  avg\[0\] = 100000 / 1 = 100000.

**Example 3:**

**Input:** nums = \[8\], k = 100000
**Output:** \[-1\]
**Explanation:**
- avg\[0\] is -1 because there are less than k elements before and after index 0.

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

class Solution {
    private static final int MODULO = 1000000007;

    public int countPaths(int n, int[][] roads) {
        List<List<int[]>> adjList = new ArrayList<>();

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

        for (int[] road : roads) {
            adjList.get(road[0]).add(new int[]{road[1], road[2]});
            adjList.get(road[1]).add(new int[]{road[0], road[2]});
        }

        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[0] = 0;
        int[] cnt = new int[n];
        cnt[0] = 1;
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
        pq.add(new int[]{0, 0});

        while (!pq.isEmpty()) {
            int[] cur = pq.poll();
            int node = cur[0], distance = cur[1];

            if (distance > dist[node]) continue;

            for (int[] neighbor : adjList.get(node)) {
                int nextNode = neighbor[0], edgeDist = neighbor[1];

                if (distance + edgeDist > dist[nextNode]) continue;

                if (distance + edgeDist == dist[nextNode]) {
                    cnt[nextNode] = (cnt[nextNode] + cnt[node]) % MODULO;
                } else {
                    cnt[nextNode] = cnt[node];
                    dist[nextNode] = distance + edgeDist;
                    pq.add(new int[]{nextNode, dist[nextNode]});
                }
            }
        }

        return cnt[n - 1];
    }
}
```
To solve this problem, we first build an adjacency list to represent the city layout graph. We then initialize the distance to each intersection initially to infinity (maximum integer for the specific language), except for the starting point (intersection 0), which is set to 0.

Next, we define an array (or vector in the case of C++) to keep track of the number of ways we can reach each intersection in the shortest time, and we set the initial count for the starting point to 1.

We create a priority queue (min-heap) and insert the starting intersection with a distance of 0. We then check each intersection until the priority queue is empty, following these steps:
1. Pop the intersection with the shortest distance from the priority queue.
2. Check if the current distance is greater than the one stored in the distance array. If so, it means we've already found a better path, and we continue with the next intersection in the queue.
3. Iterate through the neighbors of the current intersection.
   - If the current path's distance plus the distance to the neighboring intersection is greater than the best-known distance to that neighboring intersection, then this path does not offer a shorter route, and we continue to the next neighbor.
   - If the current path's distance plus the distance to the neighboring intersection is equal to the best-known distance to that neighboring intersection, we update the count of ways to reach that neighbor, maintaining the modulo 10^9 + 7 (to avoid large numbers).
   - If the current path's distance plus the distance to the neighboring intersection is less than the best-known distance to that neighboring intersection, we update both the distance and the count arrays and insert the neighboring intersection into the priority queue.

Finally, we return the number of ways to reach the destination (intersection n - 1) in the count array.

## A solution in C++

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

const int MODULO = 1000000007;

int countPaths(int n, vector<vector<int>>& roads) {
    vector<vector<pair<int, int>>> adj_list(n);

    for (auto& road : roads) {
        adj_list[road[0]].emplace_back(road[1], road[2]);
        adj_list[road[1]].emplace_back(road[0], road[2]);
    }

    vector<int> dist(n, 1e9);
    dist[0] = 0;
    vector<int> count(n);
    count[0] = 1;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, 0});

    while (!pq.empty()) {
        int node = pq.top().second;
        int distance = pq.top().first;
        pq.pop();

        if (distance > dist[node]) continue;

        for (auto& neighbor : adj_list[node]) {
            int next_node = neighbor.first;
            int edge_distance = neighbor.second;

            if (distance + edge_distance > dist[next_node]) continue;

            if (distance + edge_distance == dist[next_node]) {
                count[next_node] = (count[next_node] + count[node]) % MODULO;
            } else {
                count[next_node] = count[node];
                dist[next_node] = distance + edge_distance;
                pq.push({dist[next_node], next_node});
            }
        }
    }

    return count[n - 1];
}
```
To solve this problem, we first build an adjacency list to represent the city layout graph. We then initialize the distance to each intersection initially to infinity (maximum integer for the specific language), except for the starting point (intersection 0), which is set to 0.

Next, we define an array (or vector in the case of C++) to keep track of the number of ways we can reach each intersection in the shortest time, and we set the initial count for the starting point to 1.

We create a priority queue (min-heap) and insert the starting intersection with a distance of 0. We then check each intersection until the priority queue is empty, following these steps:
1. Pop the intersection with the shortest distance from the priority queue.
2. Check if the current distance is greater than the one stored in the distance array. If so, it means we've already found a better path, and we continue with the next intersection in the queue.
3. Iterate through the neighbors of the current intersection.
   - If the current path's distance plus the distance to the neighboring intersection is greater than the best-known distance to that neighboring intersection, then this path does not offer a shorter route, and we continue to the next neighbor.
   - If the current path's distance plus the distance to the neighboring intersection is equal to the best-known distance to that neighboring intersection, we update the count of ways to reach that neighbor, maintaining the modulo 10^9 + 7 (to avoid large numbers).
   - If the current path's distance plus the distance to the neighboring intersection is less than the best-known distance to that neighboring intersection, we update both the distance and the count arrays and insert the neighboring intersection into the priority queue.

Finally, we return the number of ways to reach the destination (intersection n - 1) in the count array.

## A solution in Python

```python
from heapq import heappush, heappop

MODULO = 1000000007

def countPaths(n, roads):
    adj_list = [[] for _ in range(n)]

    for u, v, time in roads:
        adj_list[u].append((v, time))
        adj_list[v].append((u, time))

    dist = [float('inf')] * n
    dist[0] = 0
    count = [0] * n
    count[0] = 1
    pq = [(0, 0)]

    while pq:
        distance, node = heappop(pq)

        if distance > dist[node]:
            continue

        for next_node, edge_distance in adj_list[node]:
            if distance + edge_distance > dist[next_node]:
                continue

            if distance + edge_distance == dist[next_node]:
                count[next_node] = (count[next_node] + count[node]) % MODULO
            else:
                count[next_node] = count[node]
                dist[next_node] = distance + edge_distance
                heappush(pq, (dist[next_node], next_node))

    return count[n - 1]
```
To solve this problem, we first build an adjacency list to represent the city layout graph. We then initialize the distance to each intersection initially to infinity (maximum integer for the specific language), except for the starting point (intersection 0), which is set to 0.

Next, we define an array (or vector in the case of C++) to keep track of the number of ways we can reach each intersection in the shortest time, and we set the initial count for the starting point to 1.

We create a priority queue (min-heap) and insert the starting intersection with a distance of 0. We then check each intersection until the priority queue is empty, following these steps:
1. Pop the intersection with the shortest distance from the priority queue.
2. Check if the current distance is greater than the one stored in the distance array. If so, it means we've already found a better path, and we continue with the next intersection in the queue.
3. Iterate through the neighbors of the current intersection.
   - If the current path's distance plus the distance to the neighboring intersection is greater than the best-known distance to that neighboring intersection, then this path does not offer a shorter route, and we continue to the next neighbor.
   - If the current path's distance plus the distance to the neighboring intersection is equal to the best-known distance to that neighboring intersection, we update the count of ways to reach that neighbor, maintaining the modulo 10^9 + 7 (to avoid large numbers).
   - If the current path's distance plus the distance to the neighboring intersection is less than the best-known distance to that neighboring intersection, we update both the distance and the count arrays and insert the neighboring intersection into the priority queue.

Finally, we return the number of ways to reach the destination (intersection n - 1) in the count array.

## A solution in Javascript

```javascript
const MODULO = 1000000007;

function countPaths(n, roads) {
    const adjList = Array.from({ length: n }, () => []);

    for (const [u, v, time] of roads) {
        adjList[u].push([v, time]);
        adjList[v].push([u, time]);
    }

    const dist = new Array(n).fill(Number.MAX_VALUE);
    dist[0] = 0;
    const count = new Array(n).fill(0);
    count[0] = 1;
    const pq = [[0, 0]];

    while (pq.length > 0) {
        pq.sort((a, b) => a[0] - b[0]);
        const [distance, node] = pq.shift();

        if (distance > dist[node]) continue;

        for (const [nextNode, edgeDistance] of adjList[node]) {
            if (distance + edgeDistance > dist[nextNode]) continue;

            if (distance + edgeDistance === dist[nextNode]) {
                count[nextNode] = (count[nextNode] + count[node]) % MODULO;
            } else {
                count[nextNode] = count[node];
                dist[nextNode] = distance + edgeDistance;
                pq.push([dist[nextNode], nextNode]);
            }
        }
    }

    return count[n - 1];
}
```
To solve this problem, we first build an adjacency list to represent the city layout graph. We then initialize the distance to each intersection initially to infinity (maximum integer for the specific language), except for the starting point (intersection 0), which is set to 0.

Next, we define an array (or vector in the case of C++) to keep track of the number of ways we can reach each intersection in the shortest time, and we set the initial count for the starting point to 1.

We create a priority queue (min-heap) and insert the starting intersection with a distance of 0. We then check each intersection until the priority queue is empty, following these steps:
1. Pop the intersection with the shortest distance from the priority queue.
2. Check if the current distance is greater than the one stored in the distance array. If so, it means we've already found a better path, and we continue with the next intersection in the queue.
3. Iterate through the neighbors of the current intersection.
   - If the current path's distance plus the distance to the neighboring intersection is greater than the best-known distance to that neighboring intersection, then this path does not offer a shorter route, and we continue to the next neighbor.
   - If the current path's distance plus the distance to the neighboring intersection is equal to the best-known distance to that neighboring intersection, we update the count of ways to reach that neighbor, maintaining the modulo 10^9 + 7 (to avoid large numbers).
   - If the current path's distance plus the distance to the neighboring intersection is less than the best-known distance to that neighboring intersection, we update both the distance and the count arrays and insert the neighboring intersection into the priority queue.

Finally, we return the number of ways to reach the destination (intersection n - 1) in the count array.


# Removing Minimum and Maximum From Array

- slug: removing-minimum-and-maximum-from-array
- difficulty: Medium

You are given a **0-indexed** array of **distinct** integers `nums`.

There is an element in `nums` that has the **lowest** value and an element that has the **highest** value. We call them the **minimum** and **maximum** respectively. Your goal is to remove **both** these elements from the array.

A **deletion** is defined as either removing an element from the **front** of the array or removing an element from the **back** of the array.

Return _the **minimum** number of deletions it would take to remove **both** the minimum and maximum element from the array._

**Example 1:**

**Input:** nums = \[2,**10**,7,5,4,**1**,8,6\]
**Output:** 5
**Explanation:**
The minimum element in the array is nums\[5\], which is 1.
The maximum element in the array is nums\[1\], which is 10.
We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.
This results in 2 + 3 = 5 deletions, which is the minimum number possible.

**Example 2:**

**Input:** nums = \[0,**\-4**,**19**,1,8,-2,-3,5\]
**Output:** 3
**Explanation:**
The minimum element in the array is nums\[1\], which is -4.
The maximum element in the array is nums\[2\], which is 19.
We can remove both the minimum and maximum by removing 3 elements from the front.
This results in only 3 deletions, which is the minimum number possible.

**Example 3:**

**Input:** nums = \[**101**\]
**Output:** 1
**Explanation:**
There is only one element in the array, which makes it both the minimum and maximum element.
We can remove it with 1 deletion.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `-105 <= nums[i] <= 105`
*   The integers in `nums` are **distinct**.

## A solution in Java

```java
public int numberOfLists(String num) {
    int mod = 1000000007;
    int n = num.length();
    int[][] dp = new int[n + 1][n + 1];
    dp[0][0] = 1;

    for (int i = 0; i < n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (num.charAt(i) == '0') continue;
            for (int k = 1; i + k <= n; ++k) {
                if (k > 1 && num.charAt(i + k - 1) == '0') break;
                dp[i + k][j] = (dp[i + k][j] + dp[i][j - 1]) % mod;
            }
        }
    }

    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        ans = (ans + dp[n][i]) % mod;
    }
    return ans;
}
```
Given the condition that the integer list was non-decreasing and no integer had leading zeros, the algorithm uses dynamic programming to find the number of possible lists.

Create a dynamic programming table `dp` of dimensions (n+1)x(n+1), where n is the length of the input string `num`. Initialize `dp[0][0]` with 1.

Iterate through the string `num` with two nested loops, one for the length of each possible integer and another for the specific integer itself.

1. If the current character is `0`, skip the iteration since no integer should have leading zeros.
2. For any integer of length k (maximum 10 because of the modulo 10^9+7 condition), calculate and update the corresponding `dp` value, while considering the non-decreasing order condition.
3. If a number with more than one digit starts with `0`, break the inner loop since it violates the leading zeros condition.

Finally, sum up the last rows of the `dp` array to get the total number of possible lists modulo 10^9+7. Return the result as the answer.

## A solution in C++

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

int numberOfLists(string num) {
    const int mod = 1e9 + 7;
    int n = num.size();
    vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
    dp[0][0] = 1;

    for (int i = 0; i < n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (num[i] == '0') continue;
            for (int k = 1; i + k <= n; ++k) {
                if (k > 1 && num[i + k - 1] == '0') break;
                dp[i + k][j] = (dp[i + k][j] + dp[i][j - 1]) % mod;
            }
        }
    }

    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        ans = (ans + dp[n][i]) % mod;
    }
    return ans;
}
```
Given the condition that the integer list was non-decreasing and no integer had leading zeros, the algorithm uses dynamic programming to find the number of possible lists.

Create a dynamic programming table `dp` of dimensions (n+1)x(n+1), where n is the length of the input string `num`. Initialize `dp[0][0]` with 1.

Iterate through the string `num` with two nested loops, one for the length of each possible integer and another for the specific integer itself.

1. If the current character is `0`, skip the iteration since no integer should have leading zeros.
2. For any integer of length k (maximum 10 because of the modulo 10^9+7 condition), calculate and update the corresponding `dp` value, while considering the non-decreasing order condition.
3. If a number with more than one digit starts with `0`, break the inner loop since it violates the leading zeros condition.

Finally, sum up the last rows of the `dp` array to get the total number of possible lists modulo 10^9+7. Return the result as the answer.

## A solution in Python

```python
def numberOfLists(num: str) -> int:
    mod = 10 ** 9 + 7
    n = len(num)
    dp = [[0] * (n + 1) for _ in range(n + 1)]
    dp[0][0] = 1

    for i in range(n):
        for j in range(1, n + 1):
            if num[i] == '0': continue
            for k in range(1, min(n - i + 1, 11)):
                if k > 1 and num[i + k - 1] == '0': break
                dp[i + k][j] = (dp[i + k][j] + dp[i][j - 1]) % mod

    return sum(dp[n]) % mod
```
Given the condition that the integer list was non-decreasing and no integer had leading zeros, the algorithm uses dynamic programming to find the number of possible lists.

Create a dynamic programming table `dp` of dimensions (n+1)x(n+1), where n is the length of the input string `num`. Initialize `dp[0][0]` with 1.

Iterate through the string `num` with two nested loops, one for the length of each possible integer and another for the specific integer itself.

1. If the current character is `0`, skip the iteration since no integer should have leading zeros.
2. For any integer of length k (maximum 10 because of the modulo 10^9+7 condition), calculate and update the corresponding `dp` value, while considering the non-decreasing order condition.
3. If a number with more than one digit starts with `0`, break the inner loop since it violates the leading zeros condition.

Finally, sum up the last rows of the `dp` array to get the total number of possible lists modulo 10^9+7. Return the result as the answer.

## A solution in Javascript

```javascript
function numberOfLists(num) {
    const mod = 1e9 + 7;
    const n = num.length;
    const dp = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0));
    dp[0][0] = 1;

    for (let i = 0; i < n; ++i) {
        for (let j = 1; j <= n; ++j) {
            if (num[i] === '0') continue;
            for (let k = 1; i + k <= n; ++k) {
                if (k > 1 && num[i + k - 1] === '0') break;
                dp[i + k][j] = (dp[i + k][j] + dp[i][j - 1]) % mod;
            }
        }
    }

    let ans = 0;
    for (let i = 1; i <= n; ++i) {
        ans = (ans + dp[n][i]) % mod;
    }
    return ans;
}
```
Given the condition that the integer list was non-decreasing and no integer had leading zeros, the algorithm uses dynamic programming to find the number of possible lists.

Create a dynamic programming table `dp` of dimensions (n+1)x(n+1), where n is the length of the input string `num`. Initialize `dp[0][0]` with 1.

Iterate through the string `num` with two nested loops, one for the length of each possible integer and another for the specific integer itself.

1. If the current character is `0`, skip the iteration since no integer should have leading zeros.
2. For any integer of length k (maximum 10 because of the modulo 10^9+7 condition), calculate and update the corresponding `dp` value, while considering the non-decreasing order condition.
3. If a number with more than one digit starts with `0`, break the inner loop since it violates the leading zeros condition.

Finally, sum up the last rows of the `dp` array to get the total number of possible lists modulo 10^9+7. Return the result as the answer.


# Find All People With Secret

- slug: find-all-people-with-secret
- difficulty: Hard

You are given an integer `n` indicating there are `n` people numbered from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `meetings` where `meetings[i] = [xi, yi, timei]` indicates that person `xi` and person `yi` have a meeting at `timei`. A person may attend **multiple meetings** at the same time. Finally, you are given an integer `firstPerson`.

Person `0` has a **secret** and initially shares the secret with a person `firstPerson` at time `0`. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person `xi` has the secret at `timei`, then they will share the secret with person `yi`, and vice versa.

The secrets are shared **instantaneously**. That is, a person may receive the secret and share it with people in other meetings within the same time frame.

Return _a list of all the people that have the secret after all the meetings have taken place._ You may return the answer in **any order**.

**Example 1:**

**Input:** n = 6, meetings = \[\[1,2,5\],\[2,3,8\],\[1,5,10\]\], firstPerson = 1
**Output:** \[0,1,2,3,5\]
**Explanation:**
At time 0, person 0 shares the secret with person 1.
At time 5, person 1 shares the secret with person 2.
At time 8, person 2 shares the secret with person 3.
At time 10, person 1 shares the secret with person 5.
Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.

**Example 2:**

**Input:** n = 4, meetings = \[\[3,1,3\],\[1,2,2\],\[0,3,3\]\], firstPerson = 3
**Output:** \[0,1,3\]
**Explanation:**
At time 0, person 0 shares the secret with person 3.
At time 2, neither person 1 nor person 2 know the secret.
At time 3, person 3 shares the secret with person 0 and person 1.
Thus, people 0, 1, and 3 know the secret after all the meetings.

**Example 3:**

**Input:** n = 5, meetings = \[\[3,4,2\],\[1,2,1\],\[2,3,1\]\], firstPerson = 1
**Output:** \[0,1,2,3,4\]
**Explanation:**
At time 0, person 0 shares the secret with person 1.
At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.
Note that person 2 can share the secret at the same time as receiving it.
At time 2, person 3 shares the secret with person 4.
Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.

**Constraints:**

*   `2 <= n <= 105`
*   `1 <= meetings.length <= 105`
*   `meetings[i].length == 3`
*   `0 <= xi, yi <= n - 1`
*   `xi != yi`
*   `1 <= timei <= 105`
*   `1 <= firstPerson <= n - 1`

## A solution in Java

```java
import java.util.*;

public List<Integer> findSecretSharers(int n, int[][] meetings, int firstPerson) {
    int[] secret_holders = new int[n];
    Arrays.fill(secret_holders, -1);
    secret_holders[0] = 0;
    secret_holders[firstPerson] = 0;

    Arrays.sort(meetings, (a, b) -> Integer.compare(a[2], b[2]));

    for (int[] meeting : meetings) {
        int x = meeting[0];
        int y = meeting[1];
        int time = meeting[2];

        if (secret_holders[x] != -1 && secret_holders[x] <= time) secret_holders[y] = time;
        if (secret_holders[y] != -1 && secret_holders[y] <= time) secret_holders[x] = time;
    }

    List<Integer> result = new ArrayList<>();
    for (int i = 0; i < n; ++i) {
        if (secret_holders[i] != -1) result.add(i);
    }

    return result;
}
```
The algorithm initializes an array `n` long with -1s called `secret_holders`, and only setting person `0` and the `firstPerson` to 0, representing that they initially have the secret. The meetings are then sorted by time. The algorithm then iterates over the meetings, and if either person `x` or `y` has the secret and the secret was obtained before the meeting time, then the secret is shared with the other person within this meeting. After all meetings, the algorithm returns the indices of `secret_holders` with values that are not -1, representing the people who have the secret.

## A solution in C++

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

vector<int> findSecretSharers(int n, vector<vector<int>>& meetings, int firstPerson) {
    vector<int> secret_holders(n, -1);
    secret_holders[0] = 0;
    secret_holders[firstPerson] = 0;

    sort(meetings.begin(), meetings.end(), [](const vector<int>& a, const vector<int>& b) { return a[2] < b[2]; });

    for (auto& meeting : meetings) {
        int x = meeting[0];
        int y = meeting[1];
        int time = meeting[2];

        if (secret_holders[x] != -1 && secret_holders[x] <= time) secret_holders[y] = time;
        if (secret_holders[y] != -1 && secret_holders[y] <= time) secret_holders[x] = time;
    }

    vector<int> result;
    for (int i = 0; i < n; ++i) {
        if (secret_holders[i] != -1) result.push_back(i);
    }

    return result;
}
```
The algorithm initializes an array `n` long with -1s called `secret_holders`, and only setting person `0` and the `firstPerson` to 0, representing that they initially have the secret. The meetings are then sorted by time. The algorithm then iterates over the meetings, and if either person `x` or `y` has the secret and the secret was obtained before the meeting time, then the secret is shared with the other person within this meeting. After all meetings, the algorithm returns the indices of `secret_holders` with values that are not -1, representing the people who have the secret.

## A solution in Python

```python
def find_secret_sharers(n, meetings, first_person):
    secret_holders = [-1] * n
    secret_holders[0] = 0
    secret_holders[first_person] = 0

    meetings.sort(key=lambda x: x[2])

    for x, y, time in meetings:
        if secret_holders[x] != -1 and secret_holders[x] <= time:
            secret_holders[y] = time
        if secret_holders[y] != -1 and secret_holders[y] <= time:
            secret_holders[x] = time

    return [i for i in range(n) if secret_holders[i] != -1]
```
The algorithm initializes an array `n` long with -1s called `secret_holders`, and only setting person `0` and the `firstPerson` to 0, representing that they initially have the secret. The meetings are then sorted by time. The algorithm then iterates over the meetings, and if either person `x` or `y` has the secret and the secret was obtained before the meeting time, then the secret is shared with the other person within this meeting. After all meetings, the algorithm returns the indices of `secret_holders` with values that are not -1, representing the people who have the secret.

## A solution in Javascript

```javascript
function findSecretSharers(n, meetings, firstPerson) {
    let secret_holders = Array(n).fill(-1);
    secret_holders[0] = 0;
    secret_holders[firstPerson] = 0;

    meetings.sort((a, b) => a[2] - b[2]);

    for (let [x, y, time] of meetings) {
        if (secret_holders[x] !== -1 && secret_holders[x] <= time) secret_holders[y] = time;
        if (secret_holders[y] !== -1 && secret_holders[y] <= time) secret_holders[x] = time;
    }

    return secret_holders.reduce((result, has_secret, i) => {
        if (has_secret !== -1) result.push(i);
        return result;
    }, []);
}
```
The algorithm initializes an array `n` long with -1s called `secret_holders`, and only setting person `0` and the `firstPerson` to 0, representing that they initially have the secret. The meetings are then sorted by time. The algorithm then iterates over the meetings, and if either person `x` or `y` has the secret and the secret was obtained before the meeting time, then the secret is shared with the other person within this meeting. After all meetings, the algorithm returns the indices of `secret_holders` with values that are not -1, representing the people who have the secret.


# Minimum Cost to Reach City With Discounts

- slug: minimum-cost-to-reach-city-with-discounts
- difficulty: Medium

A series of highways connect `n` cities numbered from `0` to `n - 1`. You are given a 2D integer array `highways` where `highways[i] = [city1i, city2i, tolli]` indicates that there is a highway that connects `city1i` and `city2i`, allowing a car to go from `city1i` to `city2i` **and vice versa** for a cost of `tolli`.

You are also given an integer `discounts` which represents the number of discounts you have. You can use a discount to travel across the `ith` highway for a cost of `tolli / 2` (**integer** **division**). Each discount may only be used **once**, and you can only use at most **one** discount per highway.

Return _the **minimum total cost** to go from city_ `0` _to city_ `n - 1`_, or_ `-1` _if it is not possible to go from city_ `0` _to city_ `n - 1`_._

**Example 1:**

**Input:** n = 5, highways = \[\[0,1,4\],\[2,1,3\],\[1,4,11\],\[3,2,3\],\[3,4,2\]\], discounts = 1
**Output:** 9
**Explanation:**
Go from 0 to 1 for a cost of 4.
Go from 1 to 4 and use a discount for a cost of 11 / 2 = 5.
The minimum cost to go from 0 to 4 is 4 + 5 = 9.

**Example 2:**

**Input:** n = 4, highways = \[\[1,3,17\],\[1,2,7\],\[3,2,5\],\[0,1,6\],\[3,0,20\]\], discounts = 20
**Output:** 8
**Explanation:**
Go from 0 to 1 and use a discount for a cost of 6 / 2 = 3.
Go from 1 to 2 and use a discount for a cost of 7 / 2 = 3.
Go from 2 to 3 and use a discount for a cost of 5 / 2 = 2.
The minimum cost to go from 0 to 3 is 3 + 3 + 2 = 8.

**Example 3:**

**Input:** n = 4, highways = \[\[0,1,3\],\[2,3,2\]\], discounts = 0
**Output:** -1
**Explanation:**
It is impossible to go from 0 to 3 so return -1.

**Constraints:**

*   `2 <= n <= 1000`
*   `1 <= highways.length <= 1000`
*   `highways[i].length == 3`
*   `0 <= city1i, city2i <= n - 1`
*   `city1i != city2i`
*   `0 <= tolli <= 105`
*   `0 <= discounts <= 500`
*   There are no duplicate highways.

## A solution in Java

```java
public boolean isPrefixString(String s, String[] words) {
    StringBuilder sb = new StringBuilder();
    for (String word : words) {
        sb.append(word);
        if (sb.toString().equals(s)) return true;
        if (sb.length() > s.length()) break;
    }
    return false;
}
```
The algorithm does the following to determine if the given string s is a prefix string of words:

1. Create an empty temporary string (temp).
2. Iterate through each word in the words array:
   a. Concatenate the word to the temporary string.
   b. Check if the temporary string is equal to the given string s. If it is, return true.
   c. If the length of the temporary string is greater than the length of the given string s, break the loop.
3. If the loop completes without returning true, return false. This means that the given string s is not a prefix string of words.

This algorithm has a time complexity of O(n * m) where n is the number of words and m is the length of the longest word in words.

## A solution in C++

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

bool isPrefixString(std::string s, std::vector<std::string>& words) {
    std::string temp = "";
    for (std::string word : words) {
        temp += word;
        if (temp == s) return true;
        if (temp.size() > s.size()) break;
    }
    return false;
}
```
The algorithm does the following to determine if the given string s is a prefix string of words:

1. Create an empty temporary string (temp).
2. Iterate through each word in the words array:
   a. Concatenate the word to the temporary string.
   b. Check if the temporary string is equal to the given string s. If it is, return true.
   c. If the length of the temporary string is greater than the length of the given string s, break the loop.
3. If the loop completes without returning true, return false. This means that the given string s is not a prefix string of words.

This algorithm has a time complexity of O(n * m) where n is the number of words and m is the length of the longest word in words.

## A solution in Python

```python
def is_prefix_string(s, words):
    temp = ""
    for word in words:
        temp += word
        if temp == s:
            return True
        if len(temp) > len(s):
            break
    return False
```
The algorithm does the following to determine if the given string s is a prefix string of words:

1. Create an empty temporary string (temp).
2. Iterate through each word in the words array:
   a. Concatenate the word to the temporary string.
   b. Check if the temporary string is equal to the given string s. If it is, return true.
   c. If the length of the temporary string is greater than the length of the given string s, break the loop.
3. If the loop completes without returning true, return false. This means that the given string s is not a prefix string of words.

This algorithm has a time complexity of O(n * m) where n is the number of words and m is the length of the longest word in words.

## A solution in Javascript

```javascript
function isPrefixString(s, words) {
    let temp = "";
    for (const word of words) {
        temp += word;
        if (temp === s) return true;
        if (temp.length > s.length) break;
    }
    return false;
}
```
The algorithm does the following to determine if the given string s is a prefix string of words:

1. Create an empty temporary string (temp).
2. Iterate through each word in the words array:
   a. Concatenate the word to the temporary string.
   b. Check if the temporary string is equal to the given string s. If it is, return true.
   c. If the length of the temporary string is greater than the length of the given string s, break the loop.
3. If the loop completes without returning true, return false. This means that the given string s is not a prefix string of words.

This algorithm has a time complexity of O(n * m) where n is the number of words and m is the length of the longest word in words.


# Finding 3-Digit Even Numbers

- slug: finding-3-digit-even-numbers
- difficulty: Easy

You are given an integer array `digits`, where each element is a digit. The array may contain duplicates.

You need to find **all** the **unique** integers that follow the given requirements:

*   The integer consists of the **concatenation** of **three** elements from `digits` in **any** arbitrary order.
*   The integer does not have **leading zeros**.
*   The integer is **even**.

For example, if the given `digits` were `[1, 2, 3]`, integers `132` and `312` follow the requirements.

Return _a **sorted** array of the unique integers._

**Example 1:**

**Input:** digits = \[2,1,3,0\]
**Output:** \[102,120,130,132,210,230,302,310,312,320\]
**Explanation:** All the possible integers that follow the requirements are in the output array.
Notice that there are no **odd** integers or integers with **leading zeros**.

**Example 2:**

**Input:** digits = \[2,2,8,8,2\]
**Output:** \[222,228,282,288,822,828,882\]
**Explanation:** The same digit can be used as many times as it appears in digits.
In this example, the digit 8 is used twice each time in 288, 828, and 882.

**Example 3:**

**Input:** digits = \[3,7,5\]
**Output:** \[\]
**Explanation:** No **even** integers can be formed using the given digits.

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int minStonesRemaining(int[] piles, int k) {
    for (int i = 0; i < k; i++) {
        int max_pile_index = 0;
        for (int j = 1; j < piles.length; j++) {
            if (piles[j] > piles[max_pile_index]) {
                max_pile_index = j;
            }
        }
        piles[max_pile_index] -= piles[max_pile_index] / 2;
    }

    int total_stones = 0;
    for (int pile : piles) {
        total_stones += pile;
    }
    return total_stones;
}
```
The algorithm follows these steps:
1. Iterate `k` times.
2. For each iteration, find the index of the largest pile.
3. Reduce the largest pile by half, rounding down, and update the value in the piles array.
4. After all iterations, compute the sum of the remaining piles and return it.

## A solution in C++

```cpp
#include <algorithm>

int minStonesRemaining(int piles[], int n, int k) {
    for (int i = 0; i < k; i++) {
        int max_pile_index = std::distance(piles, std::max_element(piles, piles + n));
        piles[max_pile_index] = piles[max_pile_index] - (piles[max_pile_index] / 2);
    }

    int total_stones = 0;
    for (int i = 0; i < n; i++) {
        total_stones += piles[i];
    }
    return total_stones;
}
```
The algorithm follows these steps:
1. Iterate `k` times.
2. For each iteration, find the index of the largest pile.
3. Reduce the largest pile by half, rounding down, and update the value in the piles array.
4. After all iterations, compute the sum of the remaining piles and return it.

## A solution in Python

```python
def min_stones_remaining(piles, k):
    for _ in range(k):
        max_pile_index = piles.index(max(piles))
        piles[max_pile_index] -= piles[max_pile_index] // 2

    return sum(piles)
```
The algorithm follows these steps:
1. Iterate `k` times.
2. For each iteration, find the index of the largest pile.
3. Reduce the largest pile by half, rounding down, and update the value in the piles array.
4. After all iterations, compute the sum of the remaining piles and return it.

## A solution in Javascript

```javascript
function minStonesRemaining(piles, k) {
    for (let i = 0; i < k; i++) {
        let max_pile_index = 0;
        for (let j = 1; j < piles.length; j++) {
            if (piles[j] > piles[max_pile_index]) {
                max_pile_index = j;
            }
        }
        piles[max_pile_index] -= Math.floor(piles[max_pile_index] / 2);
    }

    return piles.reduce((total, pile) => total + pile, 0);
}
```
The algorithm follows these steps:
1. Iterate `k` times.
2. For each iteration, find the index of the largest pile.
3. Reduce the largest pile by half, rounding down, and update the value in the piles array.
4. After all iterations, compute the sum of the remaining piles and return it.


# Delete the Middle Node of a Linked List

- slug: delete-the-middle-node-of-a-linked-list
- difficulty: Medium

You are given the `head` of a linked list. **Delete** the **middle node**, and return _the_ `head` _of the modified linked list_.

The **middle node** of a linked list of size `n` is the `⌊n / 2⌋th` node from the **start** using **0-based indexing**, where `⌊x⌋` denotes the largest integer less than or equal to `x`.

*   For `n` = `1`, `2`, `3`, `4`, and `5`, the middle nodes are `0`, `1`, `1`, `2`, and `2`, respectively.

**Example 1:**

**Input:** head = \[1,3,4,7,1,2,6\]
**Output:** \[1,3,4,1,2,6\]
**Explanation:**
The above figure represents the given linked list. The indices of the nodes are written below.
Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
We return the new list after removing this node.

**Example 2:**

**Input:** head = \[1,2,3,4\]
**Output:** \[1,2,4\]
**Explanation:**
The above figure represents the given linked list.
For n = 4, node 2 with value 3 is the middle node, which is marked in red.

**Example 3:**

**Input:** head = \[2,1\]
**Output:** \[2\]
**Explanation:**
The above figure represents the given linked list.
For n = 2, node 1 with value 1 is the middle node, which is marked in red.
Node 0 with value 2 is the only node remaining after removing node 1.

**Constraints:**

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

## A solution in Java

```java
public int minSwaps(String s) {
    int openBrackets = 0;
    int swaps = 0;

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);

        if (c == '[') {
            openBrackets++;
        } else {
            if (openBrackets == 0) {
                swaps++;
                openBrackets++;
            } else {
                openBrackets--;
            }
        }
    }

    return swaps;
}
```
The algorithm keeps track of the number of opening brackets '[' encountered while traversing the string. If a closing bracket ']' is encountered and there are no opening brackets available, a swap is required. Thus, the swap count is incremented and ']' is treated as an opening bracket. If there are opening brackets available, a closing bracket ']' can be paired with an opening one so we simply decrement the opening bracket count. At the end, the swap count denotes the minimum number of swaps required to balance the string.

## A solution in C++

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

int min_swaps_to_balance(string s) {
    int open_brackets = 0;
    int swaps = 0;

    for (char c : s) {
        if (c == '[') {
            open_brackets++;
        } else {
            if (open_brackets == 0) {
                swaps++;
                open_brackets++;
            } else {
                open_brackets--;
            }
        }
    }

    return swaps;
}
```
The algorithm keeps track of the number of opening brackets '[' encountered while traversing the string. If a closing bracket ']' is encountered and there are no opening brackets available, a swap is required. Thus, the swap count is incremented and ']' is treated as an opening bracket. If there are opening brackets available, a closing bracket ']' can be paired with an opening one so we simply decrement the opening bracket count. At the end, the swap count denotes the minimum number of swaps required to balance the string.

## A solution in Python

```python
def min_swaps_to_balance(s: str) -> int:
    open_brackets = 0
    swaps = 0

    for c in s:
        if c == '[':
            open_brackets += 1
        else:
            if open_brackets == 0:
                swaps += 1
                open_brackets += 1
            else:
                open_brackets -= 1

    return swaps
```
The algorithm keeps track of the number of opening brackets '[' encountered while traversing the string. If a closing bracket ']' is encountered and there are no opening brackets available, a swap is required. Thus, the swap count is incremented and ']' is treated as an opening bracket. If there are opening brackets available, a closing bracket ']' can be paired with an opening one so we simply decrement the opening bracket count. At the end, the swap count denotes the minimum number of swaps required to balance the string.

## A solution in Javascript

```javascript
function minSwaps(s) {
    let openBrackets = 0;
    let swaps = 0;

    for (let i = 0; i < s.length; i++) {
        const c = s[i];

        if (c === '[') {
            openBrackets++;
        } else {
            if (openBrackets === 0) {
                swaps++;
                openBrackets++;
            } else {
                openBrackets--;
            }
        }
    }

    return swaps;
}
```
The algorithm keeps track of the number of opening brackets '[' encountered while traversing the string. If a closing bracket ']' is encountered and there are no opening brackets available, a swap is required. Thus, the swap count is incremented and ']' is treated as an opening bracket. If there are opening brackets available, a closing bracket ']' can be paired with an opening one so we simply decrement the opening bracket count. At the end, the swap count denotes the minimum number of swaps required to balance the string.


# Step-By-Step Directions From a Binary Tree Node to Another

- slug: step-by-step-directions-from-a-binary-tree-node-to-another
- difficulty: Medium

You are given the `root` of a **binary tree** with `n` nodes. Each node is uniquely assigned a value from `1` to `n`. You are also given an integer `startValue` representing the value of the start node `s`, and a different integer `destValue` representing the value of the destination node `t`.

Find the **shortest path** starting from node `s` and ending at node `t`. Generate step-by-step directions of such path as a string consisting of only the **uppercase** letters `'L'`, `'R'`, and `'U'`. Each letter indicates a specific direction:

*   `'L'` means to go from a node to its **left child** node.
*   `'R'` means to go from a node to its **right child** node.
*   `'U'` means to go from a node to its **parent** node.

Return _the step-by-step directions of the **shortest path** from node_ `s` _to node_ `t`.

**Example 1:**

**Input:** root = \[5,1,2,3,null,6,4\], startValue = 3, destValue = 6
**Output:**  "UURL "
**Explanation:** The shortest path is: 3 -> 1 -> 5 -> 2 -> 6.

**Example 2:**

**Input:** root = \[2,1\], startValue = 2, destValue = 1
**Output:**  "L "
**Explanation:** The shortest path is: 2 -> 1.

**Constraints:**

*   The number of nodes in the tree is `n`.
*   `2 <= n <= 105`
*   `1 <= Node.val <= n`
*   All the values in the tree are **unique**.
*   `1 <= startValue, destValue <= n`
*   `startValue != destValue`

## A solution in Java

```java
import java.util.Arrays;

public int[] longestObstacleCourse(int[] obstacles) {
    int[] ans = new int[obstacles.length], active = new int[obstacles.length];
    int activeLen = 0;
    for (int i = 0; i < obstacles.length; i++) {
        int idx = Arrays.binarySearch(active, 0, activeLen, obstacles[i] + 1);
        idx = idx < 0 ? -idx - 1 : idx;
        ans[i] = idx + 1;
        if (idx == activeLen) {
            active[activeLen++] = obstacles[i];
        } else {
            active[idx] = obstacles[i];
        }
    }
    return ans;
}
```
The algorithm uses a dynamic programming approach to calculate the longest obstacle course. It keeps track of the active obstacle heights.

1. Iterate through the input array from 0 to n-1.
2. For each obstacle, find its position (idx) in the active sequence using binary search.
3. Update the length of the longest obstacle course for the index i as (idx + 1).
4. If the idx is equal to the length of the active sequence, push the obstacle height to the active sequence, else update the active sequence at position idx with the current obstacle height.

This approach makes it possible to find the longest obstacle course in O(n log n) complexity.

## A solution in C++

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

std::vector<int> longest_obstacle_course(std::vector<int>& obstacles) {
    std::vector<int> ans(obstacles.size()), active;
    for (int i = 0; i < obstacles.size(); ++i) {
        auto it = std::upper_bound(active.begin(), active.end(), obstacles[i]);
        ans[i] = (it - active.begin()) + 1;
        if (it == active.end()) {
            active.push_back(obstacles[i]);
        } else {
            *it = obstacles[i];
        }
    }
    return ans;
}
```
The algorithm uses a dynamic programming approach to calculate the longest obstacle course. It keeps track of the active obstacle heights.

1. Iterate through the input array from 0 to n-1.
2. For each obstacle, find its position (idx) in the active sequence using binary search.
3. Update the length of the longest obstacle course for the index i as (idx + 1).
4. If the idx is equal to the length of the active sequence, push the obstacle height to the active sequence, else update the active sequence at position idx with the current obstacle height.

This approach makes it possible to find the longest obstacle course in O(n log n) complexity.

## A solution in Python

```python
from bisect import bisect_right

def longest_obstacle_course(obstacles):
    ans, active = [0] * len(obstacles), []
    for i, obstacle in enumerate(obstacles):
        idx = bisect_right(active, obstacle)
        ans[i] = idx + 1
        if idx == len(active):
            active.append(obstacle)
        else:
            active[idx] = obstacle
    return ans
```
The algorithm uses a dynamic programming approach to calculate the longest obstacle course. It keeps track of the active obstacle heights.

1. Iterate through the input array from 0 to n-1.
2. For each obstacle, find its position (idx) in the active sequence using binary search.
3. Update the length of the longest obstacle course for the index i as (idx + 1).
4. If the idx is equal to the length of the active sequence, push the obstacle height to the active sequence, else update the active sequence at position idx with the current obstacle height.

This approach makes it possible to find the longest obstacle course in O(n log n) complexity.

## A solution in Javascript

```javascript
function longestObstacleCourse(obstacles) {
    const ans = new Array(obstacles.length), active = [];
    for (let i = 0; i < obstacles.length; i++) {
        const idx = upperBound(active, obstacles[i]);
        ans[i] = idx + 1;
        if (idx === active.length) {
            active.push(obstacles[i]);
        } else {
            active[idx] = obstacles[i];
        }
    }
    return ans;
}

function upperBound(arr, x) {
    let l = 0, r = arr.length;
    while (l < r) {
        const m = l + Math.floor((r - l) / 2);
        if (arr[m] <= x) {
            l = m + 1;
        } else {
            r = m;
        }
    }
    return l;
}
```
The algorithm uses a dynamic programming approach to calculate the longest obstacle course. It keeps track of the active obstacle heights.

1. Iterate through the input array from 0 to n-1.
2. For each obstacle, find its position (idx) in the active sequence using binary search.
3. Update the length of the longest obstacle course for the index i as (idx + 1).
4. If the idx is equal to the length of the active sequence, push the obstacle height to the active sequence, else update the active sequence at position idx with the current obstacle height.

This approach makes it possible to find the longest obstacle course in O(n log n) complexity.


# Valid Arrangement of Pairs

- slug: valid-arrangement-of-pairs
- difficulty: Hard

You are given a **0-indexed** 2D integer array `pairs` where `pairs[i] = [starti, endi]`. An arrangement of `pairs` is **valid** if for every index `i` where `1 <= i < pairs.length`, we have `endi-1 == starti`.

Return _**any** valid arrangement of_ `pairs`.

**Note:** The inputs will be generated such that there exists a valid arrangement of `pairs`.

**Example 1:**

**Input:** pairs = \[\[5,1\],\[4,5\],\[11,9\],\[9,4\]\]
**Output:** \[\[11,9\],\[9,4\],\[4,5\],\[5,1\]\]
**Explanation:**
This is a valid arrangement since endi-1 always equals starti.
end0 = 9 == 9 = start1
end1 = 4 == 4 = start2
end2 = 5 == 5 = start3

**Example 2:**

**Input:** pairs = \[\[1,3\],\[3,2\],\[2,1\]\]
**Output:** \[\[1,3\],\[3,2\],\[2,1\]\]
**Explanation:**
This is a valid arrangement since endi-1 always equals starti.
end0 = 3 == 3 = start1
end1 = 2 == 2 = start2
The arrangements \[\[2,1\],\[1,3\],\[3,2\]\] and \[\[3,2\],\[2,1\],\[1,3\]\] are also valid.

**Example 3:**

**Input:** pairs = \[\[1,2\],\[1,3\],\[2,1\]\]
**Output:** \[\[1,2\],\[2,1\],\[1,3\]\]
**Explanation:**
This is a valid arrangement since endi-1 always equals starti.
end0 = 2 == 2 = start1
end1 = 1 == 1 = start2

**Constraints:**

*   `1 <= pairs.length <= 105`
*   `pairs[i].length == 2`
*   `0 <= starti, endi <= 109`
*   `starti != endi`
*   No two pairs are exactly the same.
*   There **exists** a valid arrangement of `pairs`.

## A solution in Java

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

public List<List<Integer>> validArrangement(List<List<Integer>> pairs) {
    Map<Integer, List<Integer>> graph = new HashMap<>();
    for (List<Integer> pair : pairs) {
        graph.putIfAbsent(pair.get(0), new ArrayList<>());
        graph.get(pair.get(0)).add(pair.get(1));
    }
    List<List<Integer>> result = new ArrayList<>();
    int current = pairs.get(0).get(0);
    while (!graph.isEmpty()) {
        List<Integer> temp = new ArrayList<>();
        temp.add(current);
        temp.add(graph.get(current).remove(graph.get(current).size()-1));
        if (graph.get(current).isEmpty()) graph.remove(current);
        result.add(temp);
        current = temp.get(1);
    }
    return result;
}
```
We can turn this problem into a directed graph where nodes are the start and end of each pair, and an edge indicates the connection between the two nodes. All we need to do is create a path that covers all the nodes in the graph without visiting any node twice.

1. Create a graph using the 'pairs' array.
2. Initialize a variable 'current' with the first 'start' of pairs array.
3. Create an empty 'result' array.
4. While the graph is not empty, follow below steps:
   1. Create a pair [current, graph[current].pop()].
   2. If graph[current] becomes empty after popping, remove it from the graph.
   3. Append the created pair to the result.
   4. Update the current with the end of the current pair.
5. Return the 'result' array.

This algorithm will return a valid arrangement of the 'pairs' array.

## A solution in C++

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

vector<vector<int>> validArrangement(vector<vector<int>>& pairs) {
    unordered_map<int, vector<int>> graph;
    for (const auto &pair : pairs) {
        graph[pair[0]].push_back(pair[1]);
    }
    vector<vector<int>> result;
    int current = pairs[0][0];
    while (graph.size()) {
        result.push_back({current, graph[current].back()});
        graph[current].pop_back();
        if (graph[current].empty()) graph.erase(current);
        current = result.back()[1];
    }
    return result;
}
```
We can turn this problem into a directed graph where nodes are the start and end of each pair, and an edge indicates the connection between the two nodes. All we need to do is create a path that covers all the nodes in the graph without visiting any node twice.

1. Create a graph using the 'pairs' array.
2. Initialize a variable 'current' with the first 'start' of pairs array.
3. Create an empty 'result' array.
4. While the graph is not empty, follow below steps:
   1. Create a pair [current, graph[current].pop()].
   2. If graph[current] becomes empty after popping, remove it from the graph.
   3. Append the created pair to the result.
   4. Update the current with the end of the current pair.
5. Return the 'result' array.

This algorithm will return a valid arrangement of the 'pairs' array.

## A solution in Python

```python
def valid_arrangement(pairs):
    graph = {}
    for start, end in pairs:
        if start not in graph:
            graph[start] = []
        graph[start].append(end)

    result = []
    current = pairs[0][0]

    while graph:
        pair = [current, graph[current].pop()]
        if not graph[current]:
            del graph[current]
        result.append(pair)
        current = pair[1]

    return result
```
We can turn this problem into a directed graph where nodes are the start and end of each pair, and an edge indicates the connection between the two nodes. All we need to do is create a path that covers all the nodes in the graph without visiting any node twice.

1. Create a graph using the 'pairs' array.
2. Initialize a variable 'current' with the first 'start' of pairs array.
3. Create an empty 'result' array.
4. While the graph is not empty, follow below steps:
   1. Create a pair [current, graph[current].pop()].
   2. If graph[current] becomes empty after popping, remove it from the graph.
   3. Append the created pair to the result.
   4. Update the current with the end of the current pair.
5. Return the 'result' array.

This algorithm will return a valid arrangement of the 'pairs' array.

## A solution in Javascript

```javascript
function validArrangement(pairs) {
    let graph = new Map();
    for (let pair of pairs) {
        if (!graph.has(pair[0])) {
            graph.set(pair[0], []);
        }
        graph.get(pair[0]).push(pair[1]);
    }
    let result = [];
    let current = pairs[0][0];
    while (graph.size) {
        let pair = [current, graph.get(current).pop()];
        if (graph.get(current).length === 0) {
            graph.delete(current);
        }
        result.push(pair);
        current = pair[1];
    }
    return result;
}
```
We can turn this problem into a directed graph where nodes are the start and end of each pair, and an edge indicates the connection between the two nodes. All we need to do is create a path that covers all the nodes in the graph without visiting any node twice.

1. Create a graph using the 'pairs' array.
2. Initialize a variable 'current' with the first 'start' of pairs array.
3. Create an empty 'result' array.
4. While the graph is not empty, follow below steps:
   1. Create a pair [current, graph[current].pop()].
   2. If graph[current] becomes empty after popping, remove it from the graph.
   3. Append the created pair to the result.
   4. Update the current with the end of the current pair.
5. Return the 'result' array.

This algorithm will return a valid arrangement of the 'pairs' array.


# Subsequence of Size K With the Largest Even Sum

- slug: subsequence-of-size-k-with-the-largest-even-sum
- difficulty: Medium

You are given an integer array `nums` and an integer `k`. Find the **largest even sum** of any subsequence of `nums` that has a length of `k`.

Return _this sum, or_ `-1` _if such a sum does not exist_.

A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

**Example 1:**

**Input:** nums = \[4,1,5,3,1\], k = 3
**Output:** 12
**Explanation:**
The subsequence with the largest possible even sum is \[4,5,3\]. It has a sum of 4 + 5 + 3 = 12.

**Example 2:**

**Input:** nums = \[4,6,2\], k = 3
**Output:** 12
**Explanation:**
The subsequence with the largest possible even sum is \[4,6,2\]. It has a sum of 4 + 6 + 2 = 12.

**Example 3:**

**Input:** nums = \[1,3,5\], k = 1
**Output:** -1
**Explanation:**
No subsequence of nums with length 1 has an even sum.

**Constraints:**

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

## A solution in Java

```java
public int largestEvenSum(int[] nums, int k) {
    List<Integer> evens = new ArrayList<>();
    List<Integer> odds = new ArrayList<>();
    for (int num : nums) {
        if (num % 2 == 0) {
            evens.add(num);
        } else {
            odds.add(num);
        }
    }
    evens.sort(Collections.reverseOrder());
    odds.sort(Collections.reverseOrder());

    int sum = 0;
    for (int i = 0; i < k && !evens.isEmpty(); i++) {
        sum += evens.remove(evens.size() - 1);
    }

    for (int i = 0; i < k - 1 && !odds.isEmpty(); i += 2) {
        int first = odds.remove(odds.size() - 1);
        if (!odds.isEmpty()) {
            int second = odds.remove(odds.size() - 1);
            sum += first + second;
        }
    }

    if (sum % 2 == 0) {
        return sum;
    } else {
        return -1;
    }
}
```
The algorithm first splits the input numbers into two separate arrays, one for even numbers and one for odd numbers, and then sorts both arrays in decreasing order.

We take all even numbers until we reach the specified length `k`.

Then, we take pairs of odd numbers from the sorted odd numbers array and add their sums to the total sum. We take pairs of odd numbers because the sum of two odd numbers is always even.

Finally, we check if the sum is even, and if so, we return the sum. If not, we return -1 since no such sum exists for the given constraint.

## A solution in C++

```cpp
int largestEvenSum(const std::vector<int>& nums, int k) {
    std::vector<int> evens, odds;
    for (auto num : nums) {
        if (num % 2 == 0) {
            evens.push_back(num);
        } else {
            odds.push_back(num);
        }
    }
    sort(evens.rbegin(), evens.rend());
    sort(odds.rbegin(), odds.rend());

    int sum = 0;
    for (int i = 0; i < k && !evens.empty(); i++) {
        sum += evens.back();
        evens.pop_back();
    }

    for (int i = 0; i < k - 1 && !odds.empty(); i += 2) {
        int first = odds.back();
        odds.pop_back();
        if (!odds.empty()) {
            int second = odds.back();
            odds.pop_back();
            sum += first + second;
        }
    }

    if (sum % 2 == 0) {
        return sum;
    } else {
        return -1;
    }
}
```
The algorithm first splits the input numbers into two separate arrays, one for even numbers and one for odd numbers, and then sorts both arrays in decreasing order.

We take all even numbers until we reach the specified length `k`.

Then, we take pairs of odd numbers from the sorted odd numbers array and add their sums to the total sum. We take pairs of odd numbers because the sum of two odd numbers is always even.

Finally, we check if the sum is even, and if so, we return the sum. If not, we return -1 since no such sum exists for the given constraint.

## A solution in Python

```python
def largest_even_sum(nums, k):
    evens = sorted([num for num in nums if num % 2 == 0], reverse=True)
    odds = sorted([num for num in nums if num % 2 != 0], reverse=True)

    sum = 0
    for _ in range(k):
        if evens:
            sum += evens.pop()

    for _ in range(0, k - 1, 2):
        if odds:
            first = odds.pop()
            if odds:
                second = odds.pop()
                sum += first + second

    return sum if sum % 2 == 0 else -1
```
The algorithm first splits the input numbers into two separate arrays, one for even numbers and one for odd numbers, and then sorts both arrays in decreasing order.

We take all even numbers until we reach the specified length `k`.

Then, we take pairs of odd numbers from the sorted odd numbers array and add their sums to the total sum. We take pairs of odd numbers because the sum of two odd numbers is always even.

Finally, we check if the sum is even, and if so, we return the sum. If not, we return -1 since no such sum exists for the given constraint.

## A solution in Javascript

```javascript
function largestEvenSum(nums, k) {
  const evens = nums.filter(num => num % 2 === 0).sort((a, b) => b - a);
  const odds = nums.filter(num => num % 2 !== 0).sort((a, b) => b - a);

  let sum = 0;
  for (let i = 0; i < k && evens.length > 0; i++) {
    sum += evens.pop();
  }

  for (let i = 0; i < k - 1 && odds.length > 0; i += 2) {
    let first = odds.pop();
    if (odds.length > 0) {
      let second = odds.pop();
      sum += first + second;
    }
  }

  return sum % 2 === 0 ? sum : -1;
}
```
The algorithm first splits the input numbers into two separate arrays, one for even numbers and one for odd numbers, and then sorts both arrays in decreasing order.

We take all even numbers until we reach the specified length `k`.

Then, we take pairs of odd numbers from the sorted odd numbers array and add their sums to the total sum. We take pairs of odd numbers because the sum of two odd numbers is always even.

Finally, we check if the sum is even, and if so, we return the sum. If not, we return -1 since no such sum exists for the given constraint.


# Find Subsequence of Length K With the Largest Sum

- slug: find-subsequence-of-length-k-with-the-largest-sum
- difficulty: Easy

You are given an integer array `nums` and an integer `k`. You want to find a **subsequence** of `nums` of length `k` that has the **largest** sum.

Return _**any** such subsequence as an integer array of length_ `k`.

A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

**Example 1:**

**Input:** nums = \[2,1,3,3\], k = 2
**Output:** \[3,3\]
**Explanation:**
The subsequence has the largest sum of 3 + 3 = 6.

**Example 2:**

**Input:** nums = \[-1,-2,3,4\], k = 3
**Output:** \[-1,3,4\]
**Explanation:**
The subsequence has the largest sum of -1 + 3 + 4 = 6.

**Example 3:**

**Input:** nums = \[3,4,3,3\], k = 2
**Output:** \[3,4\]
**Explanation:**
The subsequence has the largest sum of 3 + 4 = 7.
Another possible subsequence is \[4, 3\].

**Constraints:**

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

## A solution in Java

```java
public int countPatternsInWord(String[] patterns, String word) {
    int count = 0;
    for (String pattern : patterns) {
        if (word.contains(pattern)) {
            count++;
        }
    }
    return count;
}
```
The algorithm iterates through each string in the given `patterns` array. In each iteration, it checks if the current pattern is a substring of the given `word`. If it is, it increases the count.

For C++, we use the `find` method of the `std::string` class and compare the result to `std::string::npos` to check if the pattern is present.

For Java, we use the `contains` method of the `String` class to check if the pattern is present.

For Python, we use the `in` operator to check if the pattern is present in the word.

For JavaScript, we use the `includes` method of the `String` class to check if the pattern is present.

At the end of the loop, the function returns the count of the patterns that are substrings of the given word.

## A solution in C++

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

int countPatternsInWord(const std::vector<std::string> &patterns, const std::string &word) {
    int count = 0;
    for (const std::string &pattern : patterns) {
        if (word.find(pattern) != std::string::npos) {
            count++;
        }
    }
    return count;
}
```
The algorithm iterates through each string in the given `patterns` array. In each iteration, it checks if the current pattern is a substring of the given `word`. If it is, it increases the count.

For C++, we use the `find` method of the `std::string` class and compare the result to `std::string::npos` to check if the pattern is present.

For Java, we use the `contains` method of the `String` class to check if the pattern is present.

For Python, we use the `in` operator to check if the pattern is present in the word.

For JavaScript, we use the `includes` method of the `String` class to check if the pattern is present.

At the end of the loop, the function returns the count of the patterns that are substrings of the given word.

## A solution in Python

```python
def count_patterns_in_word(patterns, word):
    count = 0
    for pattern in patterns:
        if pattern in word:
            count += 1
    return count
```
The algorithm iterates through each string in the given `patterns` array. In each iteration, it checks if the current pattern is a substring of the given `word`. If it is, it increases the count.

For C++, we use the `find` method of the `std::string` class and compare the result to `std::string::npos` to check if the pattern is present.

For Java, we use the `contains` method of the `String` class to check if the pattern is present.

For Python, we use the `in` operator to check if the pattern is present in the word.

For JavaScript, we use the `includes` method of the `String` class to check if the pattern is present.

At the end of the loop, the function returns the count of the patterns that are substrings of the given word.

## A solution in Javascript

```javascript
function countPatternsInWord(patterns, word) {
    let count = 0;
    for (const pattern of patterns) {
        if (word.includes(pattern)) {
            count++;
        }
    }
    return count;
}
```
The algorithm iterates through each string in the given `patterns` array. In each iteration, it checks if the current pattern is a substring of the given `word`. If it is, it increases the count.

For C++, we use the `find` method of the `std::string` class and compare the result to `std::string::npos` to check if the pattern is present.

For Java, we use the `contains` method of the `String` class to check if the pattern is present.

For Python, we use the `in` operator to check if the pattern is present in the word.

For JavaScript, we use the `includes` method of the `String` class to check if the pattern is present.

At the end of the loop, the function returns the count of the patterns that are substrings of the given word.