# Find All K-Distant Indices in an Array

- slug: find-all-k-distant-indices-in-an-array
- difficulty: Easy

You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`.

Return _a list of all k-distant indices sorted in **increasing order**_.

**Example 1:**

**Input:** nums = \[3,4,9,1,3,9,5\], key = 9, k = 1
**Output:** \[1,2,3,4,5,6\]
**Explanation:** Here, `nums[2] == key` and `nums[5] == key. - For index 0, |0 - 2| > k and |0 - 5| > k, so there is no j` where `|0 - j| <= k` and `nums[j] == key. Thus, 0 is not a k-distant index. - For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index. - For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index. - For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index. - For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index. - For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index. - For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index.`
Thus, we return \[1,2,3,4,5,6\] which is sorted in increasing order.

**Example 2:**

**Input:** nums = \[2,2,2,2,2\], key = 2, k = 2
**Output:** \[0,1,2,3,4\]
**Explanation:** For all indices i in nums, there exists some index j such that |i - j| <= k and nums\[j\] == key, so every index is a k-distant index.
Hence, we return \[0,1,2,3,4\].

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `1 <= nums[i] <= 1000`
*   `key` is an integer from the array `nums`.
*   `1 <= k <= nums.length`

## A solution in Java

```java
public boolean canFitStamps(int[][] grid, int stampHeight, int stampWidth) {
    int m = grid.length, n = grid[0].length;
    for (int i = 0; i + stampHeight - 1 < m; ++i) {
        for (int j = 0; j + stampWidth - 1 < n; ++j) {
            boolean canFit = true;
            for (int x = 0; x < stampHeight && canFit; ++x) {
                for (int y = 0; y < stampWidth && canFit; ++y) {
                    if (grid[i + x][j + y] == 1) {
                        canFit = false;
                    }
                }
            }
            if (canFit) {
                return true;
            }
        }
    }
    return false;
}
```
The algorithm loops through the cells of the grid, and for each cell, it checks if a stamp can fit the area starting from that cell. If the stamp fits without any occupied cells (value of 1) in the area, the function returns true. If the loop finishes without finding any fitting area, the function returns false.

## A solution in C++

```cpp
bool canFitStamps(vector<vector<int>>& grid, int stampHeight, int stampWidth) {
    int m = grid.size(), n = grid[0].size();
    for (int i = 0; i + stampHeight - 1 < m; ++i) {
        for (int j = 0; j + stampWidth - 1 < n; ++j) {
            bool canFit = true;
            for (int x = 0; x < stampHeight && canFit; ++x) {
                for (int y = 0; y < stampWidth && canFit; ++y) {
                    if (grid[i + x][j + y] == 1) {
                        canFit = false;
                    }
                }
            }
            if (canFit) {
                return true;
            }
        }
    }
    return false;
}
```
The algorithm loops through the cells of the grid, and for each cell, it checks if a stamp can fit the area starting from that cell. If the stamp fits without any occupied cells (value of 1) in the area, the function returns true. If the loop finishes without finding any fitting area, the function returns false.

## A solution in Python

```python
def can_fit_stamps(grid, stampHeight, stampWidth):
    m, n = len(grid), len(grid[0])
    for i in range(m - stampHeight + 1):
        for j in range(n - stampWidth + 1):
            canFit = True
            for x in range(stampHeight):
                for y in range(stampWidth):
                    if grid[i + x][j + y] == 1:
                        canFit = False
                        break
                if not canFit:
                    break
            if canFit:
                return True
    return False
```
The algorithm loops through the cells of the grid, and for each cell, it checks if a stamp can fit the area starting from that cell. If the stamp fits without any occupied cells (value of 1) in the area, the function returns true. If the loop finishes without finding any fitting area, the function returns false.

## A solution in Javascript

```javascript
function canFitStamps(grid, stampHeight, stampWidth) {
    let m = grid.length, n = grid[0].length;
    for (let i = 0; i + stampHeight - 1 < m; ++i) {
        for (let j = 0; j + stampWidth - 1 < n; ++j) {
            let canFit = true;
            for (let x = 0; x < stampHeight && canFit; ++x) {
                for (let y = 0; y < stampWidth && canFit; ++y) {
                    if (grid[i + x][j + y] === 1) {
                        canFit = false;
                    }
                }
            }
            if (canFit) {
                return true;
            }
        }
    }
    return false;
}
```
The algorithm loops through the cells of the grid, and for each cell, it checks if a stamp can fit the area starting from that cell. If the stamp fits without any occupied cells (value of 1) in the area, the function returns true. If the loop finishes without finding any fitting area, the function returns false.


# Count Artifacts That Can Be Extracted

- slug: count-artifacts-that-can-be-extracted
- difficulty: Medium

There is an `n x n` **0-indexed** grid with some artifacts buried in it. You are given the integer `n` and a **0-indexed** 2D integer array `artifacts` describing the positions of the rectangular artifacts where `artifacts[i] = [r1i, c1i, r2i, c2i]` denotes that the `ith` artifact is buried in the subgrid where:

*   `(r1i, c1i)` is the coordinate of the **top-left** cell of the `ith` artifact and
*   `(r2i, c2i)` is the coordinate of the **bottom-right** cell of the `ith` artifact.

You will excavate some cells of the grid and remove all the mud from them. If the cell has a part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact are uncovered, you can extract it.

Given a **0-indexed** 2D integer array `dig` where `dig[i] = [ri, ci]` indicates that you will excavate the cell `(ri, ci)`, return _the number of artifacts that you can extract_.

The test cases are generated such that:

*   No two artifacts overlap.
*   Each artifact only covers at most `4` cells.
*   The entries of `dig` are unique.

**Example 1:**

**Input:** n = 2, artifacts = \[\[0,0,0,0\],\[0,1,1,1\]\], dig = \[\[0,0\],\[0,1\]\]
**Output:** 1
**Explanation:**
The different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid.
There is 1 artifact that can be extracted, namely the red artifact.
The blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it.
Thus, we return 1.

**Example 2:**

**Input:** n = 2, artifacts = \[\[0,0,0,0\],\[0,1,1,1\]\], dig = \[\[0,0\],\[0,1\],\[1,1\]\]
**Output:** 2
**Explanation:** Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2.

**Constraints:**

*   `1 <= n <= 1000`
*   `1 <= artifacts.length, dig.length <= min(n2, 105)`
*   `artifacts[i].length == 4`
*   `dig[i].length == 2`
*   `0 <= r1i, c1i, r2i, c2i, ri, ci <= n - 1`
*   `r1i <= r2i`
*   `c1i <= c2i`
*   No two artifacts will overlap.
*   The number of cells covered by an artifact is **at most** `4`.
*   The entries of `dig` are unique.

## A solution in Java

```java
import java.util.*;

public List<List<Integer>> arrangePairs(List<List<Integer>> pairs) {
    Map<Integer, List<Integer>> adj = new HashMap<>();
    for (List<Integer> pair : pairs) {
        adj.put(pair.get(0), pair);
    }

    List<List<Integer>> result = new ArrayList<>();
    int start = pairs.get(0).get(0);
    while (!adj.isEmpty()) {
        List<Integer> pair = adj.get(start);
        result.add(pair);
        start = pair.get(1);
        adj.remove(start);
    }

    return result;
}
```
The algorithm uses a hash map (unordered_map in C++, HashMap in Java, dictionary in Python, and object in JavaScript) to store the starting points of each pair as keys and the pairs themselves as values.

We initialize the `result`, an empty array that will store the valid arrangement of pairs.

Then, we select the starting pair using the first pair's starting point, and enter a loop until we exhaust all the starting points in the hash map. Inside the loop, we:

1. Get the pair corresponding to the current starting point from the hash map.
2. Append the pair to the `result`.
3. Update the starting point to be the ending point of the current pair.
4. Remove the pair from the hash map.

Finally, we return the `result` array containing the valid arrangement of pairs.

## A solution in C++

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

std::vector<std::vector<int>> arrangePairs(std::vector<std::vector<int>>& pairs) {
    std::unordered_map<int, std::vector<int>> adj;
    for (const auto& pair : pairs) {
        adj[pair[0]] = pair;
    }

    std::vector<std::vector<int>> result;
    int start = pairs[0][0];
    while (!adj.empty()) {
        auto it = adj.find(start);
        result.push_back(it->second);
        start = it->second[1];
        adj.erase(it);
    }

    return result;
}
```
The algorithm uses a hash map (unordered_map in C++, HashMap in Java, dictionary in Python, and object in JavaScript) to store the starting points of each pair as keys and the pairs themselves as values.

We initialize the `result`, an empty array that will store the valid arrangement of pairs.

Then, we select the starting pair using the first pair's starting point, and enter a loop until we exhaust all the starting points in the hash map. Inside the loop, we:

1. Get the pair corresponding to the current starting point from the hash map.
2. Append the pair to the `result`.
3. Update the starting point to be the ending point of the current pair.
4. Remove the pair from the hash map.

Finally, we return the `result` array containing the valid arrangement of pairs.

## A solution in Python

```python
def arrange_pairs(pairs):
    adj = {pair[0]: pair for pair in pairs}
    result = []
    start = pairs[0][0]

    while adj:
        pair = adj.pop(start)
        result.append(pair)
        start = pair[1]

    return result
```
The algorithm uses a hash map (unordered_map in C++, HashMap in Java, dictionary in Python, and object in JavaScript) to store the starting points of each pair as keys and the pairs themselves as values.

We initialize the `result`, an empty array that will store the valid arrangement of pairs.

Then, we select the starting pair using the first pair's starting point, and enter a loop until we exhaust all the starting points in the hash map. Inside the loop, we:

1. Get the pair corresponding to the current starting point from the hash map.
2. Append the pair to the `result`.
3. Update the starting point to be the ending point of the current pair.
4. Remove the pair from the hash map.

Finally, we return the `result` array containing the valid arrangement of pairs.

## A solution in Javascript

```javascript
function arrangePairs(pairs) {
    const adj = {};
    for (const pair of pairs) {
        adj[pair[0]] = pair;
    }

    const result = [];
    let start = pairs[0][0];
    while (Object.keys(adj).length > 0) {
        const pair = adj[start];
        result.push(pair);
        start = pair[1];
        delete adj[start];
    }

    return result;
}
```
The algorithm uses a hash map (unordered_map in C++, HashMap in Java, dictionary in Python, and object in JavaScript) to store the starting points of each pair as keys and the pairs themselves as values.

We initialize the `result`, an empty array that will store the valid arrangement of pairs.

Then, we select the starting pair using the first pair's starting point, and enter a loop until we exhaust all the starting points in the hash map. Inside the loop, we:

1. Get the pair corresponding to the current starting point from the hash map.
2. Append the pair to the `result`.
3. Update the starting point to be the ending point of the current pair.
4. Remove the pair from the hash map.

Finally, we return the `result` array containing the valid arrangement of pairs.


# Maximize the Topmost Element After K Moves

- slug: maximize-the-topmost-element-after-k-moves
- difficulty: Medium

You are given a **0-indexed** integer array `nums` representing the contents of a **pile**, where `nums[0]` is the topmost element of the pile.

In one move, you can perform **either** of the following:

*   If the pile is not empty, **remove** the topmost element of the pile.
*   If there are one or more removed elements, **add** any one of them back onto the pile. This element becomes the new topmost element.

You are also given an integer `k`, which denotes the total number of moves to be made.

Return _the **maximum value** of the topmost element of the pile possible after **exactly**_ `k` _moves_. In case it is not possible to obtain a non-empty pile after `k` moves, return `-1`.

**Example 1:**

**Input:** nums = \[5,2,2,4,0,6\], k = 4
**Output:** 5
**Explanation:**
One of the ways we can end with 5 at the top of the pile after 4 moves is as follows:
- Step 1: Remove the topmost element = 5. The pile becomes \[2,2,4,0,6\].
- Step 2: Remove the topmost element = 2. The pile becomes \[2,4,0,6\].
- Step 3: Remove the topmost element = 2. The pile becomes \[4,0,6\].
- Step 4: Add 5 back onto the pile. The pile becomes \[5,4,0,6\].
Note that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.

**Example 2:**

**Input:** nums = \[2\], k = 1
**Output:** -1
**Explanation:**
In the first move, our only option is to pop the topmost element of the pile.
Since it is not possible to obtain a non-empty pile after one move, we return -1.

**Constraints:**

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

## A solution in Java

```java
public static String toBaseK(int num, int k) {
    StringBuilder baseKNum = new StringBuilder();
    while (num > 0) {
        baseKNum.append(num % k);
        num /= k;
    }
    return baseKNum.toString();
}

public static boolean isKMirror(int num, int k) {
    String base10Num = Integer.toString(num);
    String baseKNum = toBaseK(num, k);
    return (new StringBuilder(base10Num).reverse().toString().equals(base10Num)) &&
           (new StringBuilder(baseKNum).reverse().toString().equals(baseKNum));
}

public static int sumKMirrorNumbers(int k, int n) {
    int sum = 0;
    int num = 0;
    while (n > 0) {
        if (isKMirror(num, k)) {
            sum += num;
            n--;
        }
        num++;
    }
    return sum;
}
```
We have defined functions `to_base_k` and `is_k_mirror` in all 4 programming languages. Function `to_base_k` takes a number and base and converts it to a number in the given base, returning that number as a string. Function `is_k_mirror` takes a number and base and returns `true` if it is a k-mirror number and `false` otherwise. It does this by checking if the number is a palindrome in base-10 and base-k.

Now, in the `sum_k_mirror_numbers` function, we take the given value of k and n, and we find the sum of the n smallest k-mirror numbers. We initialize a variable for the sum, and check each number, incrementing it to find k-mirror numbers. When we find a k-mirror number, we add it to the sum, and decrement the value of n. The loop continues until n becomes 0, and finally we return the sum.

## A solution in C++

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

std::string to_base_k(int num, int k) {
    std::string base_k_num = "";
    while (num) {
        base_k_num += std::to_string(num % k);
        num /= k;
    }
    return base_k_num;
}

bool is_k_mirror(int num, int k) {
    std::string base_10_num = std::to_string(num);
    std::string base_k_num = to_base_k(num, k);
    return (base_10_num == std::string(base_10_num.rbegin(), base_10_num.rend())) &&
           (base_k_num == std::string(base_k_num.rbegin(), base_k_num.rend()));
}

int sum_k_mirror_numbers(int k, int n) {
    int sum = 0;
    int num = 0;
    while (n) {
        if (is_k_mirror(num, k)) {
            sum += num;
            n--;
        }
        num++;
    }
    return sum;
}
```
We have defined functions `to_base_k` and `is_k_mirror` in all 4 programming languages. Function `to_base_k` takes a number and base and converts it to a number in the given base, returning that number as a string. Function `is_k_mirror` takes a number and base and returns `true` if it is a k-mirror number and `false` otherwise. It does this by checking if the number is a palindrome in base-10 and base-k.

Now, in the `sum_k_mirror_numbers` function, we take the given value of k and n, and we find the sum of the n smallest k-mirror numbers. We initialize a variable for the sum, and check each number, incrementing it to find k-mirror numbers. When we find a k-mirror number, we add it to the sum, and decrement the value of n. The loop continues until n becomes 0, and finally we return the sum.

## A solution in Python

```python
def to_base_k(num, k):
    base_k_num = ''
    while num:
        base_k_num = str(num % k) + base_k_num
        num //= k
    return base_k_num

def is_k_mirror(num, k):
    base_10_num = str(num)
    base_k_num = to_base_k(num, k)
    return base_10_num == base_10_num[::-1] and base_k_num == base_k_num[::-1]

def sum_k_mirror_numbers(k, n):
    total = 0
    num = 0
    while n:
        if is_k_mirror(num, k):
            total += num
            n -= 1
        num += 1
    return total
```
We have defined functions `to_base_k` and `is_k_mirror` in all 4 programming languages. Function `to_base_k` takes a number and base and converts it to a number in the given base, returning that number as a string. Function `is_k_mirror` takes a number and base and returns `true` if it is a k-mirror number and `false` otherwise. It does this by checking if the number is a palindrome in base-10 and base-k.

Now, in the `sum_k_mirror_numbers` function, we take the given value of k and n, and we find the sum of the n smallest k-mirror numbers. We initialize a variable for the sum, and check each number, incrementing it to find k-mirror numbers. When we find a k-mirror number, we add it to the sum, and decrement the value of n. The loop continues until n becomes 0, and finally we return the sum.

## A solution in Javascript

```javascript
function toBaseK(num, k) {
    let baseKNum = "";
    while (num > 0) {
        baseKNum = (num % k) + baseKNum;
        num = Math.floor(num / k);
    }
    return baseKNum;
}

function isKMirror(num, k) {
    const base10Num = num.toString();
    const baseKNum = toBaseK(num, k);
    return base10Num === base10Num.split('').reverse().join('') &&
           baseKNum === baseKNum.split('').reverse().join('');
}

function sumKMirrorNumbers(k, n) {
    let sum = 0;
    let num = 0;
    while (n > 0) {
        if (isKMirror(num, k)) {
            sum += num;
            n--;
        }
        num++;
    }
    return sum;
}
```
We have defined functions `to_base_k` and `is_k_mirror` in all 4 programming languages. Function `to_base_k` takes a number and base and converts it to a number in the given base, returning that number as a string. Function `is_k_mirror` takes a number and base and returns `true` if it is a k-mirror number and `false` otherwise. It does this by checking if the number is a palindrome in base-10 and base-k.

Now, in the `sum_k_mirror_numbers` function, we take the given value of k and n, and we find the sum of the n smallest k-mirror numbers. We initialize a variable for the sum, and check each number, incrementing it to find k-mirror numbers. When we find a k-mirror number, we add it to the sum, and decrement the value of n. The loop continues until n becomes 0, and finally we return the sum.


# Minimum Weighted Subgraph With the Required Paths

- slug: minimum-weighted-subgraph-with-the-required-paths
- difficulty: Hard

You are given an integer `n` denoting the number of nodes of a **weighted directed** graph. The nodes are numbered from `0` to `n - 1`.

You are also given a 2D integer array `edges` where `edges[i] = [fromi, toi, weighti]` denotes that there exists a **directed** edge from `fromi` to `toi` with weight `weighti`.

Lastly, you are given three **distinct** integers `src1`, `src2`, and `dest` denoting three distinct nodes of the graph.

Return _the **minimum weight** of a subgraph of the graph such that it is **possible** to reach_ `dest` _from both_ `src1` _and_ `src2` _via a set of edges of this subgraph_. In case such a subgraph does not exist, return `-1`.

A **subgraph** is a graph whose vertices and edges are subsets of the original graph. The **weight** of a subgraph is the sum of weights of its constituent edges.

**Example 1:**

**Input:** n = 6, edges = \[\[0,2,2\],\[0,5,6\],\[1,0,3\],\[1,4,5\],\[2,1,1\],\[2,3,3\],\[2,3,4\],\[3,4,2\],\[4,5,1\]\], src1 = 0, src2 = 1, dest = 5
**Output:** 9
**Explanation:**
The above figure represents the input graph.
The blue edges represent one of the subgraphs that yield the optimal answer.
Note that the subgraph \[\[1,0,3\],\[0,5,6\]\] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints.

**Example 2:**

**Input:** n = 3, edges = \[\[0,1,1\],\[2,1,1\]\], src1 = 0, src2 = 1, dest = 2
**Output:** -1
**Explanation:**
The above figure represents the input graph.
It can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.

**Constraints:**

*   `3 <= n <= 105`
*   `0 <= edges.length <= 105`
*   `edges[i].length == 3`
*   `0 <= fromi, toi, src1, src2, dest <= n - 1`
*   `fromi != toi`
*   `src1`, `src2`, and `dest` are pairwise distinct.
*   `1 <= weight[i] <= 105`

## A solution in Java

```java
import java.util.*;

public int minWeightSubgraph(int n, int[][] edges, int src1, int src2, int dest) {
    List<List<int[]>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        adj.add(new ArrayList<>());
    }
    for (int[] edge : edges) {
        adj.get(edge[0]).add(new int[]{edge[1], edge[2]});
    }

    IntFunction<int[]> dijkstra = src -> {
        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[src] = 0;
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
        pq.offer(new int[]{0, src});

        while (!pq.isEmpty()) {
            int[] top = pq.poll();
            int d = top[0], u = top[1];
            if (d != dist[u]) continue;
            for (int[] nei : adj.get(u)) {
                int v = nei[0], w = nei[1];
                if (d + w < dist[v]) {
                    dist[v] = d + w;
                    pq.offer(new int[]{dist[v], v});
                }
            }
        }

        return dist;
    };

    int[] dist1 = dijkstra.apply(src1);
    int[] dist2 = dijkstra.apply(src2);

    int res = dist1[dest] + dist2[dest];
    for (int[] edge : edges) {
        int u = edge[0], v = edge[1], w = edge[2];
        res = Math.min(res, dist1[u] + dist2[v] + w);
        res = Math.min(res, dist1[v] + dist2[u] + w);
    }

    return res == Integer.MAX_VALUE ? -1 : res;
}
```
1. Create an adjacency list representing the given graph.
2. Define a Dijkstra's algorithm function to find the shortest distance between two nodes.
3. Use Dijkstra's algorithm to find the shortest distances from `src1` and `src2` to all other nodes in the graph.
4. Initialize `res` as the sum of the shortest path distances from `src1` and `src2` to the `dest`.
5. Iterate through all edges in the graph, and for each edge, update `res` as the minimum of the following:
   a. The current value of `res`.
   b. The sum of the shortest path distances from `src1` and `src2` to one node of the edge, plus the edge weight.
   c. The sum of the shortest path distances from `src2` and `src1` to one node of the edge, plus the edge weight.
6. If `res` is unchanged, return -1; otherwise, return the minimum weight subgraph.

## A solution in C++

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

using namespace std;

int min_weight_subgraph(int n, vector<vector<int>>& edges, int src1, int src2, int dest) {
    vector<vector<pair<int, int>>> adj(n);
    for (auto &edge : edges) {
        adj[edge[0]].emplace_back(edge[1], edge[2]);
    }

    auto dijkstra = [&](int src) {
        vector<int> dist(n, numeric_limits<int>::max());
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
        dist[src] = 0;
        pq.emplace(0, src);

        while (!pq.empty()) {
            int u = pq.top().second;
            int d = pq.top().first;
            pq.pop();
            if (d != dist[u]) continue;
            for (auto &[v, w] : adj[u]) {
                if (d + w < dist[v]) {
                    dist[v] = d + w;
                    pq.emplace(dist[v], v);
                }
            }
        }

        return dist;
    };

    vector<int> dist1 = dijkstra(src1);
    vector<int> dist2 = dijkstra(src2);

    int res = dist1[dest] + dist2[dest];
    for (auto &edge : edges) {
        int u = edge[0], v = edge[1], w = edge[2];
        res = min(res, dist1[u] + dist2[v] + w);
        res = min(res, dist1[v] + dist2[u] + w);
    }

    return res == numeric_limits<int>::max() ? -1 : res;
}
```
1. Create an adjacency list representing the given graph.
2. Define a Dijkstra's algorithm function to find the shortest distance between two nodes.
3. Use Dijkstra's algorithm to find the shortest distances from `src1` and `src2` to all other nodes in the graph.
4. Initialize `res` as the sum of the shortest path distances from `src1` and `src2` to the `dest`.
5. Iterate through all edges in the graph, and for each edge, update `res` as the minimum of the following:
   a. The current value of `res`.
   b. The sum of the shortest path distances from `src1` and `src2` to one node of the edge, plus the edge weight.
   c. The sum of the shortest path distances from `src2` and `src1` to one node of the edge, plus the edge weight.
6. If `res` is unchanged, return -1; otherwise, return the minimum weight subgraph.

## A solution in Python

```python
from heapq import heappop, heappush
from sys import maxsize

def dijkstra(src, adj):
    dist = [maxsize] * len(adj)
    dist[src] = 0
    pq = [(0, src)]

    while pq:
        d, u = heappop(pq)
        if d != dist[u]:
            continue
        for v, w in adj[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                heappush(pq, (dist[v], v))

    return dist

def min_weight_subgraph(n, edges, src1, src2, dest):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))

    dist1 = dijkstra(src1, adj)
    dist2 = dijkstra(src2, adj)

    res = dist1[dest] + dist2[dest]
    for u, v, w in edges:
        res = min(res, dist1[u] + dist2[v] + w)
        res = min(res, dist1[v] + dist2[u] + w)

    return res if res != maxsize else -1
```
1. Create an adjacency list representing the given graph.
2. Define a Dijkstra's algorithm function to find the shortest distance between two nodes.
3. Use Dijkstra's algorithm to find the shortest distances from `src1` and `src2` to all other nodes in the graph.
4. Initialize `res` as the sum of the shortest path distances from `src1` and `src2` to the `dest`.
5. Iterate through all edges in the graph, and for each edge, update `res` as the minimum of the following:
   a. The current value of `res`.
   b. The sum of the shortest path distances from `src1` and `src2` to one node of the edge, plus the edge weight.
   c. The sum of the shortest path distances from `src2` and `src1` to one node of the edge, plus the edge weight.
6. If `res` is unchanged, return -1; otherwise, return the minimum weight subgraph.

## A solution in Javascript

```javascript
function dijkstra(src, adj) {
    const dist = new Array(adj.length).fill(Infinity);
    dist[src] = 0;
    const pq = [[0, src]];

    while (pq.length > 0) {
        const [d, u] = pq.shift();
        if (d !== dist[u]) continue;
        for (const [v, w] of adj[u]) {
            if (d + w < dist[v]) {
                dist[v] = d + w;
                pq.push([dist[v], v]);
                pq.sort((a, b) => a[0] - b[0]);
            }
        }
    }

    return dist;
}

function minWeightSubgraph(n, edges, src1, src2, dest) {
    const adj = Array.from({ length: n }, () => []);
    for (const [u, v, w] of edges) {
        adj[u].push([v, w]);
    }

    const dist1 = dijkstra(src1, adj);
    const dist2 = dijkstra(src2, adj);

    let res = dist1[dest] + dist2[dest];
    for (const [u, v, w] of edges) {
        res = Math.min(res, dist1[u] + dist2[v] + w);
        res = Math.min(res, dist1[v] + dist2[u] + w);
    }

    return res === Infinity ? -1 : res;
}
```
1. Create an adjacency list representing the given graph.
2. Define a Dijkstra's algorithm function to find the shortest distance between two nodes.
3. Use Dijkstra's algorithm to find the shortest distances from `src1` and `src2` to all other nodes in the graph.
4. Initialize `res` as the sum of the shortest path distances from `src1` and `src2` to the `dest`.
5. Iterate through all edges in the graph, and for each edge, update `res` as the minimum of the following:
   a. The current value of `res`.
   b. The sum of the shortest path distances from `src1` and `src2` to one node of the edge, plus the edge weight.
   c. The sum of the shortest path distances from `src2` and `src1` to one node of the edge, plus the edge weight.
6. If `res` is unchanged, return -1; otherwise, return the minimum weight subgraph.


# Distance to a Cycle in Undirected Graph

- slug: distance-to-a-cycle-in-undirected-graph
- difficulty: Hard

You are given a positive integer `n` representing the number of nodes in a **connected undirected graph** containing **exactly one** cycle. The nodes are numbered from `0` to `n - 1` (**inclusive**).

You are also given a 2D integer array `edges`, where `edges[i] = [node1i, node2i]` denotes that there is a **bidirectional** edge connecting `node1i` and `node2i` in the graph.

The distance between two nodes `a` and `b` is defined to be the **minimum** number of edges that are needed to go from `a` to `b`.

Return _an integer array `answer`_ _of size_ `n`_, where_ `answer[i]` _is the **minimum** distance between the_ `ith` _node and **any** node in the cycle._

**Example 1:**

**Input:** n = 7, edges = \[\[1,2\],\[2,4\],\[4,3\],\[3,1\],\[0,1\],\[5,2\],\[6,5\]\]
**Output:** \[1,0,0,0,0,1,2\]
**Explanation:**
The nodes 1, 2, 3, and 4 form the cycle.
The distance from 0 to 1 is 1.
The distance from 1 to 1 is 0.
The distance from 2 to 2 is 0.
The distance from 3 to 3 is 0.
The distance from 4 to 4 is 0.
The distance from 5 to 2 is 1.
The distance from 6 to 2 is 2.

**Example 2:**

**Input:** n = 9, edges = \[\[0,1\],\[1,2\],\[0,2\],\[2,6\],\[6,7\],\[6,8\],\[0,3\],\[3,4\],\[3,5\]\]
**Output:** \[0,0,0,1,2,2,1,2,2\]
**Explanation:**
The nodes 0, 1, and 2 form the cycle.
The distance from 0 to 0 is 0.
The distance from 1 to 1 is 0.
The distance from 2 to 2 is 0.
The distance from 3 to 1 is 1.
The distance from 4 to 1 is 2.
The distance from 5 to 1 is 2.
The distance from 6 to 2 is 1.
The distance from 7 to 2 is 2.
The distance from 8 to 2 is 2.

**Constraints:**

*   `3 <= n <= 105`
*   `edges.length == n`
*   `edges[i].length == 2`
*   `0 <= node1i, node2i <= n - 1`
*   `node1i != node2i`
*   The graph is connected.
*   The graph has exactly one cycle.
*   There is at most one edge between any pair of vertices.

## A solution in Java

```java
import java.util.PriorityQueue;

public int[] largestSumSequence(int[] nums, int k) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);

    for (int num : nums) {
        minHeap.offer(num);
        if (minHeap.size() > k) {
            minHeap.poll();
        }
    }

    int[] result = new int[k];
    for (int i = k - 1; i >= 0; i--) {
        result[i] = minHeap.poll();
    }

    return result;
}
```
The algorithm uses a min-heap of size `k` to keep track of the largest `k` elements in the input array. It iterates through the array, pushing each element to the heap. If the heap has more than `k` elements, it pops the smallest element. After processing all elements, the min-heap contains the desired subsequence having the largest sum, and we just need to transform the heap back to an array with the same order of elements.

## A solution in C++

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

std::vector<int> largestSumSequence(std::vector<int>& nums, int k) {
    std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap;

    for (int num : nums) {
        min_heap.push(num);
        if (min_heap.size() > k) {
            min_heap.pop();
        }
    }

    std::vector<int> result(min_heap.size());
    while (!min_heap.empty()) {
        result[min_heap.size() - 1] = min_heap.top();
        min_heap.pop();
    }

    return result;
}
```
The algorithm uses a min-heap of size `k` to keep track of the largest `k` elements in the input array. It iterates through the array, pushing each element to the heap. If the heap has more than `k` elements, it pops the smallest element. After processing all elements, the min-heap contains the desired subsequence having the largest sum, and we just need to transform the heap back to an array with the same order of elements.

## A solution in Python

```python
import heapq

def largest_sum_sequence(nums, k):
    min_heap = []

    for num in nums:
        heapq.heappush(min_heap, num)
        if len(min_heap) > k:
            heapq.heappop(min_heap)

    result = [0] * k
    for i in range(k-1, -1, -1):
        result[i] = heapq.heappop(min_heap)

    return result
```
The algorithm uses a min-heap of size `k` to keep track of the largest `k` elements in the input array. It iterates through the array, pushing each element to the heap. If the heap has more than `k` elements, it pops the smallest element. After processing all elements, the min-heap contains the desired subsequence having the largest sum, and we just need to transform the heap back to an array with the same order of elements.

## A solution in Javascript

```javascript
function largestSumSequence(nums, k) {
    const minHeap = new MinHeap();

    for (const num of nums) {
        minHeap.push(num);
        if (minHeap.getSize() > k) {
            minHeap.pop();
        }
    }

    const result = new Array(k);
    for (let i = k - 1; i >= 0; i--) {
        result[i] = minHeap.pop();
    }

    return result;
}

class MinHeap {
    constructor() {
        this.heap = [];
    }

    push(num) {
        this.heap.push(num);
        this.bubbleUp(this.heap.length - 1);
    }

    pop() {
        const min = this.heap[0];
        this.heap[0] = this.heap.pop();
        this.bubbleDown(0);
        return min;
    }

    getSize() {
        return this.heap.length;
    }

    bubbleUp(index) {
        while (index > 0 && this.heap[index] < this.heap[Math.floor((index - 1) / 2)]) {
            this.swap(index, Math.floor((index - 1) / 2));
            index = Math.floor((index - 1) / 2);
        }
    }

    bubbleDown(index) {
        while (2 * index + 1 < this.heap.length) {
            let minIndex = 2 * index + 1;
            if (2 * index + 2 < this.heap.length && this.heap[minIndex] > this.heap[2 * index + 2]) {
                minIndex = 2 * index + 2;
            }
            if (this.heap[index] > this.heap[minIndex]) {
                this.swap(index, minIndex);
                index = minIndex;
            } else {
                break;
            }
        }
    }

    swap(i, j) {
        const tmp = this.heap[i];
        this.heap[i] = this.heap[j];
        this.heap[j] = tmp;
    }
}
```
The algorithm uses a min-heap of size `k` to keep track of the largest `k` elements in the input array. It iterates through the array, pushing each element to the heap. If the heap has more than `k` elements, it pops the smallest element. After processing all elements, the min-heap contains the desired subsequence having the largest sum, and we just need to transform the heap back to an array with the same order of elements.


# Divide Array Into Equal Pairs

- slug: divide-array-into-equal-pairs
- difficulty: Easy

You are given an integer array `nums` consisting of `2 * n` integers.

You need to divide `nums` into `n` pairs such that:

*   Each element belongs to **exactly one** pair.
*   The elements present in a pair are **equal**.

Return `true` _if nums can be divided into_ `n` _pairs, otherwise return_ `false`.

**Example 1:**

**Input:** nums = \[3,2,3,2,2,2\]
**Output:** true
**Explanation:**
There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.
If nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.

**Example 2:**

**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:**
There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.

**Constraints:**

*   `nums.length == 2 * n`
*   `1 <= n <= 500`
*   `1 <= nums[i] <= 500`

## A solution in Java

```java
import java.util.List;

public int maxBombsDetonated(List<List<Integer>> bombs) {
    int n = bombs.size();
    int maxBombs = 0;

    for (int i = 0; i < n; i++) {
        int count = 0;
        for (int j = 0; j < n; j++) {
            int dx = bombs.get(i).get(0) - bombs.get(j).get(0);
            int dy = bombs.get(i).get(1) - bombs.get(j).get(1);
            int distance = dx * dx + dy * dy;
            int range = bombs.get(i).get(2) * bombs.get(i).get(2) + bombs.get(j).get(2) * bombs.get(j).get(2);
            if (distance <= range) {
                count++;
            }
        }
        maxBombs = Math.max(maxBombs, count);
    }

    return maxBombs;
}
```
To solve this problem, we want to find the maximum number of bombs that can be detonated by detonating a single bomb. The algorithm:
1. Determine the number of bombs `n` and initialize a variable `max_bombs` to store the maximum number of bombs that can be detonated.
2. Iterate through each bomb `i` in the given list of bombs.
3. For each bomb, initialize a counter `count` to store the number of bombs it can detonate in its range.
4. Iterate through all other bombs `j`.
    - Calculate the distance between the bombs `i` and `j` (using squared Euclidean distance to avoid floating point calculations).
    - Calculate the sum of the squares of the radii of bombs `i` and `j`.
    - If the distance between the bombs is less than or equal to the sum of the squares of their radii, it means bomb `i` can detonate bomb `j`. Increment the counter `count`.
5. Update the maximum number of bombs that can be detonated by checking if `count` is greater than the current value of `max_bombs`.
6. Repeat steps 3-5 for all bombs `i`.
7. Return the value of `max_bombs`. This represents the maximum number of bombs that can be detonated by detonating a single bomb in the given list of bombs.

## A solution in C++

```cpp
#include <vector>
#include <cmath>

int maxBombsDetonated(std::vector<std::vector<int>>& bombs) {
    int n = bombs.size();
    int max_bombs = 0;

    for (int i = 0; i < n; ++i) {
        int count = 0;
        for (int j = 0; j < n; ++j) {
            int dx = bombs[i][0] - bombs[j][0];
            int dy = bombs[i][1] - bombs[j][1];
            int distance = dx * dx + dy * dy;
            int range = bombs[i][2] * bombs[i][2] + bombs[j][2] * bombs[j][2];
            if (distance <= range) {
                count++;
            }
        }
        max_bombs = std::max(max_bombs, count);
    }

    return max_bombs;
}
```
To solve this problem, we want to find the maximum number of bombs that can be detonated by detonating a single bomb. The algorithm:
1. Determine the number of bombs `n` and initialize a variable `max_bombs` to store the maximum number of bombs that can be detonated.
2. Iterate through each bomb `i` in the given list of bombs.
3. For each bomb, initialize a counter `count` to store the number of bombs it can detonate in its range.
4. Iterate through all other bombs `j`.
    - Calculate the distance between the bombs `i` and `j` (using squared Euclidean distance to avoid floating point calculations).
    - Calculate the sum of the squares of the radii of bombs `i` and `j`.
    - If the distance between the bombs is less than or equal to the sum of the squares of their radii, it means bomb `i` can detonate bomb `j`. Increment the counter `count`.
5. Update the maximum number of bombs that can be detonated by checking if `count` is greater than the current value of `max_bombs`.
6. Repeat steps 3-5 for all bombs `i`.
7. Return the value of `max_bombs`. This represents the maximum number of bombs that can be detonated by detonating a single bomb in the given list of bombs.

## A solution in Python

```python
from typing import List

def max_bombs_detonated(bombs: List[List[int]]) -> int:
    n = len(bombs)
    max_bombs = 0

    for i in range(n):
        count = 0
        for j in range(n):
            dx = bombs[i][0] - bombs[j][0]
            dy = bombs[i][1] - bombs[j][1]
            distance = dx * dx + dy * dy
            range_ = bombs[i][2] * bombs[i][2] + bombs[j][2] * bombs[j][2]
            if distance <= range_:
                count += 1
        max_bombs = max(max_bombs, count)

    return max_bombs
```
To solve this problem, we want to find the maximum number of bombs that can be detonated by detonating a single bomb. The algorithm:
1. Determine the number of bombs `n` and initialize a variable `max_bombs` to store the maximum number of bombs that can be detonated.
2. Iterate through each bomb `i` in the given list of bombs.
3. For each bomb, initialize a counter `count` to store the number of bombs it can detonate in its range.
4. Iterate through all other bombs `j`.
    - Calculate the distance between the bombs `i` and `j` (using squared Euclidean distance to avoid floating point calculations).
    - Calculate the sum of the squares of the radii of bombs `i` and `j`.
    - If the distance between the bombs is less than or equal to the sum of the squares of their radii, it means bomb `i` can detonate bomb `j`. Increment the counter `count`.
5. Update the maximum number of bombs that can be detonated by checking if `count` is greater than the current value of `max_bombs`.
6. Repeat steps 3-5 for all bombs `i`.
7. Return the value of `max_bombs`. This represents the maximum number of bombs that can be detonated by detonating a single bomb in the given list of bombs.

## A solution in Javascript

```javascript
function maxBombsDetonated(bombs) {
    let n = bombs.length;
    let maxBombs = 0;

    for (let i = 0; i < n; i++) {
        let count = 0;
        for (let j = 0; j < n; j++) {
            let dx = bombs[i][0] - bombs[j][0];
            let dy = bombs[i][1] - bombs[j][1];
            let distance = dx * dx + dy * dy;
            let range = bombs[i][2] * bombs[i][2] + bombs[j][2] * bombs[j][2];
            if (distance <= range) {
                count++;
            }
        }
        maxBombs = Math.max(maxBombs, count);
    }

    return maxBombs;
}
```
To solve this problem, we want to find the maximum number of bombs that can be detonated by detonating a single bomb. The algorithm:
1. Determine the number of bombs `n` and initialize a variable `max_bombs` to store the maximum number of bombs that can be detonated.
2. Iterate through each bomb `i` in the given list of bombs.
3. For each bomb, initialize a counter `count` to store the number of bombs it can detonate in its range.
4. Iterate through all other bombs `j`.
    - Calculate the distance between the bombs `i` and `j` (using squared Euclidean distance to avoid floating point calculations).
    - Calculate the sum of the squares of the radii of bombs `i` and `j`.
    - If the distance between the bombs is less than or equal to the sum of the squares of their radii, it means bomb `i` can detonate bomb `j`. Increment the counter `count`.
5. Update the maximum number of bombs that can be detonated by checking if `count` is greater than the current value of `max_bombs`.
6. Repeat steps 3-5 for all bombs `i`.
7. Return the value of `max_bombs`. This represents the maximum number of bombs that can be detonated by detonating a single bomb in the given list of bombs.


# Minimum Operations to Halve Array Sum

- slug: minimum-operations-to-halve-array-sum
- difficulty: Medium

You are given an array `nums` of positive integers. In one operation, you can choose **any** number from `nums` and reduce it to **exactly** half the number. (Note that you may choose this reduced number in future operations.)

Return _the **minimum** number of operations to reduce the sum of_ `nums` _by **at least** half._

**Example 1:**

**Input:** nums = \[5,19,8,1\]
**Output:** 3
**Explanation:** The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.
The following is one of the ways to reduce the sum by at least half:
Pick the number 19 and reduce it to 9.5.
Pick the number 9.5 and reduce it to 4.75.
Pick the number 8 and reduce it to 4.
The final array is \[5, 4.75, 4, 1\] with a total sum of 5 + 4.75 + 4 + 1 = 14.75.
The sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.

**Example 2:**

**Input:** nums = \[3,8,20\]
**Output:** 3
**Explanation:** The initial sum of nums is equal to 3 + 8 + 20 = 31.
The following is one of the ways to reduce the sum by at least half:
Pick the number 20 and reduce it to 10.
Pick the number 10 and reduce it to 5.
Pick the number 3 and reduce it to 1.5.
The final array is \[1.5, 8, 5\] with a total sum of 1.5 + 8 + 5 = 14.5.
The sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.

**Constraints:**

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

## A solution in Java

```java
import java.util.PriorityQueue;
import java.util.Collections;

public int minOperations(int[] nums) {
    PriorityQueue<Integer> max_heap = new PriorityQueue<>(nums.length, Collections.reverseOrder());

    int initial_sum = 0;
    for (int num : nums) {
        initial_sum += num;
        max_heap.add(num);
    }

    int target_sum = initial_sum / 2;
    int sum_so_far = 0;
    int operations = 0;

    while (sum_so_far <= target_sum) {
        int largest = max_heap.poll();
        sum_so_far += largest / 2;
        operations += 1;
    }

    return operations;
}
```
The algorithm starts by adding all elements from `nums` to a max_heap. We then compute the initial sum and target sum of the array values.

We start a loop where we pop the largest value from the max_heap, update the current sum to try to reach the target sum, and increment the operations counter. We continue this process until the current sum surpasses the target sum.

The time complexity of this algorithm is O(nlogn) due to the use of a priority queue (max heap).

## A solution in C++

```cpp
#include <vector>
#include <functional>
#include <queue>
#include <numeric>

int min_operations(std::vector<int>& nums) {
    std::priority_queue<int, std::vector<int>, std::less<int>> max_heap(nums.begin(), nums.end());
    int initial_sum = std::accumulate(nums.begin(), nums.end(), 0);
    int target_sum = initial_sum / 2;
    int sum_so_far = 0;
    int operations = 0;

    while (sum_so_far <= target_sum) {
        int largest = max_heap.top();
        max_heap.pop();
        sum_so_far += largest / 2;
        operations += 1;
    }

    return operations;
}
```
The algorithm starts by adding all elements from `nums` to a max_heap. We then compute the initial sum and target sum of the array values.

We start a loop where we pop the largest value from the max_heap, update the current sum to try to reach the target sum, and increment the operations counter. We continue this process until the current sum surpasses the target sum.

The time complexity of this algorithm is O(nlogn) due to the use of a priority queue (max heap).

## A solution in Python

```python
import heapq

def min_operations(nums):
    max_heap = [-num for num in nums]
    heapq.heapify(max_heap)
    initial_sum = sum(nums)
    target_sum = initial_sum // 2
    sum_so_far = 0
    operations = 0

    while sum_so_far <= target_sum:
        largest = -heapq.heappop(max_heap)
        sum_so_far += largest // 2
        operations += 1

    return operations
```
The algorithm starts by adding all elements from `nums` to a max_heap. We then compute the initial sum and target sum of the array values.

We start a loop where we pop the largest value from the max_heap, update the current sum to try to reach the target sum, and increment the operations counter. We continue this process until the current sum surpasses the target sum.

The time complexity of this algorithm is O(nlogn) due to the use of a priority queue (max heap).

## A solution in Javascript

```javascript
function minOperations(nums) {
    const max_heap = new MaxHeap(nums);
    const initial_sum = nums.reduce((acc, val) => acc + val, 0);
    const target_sum = Math.floor(initial_sum / 2);
    let sum_so_far = 0;
    let operations = 0;

    while (sum_so_far <= target_sum) {
        const largest = max_heap.pop();
        sum_so_far += Math.floor(largest / 2);
        operations++;
    }

    return operations;
}

class MaxHeap {
    constructor(elements) {
        this.heap = [];
        for (let elem of elements) {
            this.push(elem);
        }
    }

    push(val) {
        this.heap.push(val);
        this._bubbleUp();
    }

    pop() {
        if (this.heap.length === 1) return this.heap.pop();
        const max = this.heap[0];
        this.heap[0] = this.heap.pop();
        this._sinkDown();
        return max;
    }

    _bubbleUp() {
        let idx = this.heap.length - 1;
        while (idx > 0) {
            const parentIdx = Math.floor((idx - 1) / 2);
            if (this.heap[parentIdx] >= this.heap[idx]) break;
            this._swap(idx, parentIdx);
            idx = parentIdx;
        }
    }

    _sinkDown() {
        let idx = 0;
        const length = this.heap.length;
        const element = this.heap[0];
        while (true) {
            const leftChildIdx = 2 * idx + 1;
            const rightChildIdx = 2 * idx + 2;
            let swap = null;

            if (leftChildIdx < length) {
                if (this.heap[leftChildIdx] > element) {
                    swap = leftChildIdx;
                }
            }

            if (rightChildIdx < length) {
                if ((swap === null && this.heap[rightChildIdx] > element) ||
                    (swap !== null && this.heap[rightChildIdx] > this.heap[leftChildIdx])) {
                    swap = rightChildIdx;
                }
            }

            if (swap === null) break;
            this._swap(idx, swap);
            idx = swap;
        }
    }

    _swap(i, j) {
        [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
    }
}
```
The algorithm starts by adding all elements from `nums` to a max_heap. We then compute the initial sum and target sum of the array values.

We start a loop where we pop the largest value from the max_heap, update the current sum to try to reach the target sum, and increment the operations counter. We continue this process until the current sum surpasses the target sum.

The time complexity of this algorithm is O(nlogn) due to the use of a priority queue (max heap).


# Minimum White Tiles After Covering With Carpets

- slug: minimum-white-tiles-after-covering-with-carpets
- difficulty: Hard

You are given a **0-indexed binary** string `floor`, which represents the colors of tiles on a floor:

*   `floor[i] = '0'` denotes that the `ith` tile of the floor is colored **black**.
*   On the other hand, `floor[i] = '1'` denotes that the `ith` tile of the floor is colored **white**.

You are also given `numCarpets` and `carpetLen`. You have `numCarpets` **black** carpets, each of length `carpetLen` tiles. Cover the tiles with the given carpets such that the number of **white** tiles still visible is **minimum**. Carpets may overlap one another.

Return _the **minimum** number of white tiles still visible._

**Example 1:**

**Input:** floor =  "10110101 ", numCarpets = 2, carpetLen = 2
**Output:** 2
**Explanation:**
The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.
No other way of covering the tiles with the carpets can leave less than 2 white tiles visible.

**Example 2:**

**Input:** floor =  "11111 ", numCarpets = 2, carpetLen = 3
**Output:** 0
**Explanation:**
The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.
Note that the carpets are able to overlap one another.

**Constraints:**

*   `1 <= carpetLen <= floor.length <= 1000`
*   `floor[i]` is either `'0'` or `'1'`.
*   `1 <= numCarpets <= 1000`

## A solution in Java

```java
public int minVisibleWhiteTiles(String floor, int numCarpets, int carpetLen) {
    int n = floor.length(), res = n;
    for (int i = 0; i < n - carpetLen + 1; ++i) {
        int count = 0;
        for (int j = 0; j < carpetLen; ++j)
            count += (floor.charAt(i + j) == '1') ? 1 : 0;
        for (int k = 1; k <= numCarpets && k * carpetLen - 1 <= i + carpetLen; ++k) {
            res = Math.min(res, n - count * k);
            if (i + carpetLen < n) {
                count -= (floor.charAt(i + carpetLen - k * carpetLen) == '1') ? 1 : 0;
                count += (floor.charAt(i + carpetLen) == '1') ? 1 : 0;
            }
        }
    }
    return res;
}
```
The algorithm starts by iterating through the `floor` string to count the possible white tiles that can be covered by one carpet in segments of the carpet length. This results in an optimal arrangement. Then we calculate the remaining count of white tiles for each carpet placement separately by overlapping the carpets where needed. Finally, we find the minimum count of visible white tiles from all combinations and return it as the result. While finding the minimum count, we also check for the overlap of different carpets to minimize visible white tiles.

## A solution in C++

```cpp
int minVisibleWhiteTiles(string floor, int numCarpets, int carpetLen) {
    int n = floor.size(), res = n;
    for (int i = 0; i < n - carpetLen + 1; ++i) {
        int count = 0;
        for (int j = 0; j < carpetLen; ++j)
            count += (floor[i + j] == '1');
        for (int k = 1; k <= numCarpets && k * carpetLen - 1 <= i + carpetLen; ++k) {
            res = min(res, n - count * k);
            if (i + carpetLen < n) {
                count -= (floor[i + carpetLen - k * carpetLen] == '1');
                count += (floor[i + carpetLen] == '1');
            }
        }
    }
    return res;
}
```
The algorithm starts by iterating through the `floor` string to count the possible white tiles that can be covered by one carpet in segments of the carpet length. This results in an optimal arrangement. Then we calculate the remaining count of white tiles for each carpet placement separately by overlapping the carpets where needed. Finally, we find the minimum count of visible white tiles from all combinations and return it as the result. While finding the minimum count, we also check for the overlap of different carpets to minimize visible white tiles.

## A solution in Python

```python
def minVisibleWhiteTiles(floor: str, numCarpets: int, carpetLen: int) -> int:
    n, res = len(floor), len(floor)
    for i in range(n - carpetLen + 1):
        count = sum(1 for j in range(carpetLen) if floor[i + j] == '1')
        for k in range(1, numCarpets + 1):
            if k * carpetLen - 1 <= i + carpetLen:
                res = min(res, n - count * k)
                if i + carpetLen < n:
                    count -= floor[i + carpetLen - k * carpetLen] == '1'
                    count += floor[i + carpetLen] == '1'
    return res
```
The algorithm starts by iterating through the `floor` string to count the possible white tiles that can be covered by one carpet in segments of the carpet length. This results in an optimal arrangement. Then we calculate the remaining count of white tiles for each carpet placement separately by overlapping the carpets where needed. Finally, we find the minimum count of visible white tiles from all combinations and return it as the result. While finding the minimum count, we also check for the overlap of different carpets to minimize visible white tiles.

## A solution in Javascript

```javascript
function minVisibleWhiteTiles(floor, numCarpets, carpetLen) {
    let n = floor.length, res = n;
    for (let i = 0; i < n - carpetLen + 1; ++i) {
        let count = 0;
        for (let j = 0; j < carpetLen; ++j)
            count += (floor[i + j] === '1') ? 1 : 0;
        for (let k = 1; k <= numCarpets && k * carpetLen - 1 <= i + carpetLen; ++k) {
            res = Math.min(res, n - count * k);
            if (i + carpetLen < n) {
                count -= (floor[i + carpetLen - k * carpetLen] === '1') ? 1 : 0;
                count += (floor[i + carpetLen] === '1') ? 1 : 0;
            }
        }
    }
    return res;
}
```
The algorithm starts by iterating through the `floor` string to count the possible white tiles that can be covered by one carpet in segments of the carpet length. This results in an optimal arrangement. Then we calculate the remaining count of white tiles for each carpet placement separately by overlapping the carpets where needed. Finally, we find the minimum count of visible white tiles from all combinations and return it as the result. While finding the minimum count, we also check for the overlap of different carpets to minimize visible white tiles.


# Count Hills and Valleys in an Array

- slug: count-hills-and-valleys-in-an-array
- difficulty: Easy

You are given a **0-indexed** integer array `nums`. An index `i` is part of a **hill** in `nums` if the closest non-equal neighbors of `i` are smaller than `nums[i]`. Similarly, an index `i` is part of a **valley** in `nums` if the closest non-equal neighbors of `i` are larger than `nums[i]`. Adjacent indices `i` and `j` are part of the **same** hill or valley if `nums[i] == nums[j]`.

Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on **both** the left and right of the index.

Return _the number of hills and valleys in_ `nums`.

**Example 1:**

**Input:** nums = \[2,4,1,1,6,5\]
**Output:** 3
**Explanation:**
At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.
At index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill.
At index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.
At index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.
At index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.
At index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley.
There are 3 hills and valleys so we return 3.

**Example 2:**

**Input:** nums = \[6,6,5,5,4,1\]
**Output:** 0
**Explanation:**
At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.
At index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.
At index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.
At index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.
At index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.
At index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.
There are 0 hills and valleys so we return 0.

**Constraints:**

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

## A solution in Java

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

public List<Integer> sortedTargetIndices(int[] nums, int target) {
    List<Integer> result = new ArrayList<>();
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == target) {
            result.add(i);
        }
    }
    Collections.sort(result);
    return result;
}
```
We iterate over the input array `nums` and check if the element at the current index is equal to the `target`. If it is, we add the current index to the `result` list. After iterating through the whole array, we sort the `result` list to ensure that the indices are in increasing order. Finally, we return the `result` list, which contains the target indices of the given element in the sorted array. If there are no target indices, the `result` list will be empty, and an empty list will be returned as specified.

## A solution in C++

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

std::vector<int> sortedTargetIndices(std::vector<int>& nums, int target) {
    std::vector<int> result;
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] == target) {
            result.push_back(i);
        }
    }
    std::sort(result.begin(), result.end());
    return result;
}
```
We iterate over the input array `nums` and check if the element at the current index is equal to the `target`. If it is, we add the current index to the `result` list. After iterating through the whole array, we sort the `result` list to ensure that the indices are in increasing order. Finally, we return the `result` list, which contains the target indices of the given element in the sorted array. If there are no target indices, the `result` list will be empty, and an empty list will be returned as specified.

## A solution in Python

```python
def sorted_target_indices(nums, target):
    result = [i for i, num in enumerate(nums) if num == target]
    return sorted(result)
```
We iterate over the input array `nums` and check if the element at the current index is equal to the `target`. If it is, we add the current index to the `result` list. After iterating through the whole array, we sort the `result` list to ensure that the indices are in increasing order. Finally, we return the `result` list, which contains the target indices of the given element in the sorted array. If there are no target indices, the `result` list will be empty, and an empty list will be returned as specified.

## A solution in Javascript

```javascript
function sortedTargetIndices(nums, target) {
    const result = [];
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] === target) {
            result.push(i);
        }
    }
    return result.sort((a, b) => a - b);
}
```
We iterate over the input array `nums` and check if the element at the current index is equal to the `target`. If it is, we add the current index to the `result` list. After iterating through the whole array, we sort the `result` list to ensure that the indices are in increasing order. Finally, we return the `result` list, which contains the target indices of the given element in the sorted array. If there are no target indices, the `result` list will be empty, and an empty list will be returned as specified.


# Count Collisions on a Road

- slug: count-collisions-on-a-road
- difficulty: Medium

There are `n` cars on an infinitely long road. The cars are numbered from `0` to `n - 1` from left to right and each car is present at a **unique** point.

You are given a **0-indexed** string `directions` of length `n`. `directions[i]` can be either `'L'`, `'R'`, or `'S'` denoting whether the `ith` car is moving towards the **left**, towards the **right**, or **staying** at its current point respectively. Each moving car has the **same speed**.

The number of collisions can be calculated as follows:

*   When two cars moving in **opposite** directions collide with each other, the number of collisions increases by `2`.
*   When a moving car collides with a stationary car, the number of collisions increases by `1`.

After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion.

Return _the **total number of collisions** that will happen on the road_.

**Example 1:**

**Input:** directions =  "RLRSLL "
**Output:** 5
**Explanation:**
The collisions that will happen on the road are:
- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.
- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.
- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.
- Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.
Thus, the total number of collisions that will happen on the road is 5.

**Example 2:**

**Input:** directions =  "LLRR "
**Output:** 0
**Explanation:**
No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.

**Constraints:**

*   `1 <= directions.length <= 105`
*   `directions[i]` is either `'L'`, `'R'`, or `'S'`.

## A solution in Java

```java
public int[] kRadiusAverage(int[] nums, int k) {
    int n = nums.length;
    int[] avgs = new int[n];
    for (int i = 0; i < n; i++) {
        avgs[i] = -1;
    }
    for (int i = k; i < n - k; i++) {
        int sum = 0;
        for (int j = i - k; j <= i + k; j++) {
            sum += nums[j];
        }
        avgs[i] = sum / (2 * k + 1);
    }
    return avgs;
}
```
The algorithm for finding the k-radius averages consists of the following steps:
1. Initialize an array `avgs` of the same length as `nums`, and fill it with -1.
2. Loop through `nums`, starting at index `k` and ending at index `n - k - 1`.
   For each index `i`, do the following:
   a. Initialize a variable `sum` to 0.
   b. Loop through the subarray `nums[i - k]` to `nums[i + k]`, calculate the sum of its elements, and store it in `sum`.
   c. Calculate the average of the subarray by dividing `sum` by `2 * k + 1`, and store the result in `avgs[i]`.
3. Return the `avgs` array.

The algorithm provides integer division for each language as follows:
- C++ and Python: The division operator `//` performs integer division.
- Java: The division operator `/` performs integer division when both operands are integers.
- JavaScript: The `Math.floor` function is used to truncate the result of the division.

The complexity of this algorithm is O(n*k), as it iterates through each element in `nums` and sums its surrounding k elements.

## A solution in C++

```cpp
#include <vector>

std::vector<int> kRadiusAverage(std::vector<int>& nums, int k) {
    int n = nums.size();
    std::vector<int> avgs(n, -1);
    for (int i = k; i < n - k; ++i) {
        int sum = 0;
        for (int j = i - k; j <= i + k; ++j) {
            sum += nums[j];
        }
        avgs[i] = sum / (2 * k + 1);
    }
    return avgs;
}
```
The algorithm for finding the k-radius averages consists of the following steps:
1. Initialize an array `avgs` of the same length as `nums`, and fill it with -1.
2. Loop through `nums`, starting at index `k` and ending at index `n - k - 1`.
   For each index `i`, do the following:
   a. Initialize a variable `sum` to 0.
   b. Loop through the subarray `nums[i - k]` to `nums[i + k]`, calculate the sum of its elements, and store it in `sum`.
   c. Calculate the average of the subarray by dividing `sum` by `2 * k + 1`, and store the result in `avgs[i]`.
3. Return the `avgs` array.

The algorithm provides integer division for each language as follows:
- C++ and Python: The division operator `//` performs integer division.
- Java: The division operator `/` performs integer division when both operands are integers.
- JavaScript: The `Math.floor` function is used to truncate the result of the division.

The complexity of this algorithm is O(n*k), as it iterates through each element in `nums` and sums its surrounding k elements.

## A solution in Python

```python
def k_radius_average(nums, k):
    n = len(nums)
    avgs = [-1] * n
    for i in range(k, n - k):
        sum = 0
        for j in range(i - k, i + k + 1):
            sum += nums[j]
        avgs[i] = sum // (2 * k + 1)
    return avgs
```
The algorithm for finding the k-radius averages consists of the following steps:
1. Initialize an array `avgs` of the same length as `nums`, and fill it with -1.
2. Loop through `nums`, starting at index `k` and ending at index `n - k - 1`.
   For each index `i`, do the following:
   a. Initialize a variable `sum` to 0.
   b. Loop through the subarray `nums[i - k]` to `nums[i + k]`, calculate the sum of its elements, and store it in `sum`.
   c. Calculate the average of the subarray by dividing `sum` by `2 * k + 1`, and store the result in `avgs[i]`.
3. Return the `avgs` array.

The algorithm provides integer division for each language as follows:
- C++ and Python: The division operator `//` performs integer division.
- Java: The division operator `/` performs integer division when both operands are integers.
- JavaScript: The `Math.floor` function is used to truncate the result of the division.

The complexity of this algorithm is O(n*k), as it iterates through each element in `nums` and sums its surrounding k elements.

## A solution in Javascript

```javascript
function kRadiusAverage(nums, k) {
    const n = nums.length;
    const avgs = Array(n).fill(-1);
    for (let i = k; i < n - k; i++) {
        let sum = 0;
        for (let j = i - k; j <= i + k; j++) {
            sum += nums[j];
        }
        avgs[i] = Math.floor(sum / (2 * k + 1));
    }
    return avgs;
}
```
The algorithm for finding the k-radius averages consists of the following steps:
1. Initialize an array `avgs` of the same length as `nums`, and fill it with -1.
2. Loop through `nums`, starting at index `k` and ending at index `n - k - 1`.
   For each index `i`, do the following:
   a. Initialize a variable `sum` to 0.
   b. Loop through the subarray `nums[i - k]` to `nums[i + k]`, calculate the sum of its elements, and store it in `sum`.
   c. Calculate the average of the subarray by dividing `sum` by `2 * k + 1`, and store the result in `avgs[i]`.
3. Return the `avgs` array.

The algorithm provides integer division for each language as follows:
- C++ and Python: The division operator `//` performs integer division.
- Java: The division operator `/` performs integer division when both operands are integers.
- JavaScript: The `Math.floor` function is used to truncate the result of the division.

The complexity of this algorithm is O(n*k), as it iterates through each element in `nums` and sums its surrounding k elements.


# Maximum Points in an Archery Competition

- slug: maximum-points-in-an-archery-competition
- difficulty: Medium

Alice and Bob are opponents in an archery competition. The competition has set the following rules:

1.  Alice first shoots `numArrows` arrows and then Bob shoots `numArrows` arrows.
2.  The points are then calculated as follows:
    1.  The target has integer scoring sections ranging from `0` to `11` **inclusive**.
    2.  For **each** section of the target with score `k` (in between `0` to `11`), say Alice and Bob have shot `ak` and `bk` arrows on that section respectively. If `ak >= bk`, then Alice takes `k` points. If `ak < bk`, then Bob takes `k` points.
    3.  However, if `ak == bk == 0`, then **nobody** takes `k` points.

*   For example, if Alice and Bob both shot `2` arrows on the section with score `11`, then Alice takes `11` points. On the other hand, if Alice shot `0` arrows on the section with score `11` and Bob shot `2` arrows on that same section, then Bob takes `11` points.

You are given the integer `numArrows` and an integer array `aliceArrows` of size `12`, which represents the number of arrows Alice shot on each scoring section from `0` to `11`. Now, Bob wants to **maximize** the total number of points he can obtain.

Return _the array_ `bobArrows` _which represents the number of arrows Bob shot on **each** scoring section from_ `0` _to_ `11`. The sum of the values in `bobArrows` should equal `numArrows`.

If there are multiple ways for Bob to earn the maximum total points, return **any** one of them.

**Example 1:**

**Input:** numArrows = 9, aliceArrows = \[1,1,0,1,0,0,2,1,0,1,2,0\]
**Output:** \[0,0,0,0,1,1,0,0,1,2,3,1\]
**Explanation:** The table above shows how the competition is scored.
Bob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.
It can be shown that Bob cannot obtain a score higher than 47 points.

**Example 2:**

**Input:** numArrows = 3, aliceArrows = \[0,0,1,0,0,0,0,0,0,0,0,2\]
**Output:** \[0,0,0,0,0,0,0,0,1,1,1,0\]
**Explanation:** The table above shows how the competition is scored.
Bob earns a total point of 8 + 9 + 10 = 27.
It can be shown that Bob cannot obtain a score higher than 27 points.

**Constraints:**

*   `1 <= numArrows <= 105`
*   `aliceArrows.length == bobArrows.length == 12`
*   `0 <= aliceArrows[i], bobArrows[i] <= numArrows`
*   `sum(aliceArrows[i]) == numArrows`

## A solution in Java

```java
public int minDeletions(int[] nums) {
    int n = nums.length;
    if (n <= 2)
        return 0;

    int minIdx = 0, maxIdx = 0;

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

    return Math.min(Math.min(Math.max(minIdx, maxIdx), n - Math.min(minIdx, maxIdx) - 1), minIdx + n - maxIdx - 1);
}
```
First, we check if the array contains 2 or fewer elements. If this is the case, no deletions are needed.

Then, we initialize two variables `min_idx` and `max_idx` to store the indexes of the minimum and maximum elements of the array, respectively. We iterate through the array to find the minimum and maximum element indexes.

Finally, we find the minimum number of deletions needed to remove both the minimum and maximum elements. We consider three possible scenarios:
1. The minimum deletion by taking the maximum index of the minimum and maximum elements.
2. The array length minus the minimum index of the minimum and maximum elements minus 1.
3. The index of the minimum element plus the array length minus the index of the maximum element minus 1.

We return the minimum of these three possible scenarios.

## A solution in C++

```cpp
int min_deletions(vector<int>& nums) {
    int n = nums.size();
    if (n <= 2)
        return 0;

    int min_idx = 0, max_idx = 0;

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

    return min({max(min_idx, max_idx), n - min(min_idx, max_idx) - 1, min_idx + n - max_idx - 1});
}
```
First, we check if the array contains 2 or fewer elements. If this is the case, no deletions are needed.

Then, we initialize two variables `min_idx` and `max_idx` to store the indexes of the minimum and maximum elements of the array, respectively. We iterate through the array to find the minimum and maximum element indexes.

Finally, we find the minimum number of deletions needed to remove both the minimum and maximum elements. We consider three possible scenarios:
1. The minimum deletion by taking the maximum index of the minimum and maximum elements.
2. The array length minus the minimum index of the minimum and maximum elements minus 1.
3. The index of the minimum element plus the array length minus the index of the maximum element minus 1.

We return the minimum of these three possible scenarios.

## A solution in Python

```python
def min_deletions(nums):
    n = len(nums)
    if n <= 2:
        return 0

    min_idx, max_idx = 0, 0

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

    return min(max(min_idx, max_idx), n - min(min_idx, max_idx) - 1, min_idx + n - max_idx - 1)
```
First, we check if the array contains 2 or fewer elements. If this is the case, no deletions are needed.

Then, we initialize two variables `min_idx` and `max_idx` to store the indexes of the minimum and maximum elements of the array, respectively. We iterate through the array to find the minimum and maximum element indexes.

Finally, we find the minimum number of deletions needed to remove both the minimum and maximum elements. We consider three possible scenarios:
1. The minimum deletion by taking the maximum index of the minimum and maximum elements.
2. The array length minus the minimum index of the minimum and maximum elements minus 1.
3. The index of the minimum element plus the array length minus the index of the maximum element minus 1.

We return the minimum of these three possible scenarios.

## A solution in Javascript

```javascript
function minDeletions(nums) {
    let n = nums.length;
    if (n <= 2)
        return 0;

    let minIdx = 0, maxIdx = 0;

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

    return Math.min(Math.min(Math.max(minIdx, maxIdx), n - Math.min(minIdx, maxIdx) - 1), minIdx + n - maxIdx - 1);
}
```
First, we check if the array contains 2 or fewer elements. If this is the case, no deletions are needed.

Then, we initialize two variables `min_idx` and `max_idx` to store the indexes of the minimum and maximum elements of the array, respectively. We iterate through the array to find the minimum and maximum element indexes.

Finally, we find the minimum number of deletions needed to remove both the minimum and maximum elements. We consider three possible scenarios:
1. The minimum deletion by taking the maximum index of the minimum and maximum elements.
2. The array length minus the minimum index of the minimum and maximum elements minus 1.
3. The index of the minimum element plus the array length minus the index of the maximum element minus 1.

We return the minimum of these three possible scenarios.


# Longest Substring of One Repeating Character

- slug: longest-substring-of-one-repeating-character
- difficulty: Hard

You are given a **0-indexed** string `s`. You are also given a **0-indexed** string `queryCharacters` of length `k` and a **0-indexed** array of integer **indices** `queryIndices` of length `k`, both of which are used to describe `k` queries.

The `ith` query updates the character in `s` at index `queryIndices[i]` to the character `queryCharacters[i]`.

Return _an array_ `lengths` _of length_ `k` _where_ `lengths[i]` _is the **length** of the **longest substring** of_ `s` _consisting of **only one repeating** character **after** the_ `ith` _query_ _is performed._

**Example 1:**

**Input:** s =  "babacc ", queryCharacters =  "bcb ", queryIndices = \[1,3,3\]
**Output:** \[3,3,4\]
**Explanation:**
- 1st query updates s =  "b**b**bacc ". The longest substring consisting of one repeating character is  "bbb " with length 3.
- 2nd query updates s =  "bbb**c**cc ".
  The longest substring consisting of one repeating character can be  "bbb " or  "ccc " with length 3.
- 3rd query updates s =  "bbb**b**cc ". The longest substring consisting of one repeating character is  "bbbb " with length 4.
Thus, we return \[3,3,4\].

**Example 2:**

**Input:** s =  "abyzz ", queryCharacters =  "aa ", queryIndices = \[2,1\]
**Output:** \[2,3\]
**Explanation:**
- 1st query updates s =  "ab**a**zz ". The longest substring consisting of one repeating character is  "zz " with length 2.
- 2nd query updates s =  "a**a**azz ". The longest substring consisting of one repeating character is  "aaa " with length 3.
Thus, we return \[2,3\].

**Constraints:**

*   `1 <= s.length <= 105`
*   `s` consists of lowercase English letters.
*   `k == queryCharacters.length == queryIndices.length`
*   `1 <= k <= 105`
*   `queryCharacters` consists of lowercase English letters.
*   `0 <= queryIndices[i] < s.length`

## A solution in Java

```java
import java.util.*;

public List<Integer> peopleWithSecret(int n, int[][] meetings, int firstPerson) {
    Set<Integer> secretHolders = new HashSet<>();
    secretHolders.add(firstPerson);

    int time = 0;
    List<int[]> futureMeetings = new ArrayList<>(Arrays.asList(meetings));
    while (!futureMeetings.isEmpty()) {
        List<int[]> newMeetingList = new ArrayList<>();
        for (int[] meeting : futureMeetings) {
            if (meeting[2] > time) {
                newMeetingList.add(meeting);
                continue;
            }
            if (secretHolders.contains(meeting[0]) || secretHolders.contains(meeting[1])) {
                secretHolders.add(meeting[0]);
                secretHolders.add(meeting[1]);
            }
        }
        time++;
        futureMeetings = newMeetingList;
    }

    return new ArrayList<>(secretHolders);
}
```
The implemented algorithm saves the secret holders in a set called `secretHolders` and initializes it with the `firstPerson`. It then organizes the meetings by time, storing the people who participate in a meeting in a dictionary or an equivalent data structure named `meetingsByTime` where each key is a time `t` and its value is a list of arrays (length 2) that store the people who participate in the meetings at that time.

We iterate through every time step from 0 to n-1. If there are any meetings at that time step, we iterate through the people involved in each meeting. If either person involved in the meeting is in the set `secretHolders`, we add both people to the set. As a result, at each time step, we spread the secret instantly to everyone having meetings with the current secret holders. After completing the loop, we return the final `secretHolders` set as a list.

In all languages, the code first initializes a set or similar data structure for the secret holders and then populates it with the first person. Then, it organizes the meetings based on their respective times. The time steps are then iterated, and for each meeting occurring simultaneously, it updates the secret holder set whenever it encounters a secret holder. Finally, the code returns the secret holders as a list.

## A solution in C++

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

vector<int> peopleWithSecret(int n, vector<vector<int>>& meetings, int firstPerson) {
    unordered_set<int> secretHolders;
    secretHolders.insert(firstPerson);

    for (int time = 0; !meetings.empty(); ++time) {
        vector<vector<int>> future_meetings;
        for (const auto& meeting : meetings) {
            if (meeting[2] > time) {
                future_meetings.push_back(meeting);
                continue;
            }
            if (secretHolders.count(meeting[0]) || secretHolders.count(meeting[1])) {
                secretHolders.insert(meeting[0]);
                secretHolders.insert(meeting[1]);
            }
        }
        meetings = future_meetings;
    }

    return vector<int>(secretHolders.begin(), secretHolders.end());
}
```
The implemented algorithm saves the secret holders in a set called `secretHolders` and initializes it with the `firstPerson`. It then organizes the meetings by time, storing the people who participate in a meeting in a dictionary or an equivalent data structure named `meetingsByTime` where each key is a time `t` and its value is a list of arrays (length 2) that store the people who participate in the meetings at that time.

We iterate through every time step from 0 to n-1. If there are any meetings at that time step, we iterate through the people involved in each meeting. If either person involved in the meeting is in the set `secretHolders`, we add both people to the set. As a result, at each time step, we spread the secret instantly to everyone having meetings with the current secret holders. After completing the loop, we return the final `secretHolders` set as a list.

In all languages, the code first initializes a set or similar data structure for the secret holders and then populates it with the first person. Then, it organizes the meetings based on their respective times. The time steps are then iterated, and for each meeting occurring simultaneously, it updates the secret holder set whenever it encounters a secret holder. Finally, the code returns the secret holders as a list.

## A solution in Python

```python
from collections import defaultdict

def people_with_secret(n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
    secret_holders = set([firstPerson])
    meetings_by_time = defaultdict(list)

    for meeting in meetings:
        meetings_by_time[meeting[2]].append(tuple(meeting[:2]))

    for time in range(n):
        if time in meetings_by_time:
            for x, y in meetings_by_time[time]:
                if x in secret_holders or y in secret_holders:
                    secret_holders.add(x)
                    secret_holders.add(y)

    return list(secret_holders)
```
The implemented algorithm saves the secret holders in a set called `secretHolders` and initializes it with the `firstPerson`. It then organizes the meetings by time, storing the people who participate in a meeting in a dictionary or an equivalent data structure named `meetingsByTime` where each key is a time `t` and its value is a list of arrays (length 2) that store the people who participate in the meetings at that time.

We iterate through every time step from 0 to n-1. If there are any meetings at that time step, we iterate through the people involved in each meeting. If either person involved in the meeting is in the set `secretHolders`, we add both people to the set. As a result, at each time step, we spread the secret instantly to everyone having meetings with the current secret holders. After completing the loop, we return the final `secretHolders` set as a list.

In all languages, the code first initializes a set or similar data structure for the secret holders and then populates it with the first person. Then, it organizes the meetings based on their respective times. The time steps are then iterated, and for each meeting occurring simultaneously, it updates the secret holder set whenever it encounters a secret holder. Finally, the code returns the secret holders as a list.

## A solution in Javascript

```javascript
function peopleWithSecret(n, meetings, firstPerson) {
  const secretHolders = new Set([firstPerson]);

  const meetingsByTime = {};
  for (const meeting of meetings) {
    if (!(meeting[2] in meetingsByTime)) {
      meetingsByTime[meeting[2]] = [];
    }
    meetingsByTime[meeting[2]].push([meeting[0], meeting[1]]);
  }

  for (let time = 0; time < n; time++) {
    if (time in meetingsByTime) {
      for (const [x, y] of meetingsByTime[time]) {
        if (secretHolders.has(x) || secretHolders.has(y)) {
          secretHolders.add(x);
          secretHolders.add(y);
        }
      }
    }
  }

  return Array.from(secretHolders);
}
```
The implemented algorithm saves the secret holders in a set called `secretHolders` and initializes it with the `firstPerson`. It then organizes the meetings by time, storing the people who participate in a meeting in a dictionary or an equivalent data structure named `meetingsByTime` where each key is a time `t` and its value is a list of arrays (length 2) that store the people who participate in the meetings at that time.

We iterate through every time step from 0 to n-1. If there are any meetings at that time step, we iterate through the people involved in each meeting. If either person involved in the meeting is in the set `secretHolders`, we add both people to the set. As a result, at each time step, we spread the secret instantly to everyone having meetings with the current secret holders. After completing the loop, we return the final `secretHolders` set as a list.

In all languages, the code first initializes a set or similar data structure for the secret holders and then populates it with the first person. Then, it organizes the meetings based on their respective times. The time steps are then iterated, and for each meeting occurring simultaneously, it updates the secret holder set whenever it encounters a secret holder. Finally, the code returns the secret holders as a list.


# Minimum Health to Beat Game

- slug: minimum-health-to-beat-game
- difficulty: Medium

You are playing a game that has `n` levels numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `damage` where `damage[i]` is the amount of health you will lose to complete the `ith` level.

You are also given an integer `armor`. You may use your armor ability **at most once** during the game on **any** level which will protect you from **at most** `armor` damage.

You must complete the levels in order and your health must be **greater than** `0` at all times to beat the game.

Return _the **minimum** health you need to start with to beat the game._

**Example 1:**

**Input:** damage = \[2,7,4,3\], armor = 4
**Output:** 13
**Explanation:** One optimal way to beat the game starting at 13 health is:
On round 1, take 2 damage. You have 13 - 2 = 11 health.
On round 2, take 7 damage. You have 11 - 7 = 4 health.
On round 3, use your armor to protect you from 4 damage. You have 4 - 0 = 4 health.
On round 4, take 3 damage. You have 4 - 3 = 1 health.
Note that 13 is the minimum health you need to start with to beat the game.

**Example 2:**

**Input:** damage = \[2,5,3,4\], armor = 7
**Output:** 10
**Explanation:** One optimal way to beat the game starting at 10 health is:
On round 1, take 2 damage. You have 10 - 2 = 8 health.
On round 2, use your armor to protect you from 5 damage. You have 8 - 0 = 8 health.
On round 3, take 3 damage. You have 8 - 3 = 5 health.
On round 4, take 4 damage. You have 5 - 4 = 1 health.
Note that 10 is the minimum health you need to start with to beat the game.

**Example 3:**

**Input:** damage = \[3,3,3\], armor = 0
**Output:** 10
**Explanation:** One optimal way to beat the game starting at 10 health is:
On round 1, take 3 damage. You have 10 - 3 = 7 health.
On round 2, take 3 damage. You have 7 - 3 = 4 health.
On round 3, take 3 damage. You have 4 - 3 = 1 health.
Note that you did not use your armor ability.

**Constraints:**

*   `n == damage.length`
*   `1 <= n <= 105`
*   `0 <= damage[i] <= 105`
*   `0 <= armor <= 105`

## A solution in Java

```java
public int minHealth(int[] damage, int armor) {
    int health = 0;
    for (int i = damage.length - 1; i >= 0; --i) {
        health += damage[i];
        if (health > armor) {
            health -= armor;
            armor = 0;
        }
    }
    return health + 1;
}
```
We will iterate through the damage array in reverse, starting from the last element (i.e., the last level) to compute the minimum health required to complete the game.

In each step, we will add the damage[i] to the health. If the current health is greater than the value of armor, we subtract the armor value from the health and set the armor value to 0 since it can be used only once.

After iterating through all the damage array elements, we add 1 to the health value and return it as the minimum health required to beat the game.

## A solution in C++

```cpp
int min_health(int damage[], int n, int armor) {
    int health = 0;
    for (int i = n - 1; i >= 0; --i) {
        health += damage[i];
        if (health > armor) {
            health -= armor;
            armor = 0;
        }
    }
    return health + 1;
}
```
We will iterate through the damage array in reverse, starting from the last element (i.e., the last level) to compute the minimum health required to complete the game.

In each step, we will add the damage[i] to the health. If the current health is greater than the value of armor, we subtract the armor value from the health and set the armor value to 0 since it can be used only once.

After iterating through all the damage array elements, we add 1 to the health value and return it as the minimum health required to beat the game.

## A solution in Python

```python
def min_health(damage, armor):
    health = 0
    for dmg in reversed(damage):
        health += dmg
        if health > armor:
            health -= armor
            armor = 0
    return health + 1
```
We will iterate through the damage array in reverse, starting from the last element (i.e., the last level) to compute the minimum health required to complete the game.

In each step, we will add the damage[i] to the health. If the current health is greater than the value of armor, we subtract the armor value from the health and set the armor value to 0 since it can be used only once.

After iterating through all the damage array elements, we add 1 to the health value and return it as the minimum health required to beat the game.

## A solution in Javascript

```javascript
function minHealth(damage, armor) {
    let health = 0;
    for (let i = damage.length - 1; i >= 0; --i) {
        health += damage[i];
        if (health > armor) {
            health -= armor;
            armor = 0;
        }
    }
    return health + 1;
}
```
We will iterate through the damage array in reverse, starting from the last element (i.e., the last level) to compute the minimum health required to complete the game.

In each step, we will add the damage[i] to the health. If the current health is greater than the value of armor, we subtract the armor value from the health and set the armor value to 0 since it can be used only once.

After iterating through all the damage array elements, we add 1 to the health value and return it as the minimum health required to beat the game.