# Find the Kth Smallest Sum of a Matrix With Sorted Rows

- slug: find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
- difficulty: Hard

You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`.

You are allowed to choose **exactly one element** from each row to form an array.

Return _the_ `kth` _smallest array sum among all possible arrays_.

**Example 1:**

**Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k = 5
**Output:** 7
**Explanation:** Choosing one element from each row, the first k smallest sum are:
\[1,2\], \[1,4\], \[3,2\], \[3,4\], \[1,6\]. Where the 5th sum is 7.

**Example 2:**

**Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k = 9
**Output:** 17

**Example 3:**

**Input:** mat = \[\[1,10,10\],\[1,4,5\],\[2,3,6\]\], k = 7
**Output:** 9
**Explanation:** Choosing one element from each row, the first k smallest sum are:
\[1,1,2\], \[1,1,3\], \[1,4,2\], \[1,4,3\], \[1,1,6\], \[1,5,2\], \[1,5,3\]. Where the 7th sum is 9.

**Constraints:**

*   `m == mat.length`
*   `n == mat.length[i]`
*   `1 <= m, n <= 40`
*   `1 <= mat[i][j] <= 5000`
*   `1 <= k <= min(200, nm)`
*   `mat[i]` is a non-decreasing array.

## A solution in Java

```java
import java.util.PriorityQueue;

public int kthSmallest(int[][] mat, int k) {
    int m = mat.length, n = mat[0].length;
    PriorityQueue<int[]> minHeap = new PriorityQueue<int[]>((a, b) -> a[0] - b[0]);
    minHeap.offer(new int[]{mat[0][0], 0, 0});

    boolean[][] visited = new boolean[m][n];
    visited[0][0] = true;
    int count = 0;

    while (!minHeap.isEmpty()) {
        int[] cur = minHeap.poll();
        int sum = cur[0], row = cur[1], col = cur[2];

        count++;
        if (count == k) {
            return sum;
        }

        if (row + 1 < m && !visited[row + 1][col]) {
            visited[row + 1][col] = true;
            minHeap.offer(new int[]{sum - mat[row][col] + mat[row + 1][col], row + 1, col});
        }

        if (col + 1 < n && !visited[row][col + 1]) {
            visited[row][col + 1] = true;
            minHeap.offer(new int[]{sum - mat[row][col] + mat[row][col + 1], row, col + 1});
        }
    }

    return -1;
}
```
We can solve this problem using a min-heap. The main idea is as follows:
1. Initialize a min-heap and insert the first element with its coordinates (0, 0).
2. Keep a visited set or 2D boolean array to remember which elements have been inserted into the min-heap. Set the element (0, 0) as visited.
3. Using a loop, pop the smallest element along with its coordinates from the min-heap and increment a counter.
4. If the counter reached k, then return the popped sum.
5. Add the element right below the current element if it is still inside the matrix and is not visited.
6. Add the element right to the current element if it is still inside the matrix and is not visited.
7. During each addition of a new cell, update the visited set or array and add the new sum (subtract the previous matrix element and add the new one) along with its coordinates to the heap.

## A solution in C++

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

int kthSmallest(vector<vector<int>>& mat, int k) {
    int m = mat.size(), n = mat[0].size();
    priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> minHeap;
    minHeap.push({mat[0][0], 0, 0});

    vector<vector<bool>> visited(m, vector<bool>(n, false));
    visited[0][0] = true;
    int count = 0;

    while (!minHeap.empty()) {
        auto cur = minHeap.top();
        minHeap.pop();
        int sum = cur[0], row = cur[1], col = cur[2];

        count++;
        if (count == k) {
            return sum;
        }

        if (row + 1 < m && !visited[row + 1][col]) {
            visited[row + 1][col] = true;
            minHeap.push({sum - mat[row][col] + mat[row + 1][col], row + 1, col});
        }

        if (col + 1 < n && !visited[row][col + 1]) {
            visited[row][col + 1] = true;
            minHeap.push({sum - mat[row][col] + mat[row][col + 1], row, col + 1});
        }
    }

    return -1;
}
```
We can solve this problem using a min-heap. The main idea is as follows:
1. Initialize a min-heap and insert the first element with its coordinates (0, 0).
2. Keep a visited set or 2D boolean array to remember which elements have been inserted into the min-heap. Set the element (0, 0) as visited.
3. Using a loop, pop the smallest element along with its coordinates from the min-heap and increment a counter.
4. If the counter reached k, then return the popped sum.
5. Add the element right below the current element if it is still inside the matrix and is not visited.
6. Add the element right to the current element if it is still inside the matrix and is not visited.
7. During each addition of a new cell, update the visited set or array and add the new sum (subtract the previous matrix element and add the new one) along with its coordinates to the heap.

## A solution in Python

```python
import heapq

def kthSmallest(mat, k):
    m, n = len(mat), len(mat[0])
    minHeap = [(mat[0][0], 0, 0)]

    visited = set([(0, 0)])
    count = 0

    while minHeap:
        cur = heapq.heappop(minHeap)
        sum, row, col = cur

        count += 1
        if count == k:
            return sum

        if row + 1 < m and (row + 1, col) not in visited:
            visited.add((row + 1, col))
            heapq.heappush(minHeap, (sum - mat[row][col] + mat[row + 1][col], row + 1, col))

        if col + 1 < n and (row, col + 1) not in visited:
            visited.add((row, col + 1))
            heapq.heappush(minHeap, (sum - mat[row][col] + mat[row][col + 1], row, col + 1))

    return -1
```
We can solve this problem using a min-heap. The main idea is as follows:
1. Initialize a min-heap and insert the first element with its coordinates (0, 0).
2. Keep a visited set or 2D boolean array to remember which elements have been inserted into the min-heap. Set the element (0, 0) as visited.
3. Using a loop, pop the smallest element along with its coordinates from the min-heap and increment a counter.
4. If the counter reached k, then return the popped sum.
5. Add the element right below the current element if it is still inside the matrix and is not visited.
6. Add the element right to the current element if it is still inside the matrix and is not visited.
7. During each addition of a new cell, update the visited set or array and add the new sum (subtract the previous matrix element and add the new one) along with its coordinates to the heap.

## A solution in Javascript

```javascript
function kthSmallest(mat, k) {
    let m = mat.length, n = mat[0].length;
    let minHeap = new PriorityQueue((a, b) => a[0] - b[0]);
    minHeap.push([mat[0][0], 0, 0]);

    let visited = new Set([0 * n]);
    let count = 0;

    while (minHeap.length) {
        let [sum, row, col] = minHeap.pop();

        count++;
        if (count === k) {
            return sum;
        }

        if (row + 1 < m && !visited.has((row + 1) * n + col)) {
            visited.add((row + 1) * n + col);
            minHeap.push([sum - mat[row][col] + mat[row + 1][col], row + 1, col]);
        }

        if (col + 1 < n && !visited.has(row * n + (col + 1))) {
            visited.add(row * n + (col + 1));
            minHeap.push([sum - mat[row][col] + mat[row][col + 1], row, col + 1]);
        }
    }

    return -1;
}

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

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

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

    pop() {
        const top = this.heap[0];
        const bottom = this.heap.pop();
        if (this.heap.length) {
            this.heap[0] = bottom;
            this._siftDown();
        }
        return top;
    }

    _bubbleUp() {
        let index = this.heap.length - 1;
        const element = this.heap[index];

        while (index > 0) {
            const parentIndex = Math.floor((index - 1) / 2);
            const parent = this.heap[parentIndex];

            if (this.comparator(element, parent) >= 0) break;

            this.heap[index] = parent;
            this.heap[parentIndex] = element;
            index = parentIndex;
        }
    }

    _siftDown() {
        let parentIndex = 0;

        while (true) {
            const leftChildIndex = (parentIndex * 2) + 1;
            const rightChildIndex = (parentIndex * 2) + 2;
            let newIndex = parentIndex;

            if (leftChildIndex < this.heap.length && this.comparator(this.heap[leftChildIndex], this.heap[newIndex]) < 0) {
                newIndex = leftChildIndex;
            }

            if (rightChildIndex < this.heap.length && this.comparator(this.heap[rightChildIndex], this.heap[newIndex]) < 0) {
                newIndex = rightChildIndex;
            }

            if (newIndex === parentIndex) break;

            [this.heap[parentIndex], this.heap[newIndex]] = [this.heap[newIndex], this.heap[parentIndex]];
            parentIndex = newIndex;
        }
    }
}
```
We can solve this problem using a min-heap. The main idea is as follows:
1. Initialize a min-heap and insert the first element with its coordinates (0, 0).
2. Keep a visited set or 2D boolean array to remember which elements have been inserted into the min-heap. Set the element (0, 0) as visited.
3. Using a loop, pop the smallest element along with its coordinates from the min-heap and increment a counter.
4. If the counter reached k, then return the popped sum.
5. Add the element right below the current element if it is still inside the matrix and is not visited.
6. Add the element right to the current element if it is still inside the matrix and is not visited.
7. During each addition of a new cell, update the visited set or array and add the new sum (subtract the previous matrix element and add the new one) along with its coordinates to the heap.


# Build an Array With Stack Operations

- slug: build-an-array-with-stack-operations
- difficulty: Medium

You are given an integer array `target` and an integer `n`.

You have an empty stack with the two following operations:

*   **`"Push "`**: pushes an integer to the top of the stack.
*   **`"Pop "`**: removes the integer on the top of the stack.

You also have a stream of the integers in the range `[1, n]`.

Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to `target`. You should follow the following rules:

*   If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.
*   If the stack is not empty, pop the integer at the top of the stack.
*   If, at any moment, the elements in the stack (from the bottom to the top) are equal to `target`, do not read new integers from the stream and do not do more operations on the stack.

Return _the stack operations needed to build_ `target` following the mentioned rules. If there are multiple valid answers, return **any of them**.

**Example 1:**

**Input:** target = \[1,3\], n = 3
**Output:** \[ "Push ", "Push ", "Pop ", "Push "\]
**Explanation:** Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = \[1\].
Read 2 from the stream and push it to the stack. s = \[1,2\].
Pop the integer on the top of the stack. s = \[1\].
Read 3 from the stream and push it to the stack. s = \[1,3\].

**Example 2:**

**Input:** target = \[1,2,3\], n = 3
**Output:** \[ "Push ", "Push ", "Push "\]
**Explanation:** Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = \[1\].
Read 2 from the stream and push it to the stack. s = \[1,2\].
Read 3 from the stream and push it to the stack. s = \[1,2,3\].

**Example 3:**

**Input:** target = \[1,2\], n = 4
**Output:** \[ "Push ", "Push "\]
**Explanation:** Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = \[1\].
Read 2 from the stream and push it to the stack. s = \[1,2\].
Since the stack (from the bottom to the top) is equal to target, we stop the stack operations.
The answers that read integer 3 from the stream are not accepted.

**Constraints:**

*   `1 <= target.length <= 100`
*   `1 <= n <= 100`
*   `1 <= target[i] <= n`
*   `target` is strictly increasing.

## A solution in Java

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

public List<String> buildArray(int[] target, int n) {
    List<String> result = new ArrayList<>();
    int current = 1;
    for (int num : target) {
        while (current < num) {
            result.add("Push ");
            result.add("Pop ");
            current++;
        }
        result.add("Push ");
        current++;
    }
    return result;
}
```
The algorithm loops through each number in the `target` array. For each number, it loops from the current number in the stream, up to one less than the current number in `target`. In this loop, it appends "Push " and "Pop " to the `result` array, essentially skipping over the numbers we don't want to keep in the stack. It then appends another "Push " to the `result` array for the current number in `target`, as we want to keep it in the stack.

Finally, it increments the current number in the stream and moves on to the next number in `target`. The resulting `result` array will have the operations needed to build the stack.

## A solution in C++

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

std::vector<std::string> buildArray(std::vector<int>& target, int n) {
    std::vector<std::string> result;
    int current = 1;
    for (int num : target) {
        while (current < num) {
            result.push_back("Push ");
            result.push_back("Pop ");
            current++;
        }
        result.push_back("Push ");
        current++;
    }
    return result;
}
```
The algorithm loops through each number in the `target` array. For each number, it loops from the current number in the stream, up to one less than the current number in `target`. In this loop, it appends "Push " and "Pop " to the `result` array, essentially skipping over the numbers we don't want to keep in the stack. It then appends another "Push " to the `result` array for the current number in `target`, as we want to keep it in the stack.

Finally, it increments the current number in the stream and moves on to the next number in `target`. The resulting `result` array will have the operations needed to build the stack.

## A solution in Python

```python
def build_array(target, n):
    result = []
    current = 1
    for num in target:
        while current < num:
            result.append("Push ")
            result.append("Pop ")
            current += 1
        result.append("Push ")
        current += 1
    return result
```
The algorithm loops through each number in the `target` array. For each number, it loops from the current number in the stream, up to one less than the current number in `target`. In this loop, it appends "Push " and "Pop " to the `result` array, essentially skipping over the numbers we don't want to keep in the stack. It then appends another "Push " to the `result` array for the current number in `target`, as we want to keep it in the stack.

Finally, it increments the current number in the stream and moves on to the next number in `target`. The resulting `result` array will have the operations needed to build the stack.

## A solution in Javascript

```javascript
function buildArray(target, n) {
    let result = [];
    let current = 1;
    for (let num of target) {
        while (current < num) {
            result.push("Push ");
            result.push("Pop ");
            current++;
        }
        result.push("Push ");
        current++;
    }
    return result;
}
```
The algorithm loops through each number in the `target` array. For each number, it loops from the current number in the stream, up to one less than the current number in `target`. In this loop, it appends "Push " and "Pop " to the `result` array, essentially skipping over the numbers we don't want to keep in the stack. It then appends another "Push " to the `result` array for the current number in `target`, as we want to keep it in the stack.

Finally, it increments the current number in the stream and moves on to the next number in `target`. The resulting `result` array will have the operations needed to build the stack.


# Count Triplets That Can Form Two Arrays of Equal XOR

- slug: count-triplets-that-can-form-two-arrays-of-equal-xor
- difficulty: Medium

Given an array of integers `arr`.

We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`.

Let's define `a` and `b` as follows:

*   `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]`
*   `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]`

Note that **^** denotes the **bitwise-xor** operation.

Return _the number of triplets_ (`i`, `j` and `k`) Where `a == b`.

**Example 1:**

**Input:** arr = \[2,3,1,6,7\]
**Output:** 4
**Explanation:** The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)

**Example 2:**

**Input:** arr = \[1,1,1,1,1\]
**Output:** 10

**Constraints:**

*   `1 <= arr.length <= 300`
*   `1 <= arr[i] <= 108`

## A solution in Java

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

public int makeConnected(int n, int[][] connections) {
    List<List<Integer>> adjList = new ArrayList<>();
    boolean[] visited = new boolean[n];
    int components = 0, extraEdges = 0;

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

    for (int[] connection : connections) {
        adjList.get(connection[0]).add(connection[1]);
        adjList.get(connection[1]).add(connection[0]);
    }

    for (int i = 0; i < n; i++) {
        if (!visited[i]) {
            components++;
            List<Integer> stack = new ArrayList<>();
            stack.add(i);

            while (!stack.isEmpty()) {
                int current = stack.remove(stack.size() - 1);

                if (!visited[current]) {
                    visited[current] = true;
                    for (int neighbor : adjList.get(current)) {
                        if (!visited[neighbor]) {
                            stack.add(neighbor);
                        } else {
                            extraEdges++;
                        }
                    }
                }
            }
        }
    }

    int extraNeeded = components - 1;

    if (extraEdges >= extraNeeded) {
        return extraNeeded;
    }

    return -1;
}
```
We first build an adjacency list representation of the graph from the given connections. Then we iterate over each computer (node) and perform depth-first search using an iterative approach (using a stack). For every discovered connected component, we increment the `components` counter. When we visit a node during DFS, we check if it has already been visited, and if so, we increment the `extra_edges` counter.

After the loop, we calculate the minimum number of extra edges needed to connect all connected components. Subtracting one from the total number of components will give us the number of additional edges needed to connect them. If we have enough extra edges, we can return the number of extra edges needed; otherwise, we return -1 as it's not possible to connect all computers. ###
End ###

## A solution in C++

```cpp
#include <vector>

int makeConnected(int n, std::vector<std::vector<int>>& connections) {
    std::vector<std::vector<int>> adj_list(n);
    std::vector<bool> visited(n, false);
    int components = 0, extra_edges = 0;

    for (auto& connection : connections) {
        adj_list[connection[0]].push_back(connection[1]);
        adj_list[connection[1]].push_back(connection[0]);
    }

    for (int i = 0; i < n; ++i) {
        if (!visited[i]) {
            components++;
            std::vector<int> stack = {i};

            while (!stack.empty()) {
                int current = stack.back();
                stack.pop_back();

                if (!visited[current]) {
                    visited[current] = true;
                    for (int neighbor : adj_list[current]) {
                        if (!visited[neighbor]) {
                            stack.push_back(neighbor);
                        } else {
                            extra_edges++;
                        }
                    }
                }
            }
        }
    }

    int extra_needed = components - 1;

    if (extra_edges >= extra_needed) {
        return extra_needed;
    }

    return -1;
}
```
We first build an adjacency list representation of the graph from the given connections. Then we iterate over each computer (node) and perform depth-first search using an iterative approach (using a stack). For every discovered connected component, we increment the `components` counter. When we visit a node during DFS, we check if it has already been visited, and if so, we increment the `extra_edges` counter.

After the loop, we calculate the minimum number of extra edges needed to connect all connected components. Subtracting one from the total number of components will give us the number of additional edges needed to connect them. If we have enough extra edges, we can return the number of extra edges needed; otherwise, we return -1 as it's not possible to connect all computers. ###
End ###

## A solution in Python

```python
def make_connected(n, connections):
    adj_list = [[] for _ in range(n)]
    visited = [False] * n
    components = 0
    extra_edges = 0

    for a, b in connections:
        adj_list[a].append(b)
        adj_list[b].append(a)

    for i in range(n):
        if not visited[i]:
            components += 1
            stack = [i]

            while stack:
                current = stack.pop()

                if not visited[current]:
                    visited[current] = True

                    for neighbor in adj_list[current]:
                        if not visited[neighbor]:
                            stack.append(neighbor)
                        else:
                            extra_edges += 1

    extra_needed = components - 1

    if extra_edges >= extra_needed:
        return extra_needed

    return -1
```
We first build an adjacency list representation of the graph from the given connections. Then we iterate over each computer (node) and perform depth-first search using an iterative approach (using a stack). For every discovered connected component, we increment the `components` counter. When we visit a node during DFS, we check if it has already been visited, and if so, we increment the `extra_edges` counter.

After the loop, we calculate the minimum number of extra edges needed to connect all connected components. Subtracting one from the total number of components will give us the number of additional edges needed to connect them. If we have enough extra edges, we can return the number of extra edges needed; otherwise, we return -1 as it's not possible to connect all computers. ###
End ###

## A solution in Javascript

```javascript
function makeConnected(n, connections) {
    const adjList = Array.from({ length: n }, () => []);
    const visited = Array(n).fill(false);
    let components = 0, extraEdges = 0;

    for (const [a, b] of connections) {
        adjList[a].push(b);
        adjList[b].push(a);
    }

    for (let i = 0; i < n; i++) {
        if (!visited[i]) {
            components++;
            const stack = [i];

            while (stack.length) {
                const current = stack.pop();

                if (!visited[current]) {
                    visited[current] = true;

                    for (const neighbor of adjList[current]) {
                        if (!visited[neighbor]) {
                            stack.push(neighbor);
                        } else {
                            extraEdges++;
                        }
                    }
                }
            }
        }
    }

    const extraNeeded = components - 1;

    if (extraEdges >= extraNeeded) {
        return extraNeeded;
    }

    return -1;
}
```
We first build an adjacency list representation of the graph from the given connections. Then we iterate over each computer (node) and perform depth-first search using an iterative approach (using a stack). For every discovered connected component, we increment the `components` counter. When we visit a node during DFS, we check if it has already been visited, and if so, we increment the `extra_edges` counter.

After the loop, we calculate the minimum number of extra edges needed to connect all connected components. Subtracting one from the total number of components will give us the number of additional edges needed to connect them. If we have enough extra edges, we can return the number of extra edges needed; otherwise, we return -1 as it's not possible to connect all computers. ###
End ###


# Minimum Time to Collect All Apples in a Tree

- slug: minimum-time-to-collect-all-apples-in-a-tree
- difficulty: Medium

Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex._

The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`. Additionally, there is a boolean array `hasApple`, where `hasApple[i] = true` means that vertex `i` has an apple; otherwise, it does not have any apple.

**Example 1:**

**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,true,true,false\]
**Output:** 8
**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.

**Example 2:**

**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,false,true,false\]
**Output:** 6
**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.

**Example 3:**

**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,false,false,false,false,false\]
**Output:** 0

**Constraints:**

*   `1 <= n <= 105`
*   `edges.length == n - 1`
*   `edges[i].length == 2`
*   `0 <= ai < bi <= n - 1`
*   `hasApple.length == n`

## A solution in Java

```java
public int minimum_distance(String word) {
    return dp(-1, -1, 0, word);
}

private int dp(int first, int second, int pos, String word) {
    if (pos == word.length()) return 0;

    int ans = 1_000_000_000;
    for (int i : new int[]{first, second}) {
        if (i != -1) {
            int dx = Math.abs(word.charAt(pos) - word.charAt(i)) % 6, dy = Math.abs(word.charAt(pos) - word.charAt(i)) / 6;
            ans = Math.min(ans, Math.min(dx, dy) * 2 + Math.max(dx, dy));
        }
    }
    ans += dp(first, second, pos + 1, word);

    if (first == -1 || second == -1) {
        ans = Math.min(ans, dp(first == -1 ? pos : first, word.charAt(pos), pos + 1, word));
    }

    return ans;
}
```
The problem can be solved using Dynamic Programming. We can start with the positions of the two fingers and the current position in the word. For each position, we try to move one of the two fingers and calculate the minimum distance between the previous position and the current position using the upper and lower bounds of the difference in X and Y coordinates. Then we add this distance to the result of a recursive call with the updated positions and skip the free positions (initial positions of the fingers). We perform these steps until we reach the end of the word. The base case is when we reach the end of the word, we return 0. The final result is the minimum total distance with the given recursion tree.

## A solution in C++

```cpp
#include<cstring>

int dp(int first, int second, int pos, const std::string& word) {
    if (pos == word.size()) return 0;

    int ans = 1e9;
    for (int i : { first, second }) {
        if (i != -1) {
            int dx = abs(word[pos] - word[i]) % 6, dy = abs(word[pos] - word[i]) / 6;
            ans = std::min(ans, min(dx, dy) * 2 + max(dx, dy));
        }
    }
    ans += dp(first, second, pos + 1, word);

    if (first == -1 || second == -1) {
        ans = std::min(ans, dp(first == -1 ? pos : first, word[pos], pos + 1, word));
    }

    return ans;
}

int minimum_distance(const std::string& word) {
    return dp(-1, -1, 0, word);
}
```
The problem can be solved using Dynamic Programming. We can start with the positions of the two fingers and the current position in the word. For each position, we try to move one of the two fingers and calculate the minimum distance between the previous position and the current position using the upper and lower bounds of the difference in X and Y coordinates. Then we add this distance to the result of a recursive call with the updated positions and skip the free positions (initial positions of the fingers). We perform these steps until we reach the end of the word. The base case is when we reach the end of the word, we return 0. The final result is the minimum total distance with the given recursion tree.

## A solution in Python

```python
def minimum_distance(word: str) -> int:
    def dp(first: int, second: int, pos: int) -> int:
        if pos == len(word): return 0

        ans = float('inf')
        for i in [first, second]:
            if i != -1:
                dx = abs(ord(word[pos]) - ord(word[i])) % 6
                dy = abs(ord(word[pos]) - ord(word[i])) // 6
                ans = min(ans, min(dx, dy) * 2 + max(dx, dy))
        ans += dp(first, second, pos + 1)

        if first == -1 or second == -1:
            ans = min(ans, dp(pos if first == -1 else first, ord(word[pos]), pos + 1))

        return ans

    return dp(-1, -1, 0)
```
The problem can be solved using Dynamic Programming. We can start with the positions of the two fingers and the current position in the word. For each position, we try to move one of the two fingers and calculate the minimum distance between the previous position and the current position using the upper and lower bounds of the difference in X and Y coordinates. Then we add this distance to the result of a recursive call with the updated positions and skip the free positions (initial positions of the fingers). We perform these steps until we reach the end of the word. The base case is when we reach the end of the word, we return 0. The final result is the minimum total distance with the given recursion tree.

## A solution in Javascript

```javascript
function minimumDistance(word) {
    return dp(-1, -1, 0 and word);

    function dp(first, second, pos, word) {
        if(pos == word.length) return 0;

        let ans = 1e9;
        for (let i of [first, second]) {
            if (i != -1) {
                let dx = Math.abs(word.charCodeAt(pos) - word.charCodeAt(i)) % 6;
                let dy = Math.abs(word.charCodeAt(pos) - word.charCodeAt(i)) / 6;
                ans = Math.min(ans, Math.min(dx, dy) * 2 + Math.max(dx,  dy));
            }
        }
        ans += dp(first, second, pos + 1, word);

        if (first == -1 || second == -1) {
            ans = Math.min(ans, dp(first == -1 ? pos : first, word.charCodeAt(pos), pos + 1, word ));
        }

        return ans;
    }
}
```
The problem can be solved using Dynamic Programming. We can start with the positions of the two fingers and the current position in the word. For each position, we try to move one of the two fingers and calculate the minimum distance between the previous position and the current position using the upper and lower bounds of the difference in X and Y coordinates. Then we add this distance to the result of a recursive call with the updated positions and skip the free positions (initial positions of the fingers). We perform these steps until we reach the end of the word. The base case is when we reach the end of the word, we return 0. The final result is the minimum total distance with the given recursion tree.


# Number of Ways of Cutting a Pizza

- slug: number-of-ways-of-cutting-a-pizza
- difficulty: Hard

Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts.

For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.

_Return the number of ways of cutting the pizza such that each piece contains **at least** one apple._ Since the answer can be a huge number, return this modulo 10^9 + 7.

**Example 1:**

**Input:** pizza = \[ "A.. ", "AAA ", "... "\], k = 3
**Output:** 3
**Explanation:** The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.

**Example 2:**

**Input:** pizza = \[ "A.. ", "AA. ", "... "\], k = 3
**Output:** 1

**Example 3:**

**Input:** pizza = \[ "A.. ", "A.. ", "... "\], k = 1
**Output:** 1

**Constraints:**

*   `1 <= rows, cols <= 50`
*   `rows == pizza.length`
*   `cols == pizza[i].length`
*   `1 <= k <= 10`
*   `pizza` consists of characters `'A'` and `'.'` only.

## A solution in Java

```java
int numberOfSteps(int num) {
    int steps = 0;
    while (num != 0) {
        steps += (num % 2 == 0) ? 1 : 2;
        num >>= 1;
    }
    return steps - 1;
}
```
The algorithm initializes a `steps` variable to count the number of steps taken. It then iterates through a loop as long as the value of `num` is not zero. Inside the loop, if `num` is even, add one step; if `num` is odd, add two steps (subtracting one, getting an even number, then dividing by 2). The loop uses bit manipulation to divide `num` by 2 (shifting right by 1). Finally, we return the total steps minus one since we considered one extra step when subtracting an odd number.

## A solution in C++

```cpp
int numberOfSteps(int num) {
    int steps = 0;
    while (num) {
        steps += (num % 2 == 0) ? 1 : 2;
        num >>= 1;
    }
    return steps - 1;
}
```
The algorithm initializes a `steps` variable to count the number of steps taken. It then iterates through a loop as long as the value of `num` is not zero. Inside the loop, if `num` is even, add one step; if `num` is odd, add two steps (subtracting one, getting an even number, then dividing by 2). The loop uses bit manipulation to divide `num` by 2 (shifting right by 1). Finally, we return the total steps minus one since we considered one extra step when subtracting an odd number.

## A solution in Python

```python
def number_of_steps(num):
    steps = 0
    while num:
        steps += 1 if num % 2 == 0 else 2
        num >>= 1
    return steps - 1
```
The algorithm initializes a `steps` variable to count the number of steps taken. It then iterates through a loop as long as the value of `num` is not zero. Inside the loop, if `num` is even, add one step; if `num` is odd, add two steps (subtracting one, getting an even number, then dividing by 2). The loop uses bit manipulation to divide `num` by 2 (shifting right by 1). Finally, we return the total steps minus one since we considered one extra step when subtracting an odd number.

## A solution in Javascript

```javascript
function numberOfSteps(num) {
    let steps = 0;
    while (num) {
        steps += (num % 2 === 0) ? 1 : 2;
        num >>= 1;
    }
    return steps - 1;
}
```
The algorithm initializes a `steps` variable to count the number of steps taken. It then iterates through a loop as long as the value of `num` is not zero. Inside the loop, if `num` is even, add one step; if `num` is odd, add two steps (subtracting one, getting an even number, then dividing by 2). The loop uses bit manipulation to divide `num` by 2 (shifting right by 1). Finally, we return the total steps minus one since we considered one extra step when subtracting an odd number.


# Consecutive Characters

- slug: consecutive-characters
- difficulty: Easy

The **power** of the string is the maximum length of a non-empty substring that contains only one unique character.

Given a string `s`, return _the **power** of_ `s`.

**Example 1:**

**Input:** s =  "leetcode "
**Output:** 2
**Explanation:** The substring  "ee " is of length 2 with the character 'e' only.

**Example 2:**

**Input:** s =  "abbcccddddeeeeedcba "
**Output:** 5
**Explanation:** The substring  "eeeee " is of length 5 with the character 'e' only.

**Constraints:**

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

## A solution in Java

```java
double angleClock(int hour, int minutes) {
    double minuteAngle = 6 * minutes;
    double hourAngle = 30 * hour + 0.5 * minutes;
    double angle = Math.abs(hourAngle - minuteAngle);
    return Math.min(angle, 360 - angle);
}
```
Here is the algorithm to find the smaller angle between the hour and the minute hand:

1. Calculate the angle of the minute hand from the 12 o'clock position. Since each minute mark is 6 degrees apart (360/60), multiply the provided minutes by 6 to find the angle.
2. Calculate the angle of the hour hand from the 12 o'clock position. Each hour mark is 30 degrees apart (360/12). Multiply the provided hours by 30, but also add half a degree for each minute passed as the hour hand moves slightly with each passing minute.
3. Find the absolute difference between the hour and minute hand angles.
4. Return the minimum of the calculated angle and 360 minus the calculated angle, as the target angle should always be the smaller angle formed between the clock hands.

## A solution in C++

```cpp
double angleClock(int hour, int minutes) {
    double minuteAngle = 6 * minutes;
    double hourAngle = 30 * hour + 0.5 * minutes;
    double angle = abs(hourAngle - minuteAngle);
    return min(angle, 360 - angle);
}
```
Here is the algorithm to find the smaller angle between the hour and the minute hand:

1. Calculate the angle of the minute hand from the 12 o'clock position. Since each minute mark is 6 degrees apart (360/60), multiply the provided minutes by 6 to find the angle.
2. Calculate the angle of the hour hand from the 12 o'clock position. Each hour mark is 30 degrees apart (360/12). Multiply the provided hours by 30, but also add half a degree for each minute passed as the hour hand moves slightly with each passing minute.
3. Find the absolute difference between the hour and minute hand angles.
4. Return the minimum of the calculated angle and 360 minus the calculated angle, as the target angle should always be the smaller angle formed between the clock hands.

## A solution in Python

```python
def angleClock(hour: int, minutes: int) -> float:
    minute_angle = 6 * minutes
    hour_angle = 30 * hour + 0.5 * minutes
    angle = abs(hour_angle - minute_angle)
    return min(angle, 360 - angle)
```
Here is the algorithm to find the smaller angle between the hour and the minute hand:

1. Calculate the angle of the minute hand from the 12 o'clock position. Since each minute mark is 6 degrees apart (360/60), multiply the provided minutes by 6 to find the angle.
2. Calculate the angle of the hour hand from the 12 o'clock position. Each hour mark is 30 degrees apart (360/12). Multiply the provided hours by 30, but also add half a degree for each minute passed as the hour hand moves slightly with each passing minute.
3. Find the absolute difference between the hour and minute hand angles.
4. Return the minimum of the calculated angle and 360 minus the calculated angle, as the target angle should always be the smaller angle formed between the clock hands.

## A solution in Javascript

```javascript
function angleClock(hour, minutes) {
    let minuteAngle = 6 * minutes;
    let hourAngle = 30 * hour + 0.5 * minutes;
    let angle = Math.abs(hourAngle - minuteAngle);
    return Math.min(angle, 360 - angle);
}
```
Here is the algorithm to find the smaller angle between the hour and the minute hand:

1. Calculate the angle of the minute hand from the 12 o'clock position. Since each minute mark is 6 degrees apart (360/60), multiply the provided minutes by 6 to find the angle.
2. Calculate the angle of the hour hand from the 12 o'clock position. Each hour mark is 30 degrees apart (360/12). Multiply the provided hours by 30, but also add half a degree for each minute passed as the hour hand moves slightly with each passing minute.
3. Find the absolute difference between the hour and minute hand angles.
4. Return the minimum of the calculated angle and 360 minus the calculated angle, as the target angle should always be the smaller angle formed between the clock hands.


# Simplified Fractions

- slug: simplified-fractions
- difficulty: Medium

Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**.

**Example 1:**

**Input:** n = 2
**Output:** \[ "1/2 "\]
**Explanation:**  "1/2 " is the only unique fraction with a denominator less-than-or-equal-to 2.

**Example 2:**

**Input:** n = 3
**Output:** \[ "1/2 ", "1/3 ", "2/3 "\]

**Example 3:**

**Input:** n = 4
**Output:** \[ "1/2 ", "1/3 ", "1/4 ", "2/3 ", "3/4 "\]
**Explanation:**  "2/4 " is not a simplified fraction because it can be simplified to  "1/2 ".

**Constraints:**

*   `1 <= n <= 100`

## A solution in Java

```java
public int minJumps(int[] arr) {
    int n = arr.length;
    int maxReach = arr[0];
    int step = arr[0];
    int jumps = 1;

    if(n == 1) return 0;

    for(int i = 1; i < n; i++) {
        if(i == n - 1) return jumps;

        maxReach = Math.max(maxReach, i + arr[i]);

        step--;

        if(step == 0) {
            jumps++;
            step = maxReach - i;
        }
    }
    return -1;
}
```
The algorithm first checks if the given array has only one element, in which case we're already at the last index and no jumps are needed, returning zero. Then, the algorithm initializes the maximum reach, step, and jumps found so far after evaluating the first element.

While iterating through the array starting at the second element:

- If we've reached the last index, return the current number of jumps.
- Update the maximum reach based on the current index and its corresponding value in the array.
- Decrement the step.
- If the step becomes zero, increment the jumps and set the step to the difference between maximum reach and the current index.

If the loop finishes without finding a way to the last index, return -1 since there's no possible way to reach it.

## A solution in C++

```cpp
int minJumps(vector<int>& arr) {
    int n = arr.size();
    int maxReach = arr[0];
    int step = arr[0];
    int jumps = 1;

    if(n == 1) return 0;

    for(int i = 1; i < n; i++) {
        if(i == n - 1) return jumps;

        maxReach = max(maxReach, i + arr[i]);

        step--;

        if(step == 0) {
            jumps++;
            step = maxReach - i;
        }
    }
    return -1;
}
```
The algorithm first checks if the given array has only one element, in which case we're already at the last index and no jumps are needed, returning zero. Then, the algorithm initializes the maximum reach, step, and jumps found so far after evaluating the first element.

While iterating through the array starting at the second element:

- If we've reached the last index, return the current number of jumps.
- Update the maximum reach based on the current index and its corresponding value in the array.
- Decrement the step.
- If the step becomes zero, increment the jumps and set the step to the difference between maximum reach and the current index.

If the loop finishes without finding a way to the last index, return -1 since there's no possible way to reach it.

## A solution in Python

```python
def minJumps(arr):
    n = len(arr)
    maxReach = arr[0]
    step = arr[0]
    jumps = 1

    if n == 1:
        return 0

    for i in range(1, n):
        if i == n - 1:
            return jumps

        maxReach = max(maxReach, i + arr[i])

        step -= 1

        if step == 0:
            jumps += 1
            step = maxReach - i

    return -1
```
The algorithm first checks if the given array has only one element, in which case we're already at the last index and no jumps are needed, returning zero. Then, the algorithm initializes the maximum reach, step, and jumps found so far after evaluating the first element.

While iterating through the array starting at the second element:

- If we've reached the last index, return the current number of jumps.
- Update the maximum reach based on the current index and its corresponding value in the array.
- Decrement the step.
- If the step becomes zero, increment the jumps and set the step to the difference between maximum reach and the current index.

If the loop finishes without finding a way to the last index, return -1 since there's no possible way to reach it.

## A solution in Javascript

```javascript
function minJumps(arr) {
    let n = arr.length;
    let maxReach = arr[0];
    let step = arr[0];
    let jumps = 1;

    if(n === 1) return 0;

    for(let i = 1; i < n; i++) {
        if(i === n - 1) return jumps;

        maxReach = Math.max(maxReach, i + arr[i]);

        step--;

        if(step === 0) {
            jumps++;
            step = maxReach - i;
        }
    }
    return -1;
}
```
The algorithm first checks if the given array has only one element, in which case we're already at the last index and no jumps are needed, returning zero. Then, the algorithm initializes the maximum reach, step, and jumps found so far after evaluating the first element.

While iterating through the array starting at the second element:

- If we've reached the last index, return the current number of jumps.
- Update the maximum reach based on the current index and its corresponding value in the array.
- Decrement the step.
- If the step becomes zero, increment the jumps and set the step to the difference between maximum reach and the current index.

If the loop finishes without finding a way to the last index, return -1 since there's no possible way to reach it.


# Count Good Nodes in Binary Tree

- slug: count-good-nodes-in-binary-tree
- difficulty: Medium

Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X.

Return the number of **good** nodes in the binary tree.

**Example 1:**

**Input:** root = \[3,1,4,3,null,1,5\]
**Output:** 4
**Explanation:** Nodes in blue are **good**.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.

**Example 2:**

**Input:** root = \[3,3,null,4,2\]
**Output:** 3
**Explanation:** Node 2 -> (3, 3, 2) is not good, because  "3 " is higher than it.

**Example 3:**

**Input:** root = \[1\]
**Output:** 1
**Explanation:** Root is considered as **good**.

**Constraints:**

*   The number of nodes in the binary tree is in the range `[1, 10^5]`.
*   Each node's value is between `[-10^4, 10^4]`.

## A solution in Java

```java
public int maximum69Number(int num) {
    String numStr = Integer.toString(num);
    char[] numChars = numStr.toCharArray();
    for (int i = 0; i < numChars.length; i++) {
        if (numChars[i] == '6') {
            numChars[i] = '9';
            break;
        }
    }
    return Integer.parseInt(new String(numChars));
}
```
1. Convert the integer `num` into a string (or list of characters for Python).
2. Iterate through the characters of the string (or list).
3. When encountering the first '6', replace it with '9' and break out of the loop.
4. Convert the modified string (or list) back into an integer and return it.

## A solution in C++

```cpp
int maximum69Number(int num) {
    string num_str = to_string(num);
    for (char &c : num_str) {
        if (c == '6') {
            c = '9';
            break;
        }
    }
    return stoi(num_str);
}
```
1. Convert the integer `num` into a string (or list of characters for Python).
2. Iterate through the characters of the string (or list).
3. When encountering the first '6', replace it with '9' and break out of the loop.
4. Convert the modified string (or list) back into an integer and return it.

## A solution in Python

```python
def maximum69Number(num: int) -> int:
    num_str = list(str(num))
    for i, c in enumerate(num_str):
        if c == '6':
            num_str[i] = '9'
            break
    return int(''.join(num_str))
```
1. Convert the integer `num` into a string (or list of characters for Python).
2. Iterate through the characters of the string (or list).
3. When encountering the first '6', replace it with '9' and break out of the loop.
4. Convert the modified string (or list) back into an integer and return it.

## A solution in Javascript

```javascript
function maximum69Number(num) {
    let numStr = num.toString();
    let numChars = numStr.split("");
    for (let i = 0; i < numChars.length; i++) {
        if (numChars[i] === "6") {
            numChars[i] = "9";
            break;
        }
    }
    return parseInt(numChars.join(""));
}
```
1. Convert the integer `num` into a string (or list of characters for Python).
2. Iterate through the characters of the string (or list).
3. When encountering the first '6', replace it with '9' and break out of the loop.
4. Convert the modified string (or list) back into an integer and return it.


# Form Largest Integer With Digits That Add up to Target

- slug: form-largest-integer-with-digits-that-add-up-to-target
- difficulty: Hard

Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_:

*   The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**).
*   The total cost used must be equal to `target`.
*   The integer does not have `0` digits.

Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return `"0 "`.

**Example 1:**

**Input:** cost = \[4,3,2,5,6,7,2,5,5\], target = 9
**Output:**  "7772 "
**Explanation:** The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost( "7772 ") = 2\*3+ 3\*1 = 9. You could also paint  "977 ", but  "7772 " is the largest number.
**Digit    cost**
  1  ->   4
  2  ->   3
  3  ->   2
  4  ->   5
  5  ->   6
  6  ->   7
  7  ->   2
  8  ->   5
  9  ->   5

**Example 2:**

**Input:** cost = \[7,6,5,5,5,6,8,7,8\], target = 12
**Output:**  "85 "
**Explanation:** The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost( "85 ") = 7 + 5 = 12.

**Example 3:**

**Input:** cost = \[2,4,6,2,4,6,4,4,4\], target = 5
**Output:**  "0 "
**Explanation:** It is impossible to paint any integer with total cost equal to target.

**Constraints:**

*   `cost.length == 9`
*   `1 <= cost[i], target <= 5000`

## A solution in Java

```java
public String largestNumber(int[] cost, int target) {
    String[] dp = new String[target + 1];
    dp[0] = "";

    for (int i = 0; i < 9; ++i) {
        for (int j = cost[i]; j <= target; ++j) {
            if (dp[j - cost[i]] != null && dp[j - cost[i]].length() < j - cost[i]
                    && (dp[j] == null || dp[j - cost[i]].length() + 1 > dp[j].length())) {
                dp[j] = dp[j - cost[i]] + (char) ('1' + i);
            }
        }
    }

    return dp[target] == null ? "0" : dp[target];
}
```
To solve this problem, we use a dynamic programming approach. We create an array `dp` where `dp[i]` keeps the maximum integer using the total cost `i`. To find the value of `dp[i]`, we keep track of the maximum integer up to the cost `i - cost[j]` for each of the paint costs and add the digit `j + 1`. Then, we compare the lengths of the integers at `dp[i - cost[j]]` and `dp[i]` to determine which one generates the maximum integer. At the end, we return `dp[target]`. If there is no solution, the default value will be an empty string which is changed to "0" before returning.

## A solution in C++

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

std::string largestNumber(std::vector<int>& cost, int target) {
    std::vector<std::string> dp(target + 1, "");

    for (int i = 0; i < 9; ++i) {
        for (int j = cost[i]; j <= target; ++j) {
            if (dp[j - cost[i]].size() < j - cost[i] && dp[j - cost[i]].size() + 1 > dp[j].size()) {
                dp[j] = dp[j - cost[i]] + std::to_string(i + 1);
            }
        }
    }

    return dp[target].empty() ? "0" : dp[target];
}
```
To solve this problem, we use a dynamic programming approach. We create an array `dp` where `dp[i]` keeps the maximum integer using the total cost `i`. To find the value of `dp[i]`, we keep track of the maximum integer up to the cost `i - cost[j]` for each of the paint costs and add the digit `j + 1`. Then, we compare the lengths of the integers at `dp[i - cost[j]]` and `dp[i]` to determine which one generates the maximum integer. At the end, we return `dp[target]`. If there is no solution, the default value will be an empty string which is changed to "0" before returning.

## A solution in Python

```python
def largestNumber(cost, target):
    dp = ["" for _ in range(target + 1)]
    dp[0] = ""

    for i in range(9):
        for j in range(cost[i], target + 1):
            if dp[j - cost[i]] != None and len(dp[j - cost[i]]) < j - cost[i] \
               and (dp[j] == None or len(dp[j - cost[i]]) + 1 > len(dp[j])):
                dp[j] = dp[j - cost[i]] + str(i + 1)

    return dp[target] if dp[target] else "0"
```
To solve this problem, we use a dynamic programming approach. We create an array `dp` where `dp[i]` keeps the maximum integer using the total cost `i`. To find the value of `dp[i]`, we keep track of the maximum integer up to the cost `i - cost[j]` for each of the paint costs and add the digit `j + 1`. Then, we compare the lengths of the integers at `dp[i - cost[j]]` and `dp[i]` to determine which one generates the maximum integer. At the end, we return `dp[target]`. If there is no solution, the default value will be an empty string which is changed to "0" before returning.

## A solution in Javascript

```javascript
function largestNumber(cost, target) {
    const dp = new Array(target + 1).fill("");
    dp[0] = "";

    for (let i = 0; i < 9; ++i) {
        for (let j = cost[i]; j <= target; ++j) {
            if (dp[j - cost[i]].length < j - cost[i] && dp[j - cost[i]].length + 1 > dp[j].length) {
                dp[j] = dp[j - cost[i]] + (i + 1).toString();
            }
        }
    }

    return dp[target] || "0";
}
```
To solve this problem, we use a dynamic programming approach. We create an array `dp` where `dp[i]` keeps the maximum integer using the total cost `i`. To find the value of `dp[i]`, we keep track of the maximum integer up to the cost `i - cost[j]` for each of the paint costs and add the digit `j + 1`. Then, we compare the lengths of the integers at `dp[i - cost[j]]` and `dp[i]` to determine which one generates the maximum integer. At the end, we return `dp[target]`. If there is no solution, the default value will be an empty string which is changed to "0" before returning.


# Number of Students Doing Homework at a Given Time

- slug: number-of-students-doing-homework-at-a-given-time
- difficulty: Easy

Given two integer arrays `startTime` and `endTime` and given an integer `queryTime`.

The `ith` student started doing their homework at the time `startTime[i]` and finished it at time `endTime[i]`.

Return _the number of students_ doing their homework at time `queryTime`. More formally, return the number of students where `queryTime` lays in the interval `[startTime[i], endTime[i]]` inclusive.

**Example 1:**

**Input:** startTime = \[1,2,3\], endTime = \[3,2,7\], queryTime = 4
**Output:** 1
**Explanation:** We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.

**Example 2:**

**Input:** startTime = \[4\], endTime = \[4\], queryTime = 4
**Output:** 1
**Explanation:** The only student was doing their homework at the queryTime.

**Constraints:**

*   `startTime.length == endTime.length`
*   `1 <= startTime.length <= 100`
*   `1 <= startTime[i] <= endTime[i] <= 1000`
*   `1 <= queryTime <= 1000`

## A solution in Java

```java
public TreeNode removeLeafNodes(TreeNode root, int target) {
    if (root == null) return null;
    root.left = removeLeafNodes(root.left, target);
    root.right = removeLeafNodes(root.right, target);
    if (root.left == null && root.right == null && root.val == target) {
        return null;
    }
    return root;
}
```
We traverse the binary tree using a depth-first search (DFS) approach. We use a recursion to visit left and right children of each node.

1. If the root node is null, return null.
2. Call `removeLeafNodes` recursively and update left and right children.
3. After updating children, check if the current node is a leaf node (i.e., both children are null) and its value equals the target. If so, delete it (return null); otherwise, return the current node.
4. Repeat this process until deleted leaf nodes can no longer create new leaf nodes with the target value.

## A solution in C++

```cpp
TreeNode* removeLeafNodes(TreeNode* root, int target) {
    if (!root) return nullptr;
    root->left = removeLeafNodes(root->left, target);
    root->right = removeLeafNodes(root->right, target);
    if (!root->left && !root->right && root->val == target) {
        return nullptr;
    }
    return root;
}
```
We traverse the binary tree using a depth-first search (DFS) approach. We use a recursion to visit left and right children of each node.

1. If the root node is null, return null.
2. Call `removeLeafNodes` recursively and update left and right children.
3. After updating children, check if the current node is a leaf node (i.e., both children are null) and its value equals the target. If so, delete it (return null); otherwise, return the current node.
4. Repeat this process until deleted leaf nodes can no longer create new leaf nodes with the target value.

## A solution in Python

```python
def removeLeafNodes(root, target):
    if not root:
        return None
    root.left = removeLeafNodes(root.left, target)
    root.right = removeLeafNodes(root.right, target)
    if not root.left and not root.right and root.val == target:
        return None
    return root
```
We traverse the binary tree using a depth-first search (DFS) approach. We use a recursion to visit left and right children of each node.

1. If the root node is null, return null.
2. Call `removeLeafNodes` recursively and update left and right children.
3. After updating children, check if the current node is a leaf node (i.e., both children are null) and its value equals the target. If so, delete it (return null); otherwise, return the current node.
4. Repeat this process until deleted leaf nodes can no longer create new leaf nodes with the target value.

## A solution in Javascript

```javascript
function removeLeafNodes(root, target) {
    if (!root) return null;
    root.left = removeLeafNodes(root.left, target);
    root.right = removeLeafNodes(root.right, target);
    if (!root.left && !root.right && root.val === target) {
        return null;
    }
    return root;
}
```
We traverse the binary tree using a depth-first search (DFS) approach. We use a recursion to visit left and right children of each node.

1. If the root node is null, return null.
2. Call `removeLeafNodes` recursively and update left and right children.
3. After updating children, check if the current node is a leaf node (i.e., both children are null) and its value equals the target. If so, delete it (return null); otherwise, return the current node.
4. Repeat this process until deleted leaf nodes can no longer create new leaf nodes with the target value.


# Rearrange Words in a Sentence

- slug: rearrange-words-in-a-sentence
- difficulty: Medium

Given a sentence `text` (A _sentence_ is a string of space-separated words) in the following format:

*   First letter is in upper case.
*   Each word in `text` are separated by a single space.

Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.

Return the new text following the format shown above.

**Example 1:**

**Input:** text =  "Leetcode is cool "
**Output:**  "Is cool leetcode "
**Explanation:** There are 3 words,  "Leetcode " of length 8,  "is " of length 2 and  "cool " of length 4.
Output is ordered by length and the new first word starts with capital letter.

**Example 2:**

**Input:** text =  "Keep calm and code on "
**Output:**  "On and keep calm code "
**Explanation:** Output is ordered as follows:
 "On " 2 letters.
 "and " 3 letters.
 "keep " 4 letters in case of tie order by position in original text.
 "calm " 4 letters.
 "code " 4 letters.

**Example 3:**

**Input:** text =  "To be or not to be "
**Output:**  "To be or to be not "

**Constraints:**

*   `text` begins with a capital letter and then contains lowercase letters and single space between words.
*   `1 <= text.length <= 10^5`

## A solution in Java

```java
public int minTaps(int n, int[] ranges) {
    int[] intervals = new int[n + 1];
    for (int i = 0; i <= n; i++) {
        int left = Math.max(0, i - ranges[i]);
        int right = Math.min(n, i + ranges[i]);
        intervals[left] = Math.max(intervals[left], right - left);
    }

    int position = 0, total_taps = 0, max_reach = 0;
    while (position < n) {
        max_reach = Math.max(max_reach, position + intervals[position]);
        if (max_reach == position) return -1;
        position = max_reach;
        total_taps++;
    }
    return total_taps;
}
```
The algorithm uses a greedy approach to identify the minimum number of taps needed to water the whole garden.

1. Create an array named `intervals` to store the maximum interval that can be covered by each tap.
2. Iterate through the `ranges` array, for each tap, calculate the leftmost and rightmost points it can cover. Update the `intervals` array accordingly.
3. Initialize variables `position`, `total_taps`, and `max_reach` to 0.
4. While the `position` is less than `n`, update `max_reach` to the maximum covered area at the current position.
5. If the `max_reach` is equal to the current `position`, it means the garden cannot be watered, thus return -1.
6. Otherwise, update the `position` to the value of `max_reach` and increment the counter `total_taps`.
7. After the loop ends, return the value of `total_taps` as the minimum number of taps needed.

This algorithm has a time complexity of O(n) as it iterates through the array once and updates the counters greedily.

## A solution in C++

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

int minTaps(int n, std::vector<int>& ranges) {
    std::vector<int> intervals(n + 1, 0);
    for (int i = 0; i <= n; ++i) {
        int left = std::max(0, i - ranges[i]);
        int right = std::min(n, i + ranges[i]);
        intervals[left] = std::max(intervals[left], right - left);
    }

    int position = 0, total_taps = 0, max_reach = 0;
    while (position < n) {
        max_reach = std::max(max_reach, position + intervals[position]);
        if (max_reach == position) return -1;
        position = max_reach;
        ++total_taps;
    }
    return total_taps;
}
```
The algorithm uses a greedy approach to identify the minimum number of taps needed to water the whole garden.

1. Create an array named `intervals` to store the maximum interval that can be covered by each tap.
2. Iterate through the `ranges` array, for each tap, calculate the leftmost and rightmost points it can cover. Update the `intervals` array accordingly.
3. Initialize variables `position`, `total_taps`, and `max_reach` to 0.
4. While the `position` is less than `n`, update `max_reach` to the maximum covered area at the current position.
5. If the `max_reach` is equal to the current `position`, it means the garden cannot be watered, thus return -1.
6. Otherwise, update the `position` to the value of `max_reach` and increment the counter `total_taps`.
7. After the loop ends, return the value of `total_taps` as the minimum number of taps needed.

This algorithm has a time complexity of O(n) as it iterates through the array once and updates the counters greedily.

## A solution in Python

```python
def min_taps(n, ranges):
    intervals = [0] * (n + 1)
    for i in range(n + 1):
        left = max(0, i - ranges[i])
        right = min(n, i + ranges[i])
        intervals[left] = max(intervals[left], right - left)

    position, total_taps, max_reach = 0, 0, 0
    while position < n:
        max_reach = max(max_reach, position + intervals[position])
        if max_reach == position:
            return -1
        position = max_reach
        total_taps += 1

    return total_taps
```
The algorithm uses a greedy approach to identify the minimum number of taps needed to water the whole garden.

1. Create an array named `intervals` to store the maximum interval that can be covered by each tap.
2. Iterate through the `ranges` array, for each tap, calculate the leftmost and rightmost points it can cover. Update the `intervals` array accordingly.
3. Initialize variables `position`, `total_taps`, and `max_reach` to 0.
4. While the `position` is less than `n`, update `max_reach` to the maximum covered area at the current position.
5. If the `max_reach` is equal to the current `position`, it means the garden cannot be watered, thus return -1.
6. Otherwise, update the `position` to the value of `max_reach` and increment the counter `total_taps`.
7. After the loop ends, return the value of `total_taps` as the minimum number of taps needed.

This algorithm has a time complexity of O(n) as it iterates through the array once and updates the counters greedily.

## A solution in Javascript

```javascript
function minTaps(n, ranges) {
    let intervals = new Array(n + 1).fill(0);
    for (let i = 0; i <= n; i++) {
        let left = Math.max(0, i - ranges[i]);
        let right = Math.min(n, i + ranges[i]);
        intervals[left] = Math.max(intervals[left], right - left);
    }

    let position = 0, total_taps = 0, max_reach = 0;
    while (position < n) {
        max_reach = Math.max(max_reach, position + intervals[position]);
        if (max_reach == position) return -1;
        position = max_reach;
        total_taps++;
    }
    return total_taps;
}
```
The algorithm uses a greedy approach to identify the minimum number of taps needed to water the whole garden.

1. Create an array named `intervals` to store the maximum interval that can be covered by each tap.
2. Iterate through the `ranges` array, for each tap, calculate the leftmost and rightmost points it can cover. Update the `intervals` array accordingly.
3. Initialize variables `position`, `total_taps`, and `max_reach` to 0.
4. While the `position` is less than `n`, update `max_reach` to the maximum covered area at the current position.
5. If the `max_reach` is equal to the current `position`, it means the garden cannot be watered, thus return -1.
6. Otherwise, update the `position` to the value of `max_reach` and increment the counter `total_taps`.
7. After the loop ends, return the value of `total_taps` as the minimum number of taps needed.

This algorithm has a time complexity of O(n) as it iterates through the array once and updates the counters greedily.


# People Whose List of Favorite Companies Is Not a Subset of Another List

- slug: people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list
- difficulty: Medium

Given the array `favoriteCompanies` where `favoriteCompanies[i]` is the list of favorites companies for the `ith` person (**indexed from 0**).

_Return the indices of people whose list of favorite companies is not a **subset** of any other list of favorites companies_. You must return the indices in increasing order.

**Example 1:**

**Input:** favoriteCompanies = \[\[ "leetcode ", "google ", "facebook "\],\[ "google ", "microsoft "\],\[ "google ", "facebook "\],\[ "google "\],\[ "amazon "\]\]
**Output:** \[0,1,4\]
**Explanation:**
Person with index=2 has favoriteCompanies\[2\]=\[ "google ", "facebook "\] which is a subset of favoriteCompanies\[0\]=\[ "leetcode ", "google ", "facebook "\] corresponding to the person with index 0.
Person with index=3 has favoriteCompanies\[3\]=\[ "google "\] which is a subset of favoriteCompanies\[0\]=\[ "leetcode ", "google ", "facebook "\] and favoriteCompanies\[1\]=\[ "google ", "microsoft "\].
Other lists of favorite companies are not a subset of another list, therefore, the answer is \[0,1,4\].

**Example 2:**

**Input:** favoriteCompanies = \[\[ "leetcode ", "google ", "facebook "\],\[ "leetcode ", "amazon "\],\[ "facebook ", "google "\]\]
**Output:** \[0,1\]
**Explanation:** In this case favoriteCompanies\[2\]=\[ "facebook ", "google "\] is a subset of favoriteCompanies\[0\]=\[ "leetcode ", "google ", "facebook "\], therefore, the answer is \[0,1\].

**Example 3:**

**Input:** favoriteCompanies = \[\[ "leetcode "\],\[ "google "\],\[ "facebook "\],\[ "amazon "\]\]
**Output:** \[0,1,2,3\]

**Constraints:**

*   `1 <= favoriteCompanies.length <= 100`
*   `1 <= favoriteCompanies[i].length <= 500`
*   `1 <= favoriteCompanies[i][j].length <= 20`
*   All strings in `favoriteCompanies[i]` are **distinct**.
*   All lists of favorite companies are **distinct**, that is, If we sort alphabetically each list then `favoriteCompanies[i] != favoriteCompanies[j].`
*   All strings consist of lowercase English letters only.

## A solution in Java

```java
import java.util.*;

class Solution {
    public List<Integer> peopleIndexes(List<List<String>> favoriteCompanies) {
        List<Integer> result = new ArrayList<>();
        List<Set<String>> companySets = new ArrayList<>();

        for (List<String> companies : favoriteCompanies) {
            companySets.add(new HashSet<String>(companies));
        }

        for (int i = 0; i < companySets.size(); ++i) {
            boolean isSubset = false;
            for (int j = 0; j < companySets.size(); ++j) {
                if (i != j && companySets.get(j).containsAll(companySets.get(i))) {
                    isSubset = true;
                    break;
                }
            }
            if (!isSubset) result.add(i);
        }

        return result;
    }
}
```
The algorithm first converts the favoriteCompanies array of lists to an array of sets (for faster lookups).
Then, for each list, iterate through the lists again to find if there's any list that contains all the favorite companies of the current list. If it's a subset of any other list, then continue to the next list without adding the current index to the result. If it's not a subset of any other list, append the index to the result.

## A solution in C++

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

vector<int> peopleIndexes(vector<vector<string>>& favoriteCompanies) {
    vector<int> result;
    vector<set<string>> companySets;

    for (const auto& companies : favoriteCompanies) {
        companySets.push_back(set<string>(companies.begin(), companies.end()));
    }

    for (int i = 0; i < companySets.size(); ++i) {
        bool isSubset = false;
        for (int j = 0; j < companySets.size(); ++j) {
            if (i != j && includes(companySets[j].begin(), companySets[j].end(),
                                    companySets[i].begin(), companySets[i].end())) {
                isSubset = true;
                break;
            }
        }
        if (!isSubset) result.push_back(i);
    }

    return result;
}
```
The algorithm first converts the favoriteCompanies array of lists to an array of sets (for faster lookups).
Then, for each list, iterate through the lists again to find if there's any list that contains all the favorite companies of the current list. If it's a subset of any other list, then continue to the next list without adding the current index to the result. If it's not a subset of any other list, append the index to the result.

## A solution in Python

```python
from typing import List

def peopleIndexes(favoriteCompanies: List[List[str]]) -> List[int]:
    result = []
    companySets = [set(companies) for companies in favoriteCompanies]

    for i, companies in enumerate(companySets):
        isSubset = False
        for j, otherCompanies in enumerate(companySets):
            if i != j and companies.issubset(otherCompanies):
                isSubset = True
                break
        if not isSubset:
            result.append(i)

    return result
```
The algorithm first converts the favoriteCompanies array of lists to an array of sets (for faster lookups).
Then, for each list, iterate through the lists again to find if there's any list that contains all the favorite companies of the current list. If it's a subset of any other list, then continue to the next list without adding the current index to the result. If it's not a subset of any other list, append the index to the result.

## A solution in Javascript

```javascript
var peopleIndexes = function(favoriteCompanies) {
    const result = [];
    const companySets = favoriteCompanies.map(companies => new Set(companies));

    for (let i = 0; i < companySets.length; ++i) {
        let isSubset = false;
        for (let j = 0; j < companySets.length; ++j) {
            if (i !== j && isSubsetOf(companySets[i], companySets[j])) {
                isSubset = true;
                break;
            }
        }
        if (!isSubset) result.push(i);
    }

    return result;
};

function isSubsetOf(setA, setB) {
    for (let elem of setA) {
        if (!setB.has(elem)) return false;
    }
    return true;
}
```
The algorithm first converts the favoriteCompanies array of lists to an array of sets (for faster lookups).
Then, for each list, iterate through the lists again to find if there's any list that contains all the favorite companies of the current list. If it's a subset of any other list, then continue to the next list without adding the current index to the result. If it's not a subset of any other list, append the index to the result.


# Maximum Number of Darts Inside of a Circular Dartboard

- slug: maximum-number-of-darts-inside-of-a-circular-dartboard
- difficulty: Hard

Alice is throwing `n` darts on a very large wall. You are given an array `darts` where `darts[i] = [xi, yi]` is the position of the `ith` dart that Alice threw on the wall.

Bob knows the positions of the `n` darts on the wall. He wants to place a dartboard of radius `r` on the wall so that the maximum number of darts that Alice throws lies on the dartboard.

Given the integer `r`, return _the maximum number of darts that can lie on the dartboard_.

**Example 1:**

**Input:** darts = \[\[-2,0\],\[2,0\],\[0,2\],\[0,-2\]\], r = 2
**Output:** 4
**Explanation:** Circle dartboard with center in (0,0) and radius = 2 contain all points.

**Example 2:**

**Input:** darts = \[\[-3,0\],\[3,0\],\[2,6\],\[5,4\],\[0,9\],\[7,8\]\], r = 5
**Output:** 5
**Explanation:** Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).

**Constraints:**

*   `1 <= darts.length <= 100`
*   `darts[i].length == 2`
*   `-104 <= xi, yi <= 104`
*   All the `darts` are unique
*   `1 <= r <= 5000`

## A solution in Java

```java
import java.util.List;

public int numPoints(List<List<Integer>> darts, int r) {
    int n = darts.size();
    int result = 1;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            int cnt = 0;
            for (int k = 0; k < n; ++k) {
                int dx = darts.get(i).get(0) - darts.get(k).get(0);
                int dy = darts.get(i).get(1) - darts.get(k).get(1);
                if (Math.sqrt(dx * dx + dy * dy) <= r) cnt++;
            }

            if (cnt > result) result = cnt;
        }
    }
    return result;
}
```
The algorithm is fairly straightforward. We iterate through all pairs of darts and try to place the dartboard center on each pair. Then, for each pair of darts, we check how many darts are within the distance `r` from both darts in the pair. The answer is the maximum count of darts that can be covered by the dartboard for all pairs of darts.

The time complexity of the algorithm is O(n^3), where n is the number of darts. In the worst case, there can be up to 100 darts, so the algorithm will be fast enough.

## A solution in C++

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

int numPoints(std::vector<std::vector<int>>& darts, int r) {
    int n = darts.size();
    int result = 1;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            int cnt = 0;
            for (int k = 0; k < n; ++k) {
                int dx = darts[i][0] - darts[k][0];
                int dy = darts[i][1] - darts[k][1];
                if (sqrt(dx * dx + dy * dy) <= r) cnt++;
            }

            if (cnt > result) result = cnt;
        }
    }
    return result;
}
```
The algorithm is fairly straightforward. We iterate through all pairs of darts and try to place the dartboard center on each pair. Then, for each pair of darts, we check how many darts are within the distance `r` from both darts in the pair. The answer is the maximum count of darts that can be covered by the dartboard for all pairs of darts.

The time complexity of the algorithm is O(n^3), where n is the number of darts. In the worst case, there can be up to 100 darts, so the algorithm will be fast enough.

## A solution in Python

```python
def numPoints(darts, r):
    n = len(darts)
    result = 1

    for i in range(n):
        for j in range(n):
            cnt = 0
            for k in range(n):
                dx = darts[i][0] - darts[k][0]
                dy = darts[i][1] - darts[k][1]
                if (dx * dx + dy * dy) ** 0.5 <= r:
                    cnt += 1

            if cnt > result:
                result = cnt

    return result
```
The algorithm is fairly straightforward. We iterate through all pairs of darts and try to place the dartboard center on each pair. Then, for each pair of darts, we check how many darts are within the distance `r` from both darts in the pair. The answer is the maximum count of darts that can be covered by the dartboard for all pairs of darts.

The time complexity of the algorithm is O(n^3), where n is the number of darts. In the worst case, there can be up to 100 darts, so the algorithm will be fast enough.

## A solution in Javascript

```javascript
function numPoints(darts, r) {
    const n = darts.length;
    let result = 1;

    for (let i = 0; i < n; ++i) {
        for (let j = 0; j < n; ++j) {
            let cnt = 0;
            for (let k = 0; k < n; ++k) {
                const dx = darts[i][0] - darts[k][0];
                const dy = darts[i][1] - darts[k][1];
                if (Math.sqrt(dx * dx + dy * dy) <= r) cnt++;
            }

            if (cnt > result) result = cnt;
        }
    }
    return result;
}
```
The algorithm is fairly straightforward. We iterate through all pairs of darts and try to place the dartboard center on each pair. Then, for each pair of darts, we check how many darts are within the distance `r` from both darts in the pair. The answer is the maximum count of darts that can be covered by the dartboard for all pairs of darts.

The time complexity of the algorithm is O(n^3), where n is the number of darts. In the worst case, there can be up to 100 darts, so the algorithm will be fast enough.


# Check If a Word Occurs As a Prefix of Any Word in a Sentence

- slug: check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence
- difficulty: Easy

Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`.

Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one word, return the index of the first word **(minimum index)**. If there is no such word return `-1`.

A **prefix** of a string `s` is any leading contiguous substring of `s`.

**Example 1:**

**Input:** sentence =  "i love eating burger ", searchWord =  "burg "
**Output:** 4
**Explanation:**  "burg " is prefix of  "burger " which is the 4th word in the sentence.

**Example 2:**

**Input:** sentence =  "this problem is an easy problem ", searchWord =  "pro "
**Output:** 2
**Explanation:**  "pro " is prefix of  "problem " which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.

**Example 3:**

**Input:** sentence =  "i am tired ", searchWord =  "you "
**Output:** -1
**Explanation:**  "you " is not a prefix of any word in the sentence.

**Constraints:**

*   `1 <= sentence.length <= 100`
*   `1 <= searchWord.length <= 10`
*   `sentence` consists of lowercase English letters and spaces.
*   `searchWord` consists of lowercase English letters.

## A solution in Java

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

public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {
    List<int[]> filteredRestaurants = new ArrayList<>();
    for (int[] r : restaurants) {
        if ((veganFriendly == 0 || r[2] == veganFriendly) && r[3] <= maxPrice && r[4] <= maxDistance) {
            filteredRestaurants.add(r);
        }
    }
    Collections.sort(filteredRestaurants, (a, b) -> a[1] == b[1] ? b[0] - a[0] : b[1] - a[1]);
    List<Integer> ids = new ArrayList<>();
    for (int[] r : filteredRestaurants) {
        ids.add(r[0]);
    }
    return ids;
}
```
The algorithm filters the given restaurants by checking each restaurant's vegan-friendly status, price, and distance. If the veganFriendly input is 0, the restaurant is considered regardless of its vegan-friendly status. If it is 1, only those restaurants with a vegan-friendly status of 1 are considered. Additionally, the restaurant's price and distance must be less than or equal to the given maxPrice and maxDistance, respectively. After filtering, the restaurants are sorted based on their ratings in descending order, and if two restaurants have the same rating, they are sorted by their IDs in descending order. Finally, the list of restaurant IDs is returned.

## A solution in C++

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

using namespace std;

bool customCompare(vector<int>& a, vector<int>& b) {
    if (a[1] == b[1]) return a[0] > b[0];
    return a[1] > b[1];
}

vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance) {
    vector<vector<int>> filteredRestaurants;
    for (auto& r : restaurants) {
        if ((veganFriendly == 0 || r[2] == veganFriendly) && r[3] <= maxPrice && r[4] <= maxDistance) {
            filteredRestaurants.push_back(r);
        }
    }
    sort(filteredRestaurants.begin(), filteredRestaurants.end(), customCompare);
    vector<int> ids;
    for (auto& r : filteredRestaurants) {
        ids.push_back(r[0]);
    }
    return ids;
}
```
The algorithm filters the given restaurants by checking each restaurant's vegan-friendly status, price, and distance. If the veganFriendly input is 0, the restaurant is considered regardless of its vegan-friendly status. If it is 1, only those restaurants with a vegan-friendly status of 1 are considered. Additionally, the restaurant's price and distance must be less than or equal to the given maxPrice and maxDistance, respectively. After filtering, the restaurants are sorted based on their ratings in descending order, and if two restaurants have the same rating, they are sorted by their IDs in descending order. Finally, the list of restaurant IDs is returned.

## A solution in Python

```python
def filter_restaurants(restaurants, vegan_friendly, max_price, max_distance):
    def custom_compare(a, b):
        if a[1] == b[1]:
            return b[0] - a[0]
        return b[1] - a[1]

    filtered_restaurants = [
        r for r in restaurants
        if (vegan_friendly == 0 or r[2] == vegan_friendly) and r[3] <= max_price and r[4] <= max_distance
    ]

    filtered_restaurants.sort(key=lambda r: (r[1], r[0]), reverse=True)

    return [r[0] for r in filtered_restaurants]
```
The algorithm filters the given restaurants by checking each restaurant's vegan-friendly status, price, and distance. If the veganFriendly input is 0, the restaurant is considered regardless of its vegan-friendly status. If it is 1, only those restaurants with a vegan-friendly status of 1 are considered. Additionally, the restaurant's price and distance must be less than or equal to the given maxPrice and maxDistance, respectively. After filtering, the restaurants are sorted based on their ratings in descending order, and if two restaurants have the same rating, they are sorted by their IDs in descending order. Finally, the list of restaurant IDs is returned.

## A solution in Javascript

```javascript
function filterRestaurants(restaurants, veganFriendly, maxPrice, maxDistance) {
    const filteredRestaurants = restaurants.filter(r => (veganFriendly === 0 || r[2] === veganFriendly) && r[3] <= maxPrice && r[4] <= maxDistance);
    filteredRestaurants.sort((a, b) => a[1] === b[1] ? b[0] - a[0] : b[1] - a[1]);

    return filteredRestaurants.map(r => r[0]);
}
```
The algorithm filters the given restaurants by checking each restaurant's vegan-friendly status, price, and distance. If the veganFriendly input is 0, the restaurant is considered regardless of its vegan-friendly status. If it is 1, only those restaurants with a vegan-friendly status of 1 are considered. Additionally, the restaurant's price and distance must be less than or equal to the given maxPrice and maxDistance, respectively. After filtering, the restaurants are sorted based on their ratings in descending order, and if two restaurants have the same rating, they are sorted by their IDs in descending order. Finally, the list of restaurant IDs is returned.


# Maximum Number of Vowels in a Substring of Given Length

- slug: maximum-number-of-vowels-in-a-substring-of-given-length
- difficulty: Medium

Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`.

**Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`.

**Example 1:**

**Input:** s =  "abciiidef ", k = 3
**Output:** 3
**Explanation:** The substring  "iii " contains 3 vowel letters.

**Example 2:**

**Input:** s =  "aeiou ", k = 2
**Output:** 2
**Explanation:** Any substring of length 2 contains 2 vowels.

**Example 3:**

**Input:** s =  "leetcode ", k = 3
**Output:** 2
**Explanation:**  "lee ",  "eet " and  "ode " contain 2 vowels.

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

public int findTheCity(int n, int[][] edges, int distanceThreshold) {
    int INF = Integer.MAX_VALUE;
    int[][] dist = new int[n][n];

    for (int i = 0; i < n; ++i) {
        Arrays.fill(dist[i], INF);
        dist[i][i] = 0;
    }

    for (int[] edge : edges) {
        dist[edge[0]][edge[1]] = dist[edge[1]][edge[0]] = edge[2];
    }

    for (int k = 0; k < n; ++k) {
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                if (dist[i][k] != INF && dist[k][j] != INF)
                    dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
            }
        }
    }

    int res = -1, minReachable = n + 1;
    for (int i = 0; i < n; ++i) {
        int cnt = 0;
        for (int d : dist[i]) {
            if (d <= distanceThreshold) ++cnt;
        }
        if (cnt <= minReachable) {
            minReachable = cnt;
            res = i;
        }
    }
    return res;
}
```
1. Initialize the distance matrix with `INF` (infinite) value and fill the diagonal with 0 because the city's distance to itself is always zero.
2. Fill the distance matrix with the given edges.
3. Apply Floyd–Warshall algorithm to find all minimum distances between cities.
4. Initialize the `res` and `minReachable`, loop through each city.
5. Inside the loop, count the number of cities that can be reached with a distance of at most `distanceThreshold`.
6. Update `minReachable` and `res` when the count is less than or equal to the current minimum including the greatest number.
7. Return the resulting city index.

## A solution in C++

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

int findTheCity(int n, std::vector<std::vector<int>>& edges, int distanceThreshold) {
    const int INF = std::numeric_limits<int>::max();
    std::vector<std::vector<int>> dist(n, std::vector<int>(n, INF));

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

    for (const auto& edge : edges) {
        dist[edge[0]][edge[1]] = dist[edge[1]][edge[0]] = edge[2];
    }

    for (int k = 0; k < n; ++k) {
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                dist[i][j] = std::min(dist[i][j], dist[i][k] + dist[k][j]);
            }
        }
    }

    int res = -1, minReachable = n + 1;
    for (int i = 0; i < n; ++i) {
        int cnt = 0;
        for (const auto& d : dist[i]) {
            if (d <= distanceThreshold) ++cnt;
        }
        if (cnt <= minReachable) {
            minReachable = cnt;
            res = i;
        }
    }
    return res;
}
```
1. Initialize the distance matrix with `INF` (infinite) value and fill the diagonal with 0 because the city's distance to itself is always zero.
2. Fill the distance matrix with the given edges.
3. Apply Floyd–Warshall algorithm to find all minimum distances between cities.
4. Initialize the `res` and `minReachable`, loop through each city.
5. Inside the loop, count the number of cities that can be reached with a distance of at most `distanceThreshold`.
6. Update `minReachable` and `res` when the count is less than or equal to the current minimum including the greatest number.
7. Return the resulting city index.

## A solution in Python

```python
def findTheCity(n, edges, distanceThreshold):
    INF = float("inf")
    dist = [[INF] * n for _ in range(n)]

    for i in range(n):
        dist[i][i] = 0

    for fr, to, w in edges:
        dist[fr][to] = dist[to][fr] = w

    for k in range(n):
        for i in range(n):
            for j in range(n):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    res, minReachable = -1, n + 1
    for i in range(n):
        cnt = sum(1 for d in dist[i] if d <= distanceThreshold)
        if cnt <= minReachable:
            minReachable = cnt
            res = i

    return res
```
1. Initialize the distance matrix with `INF` (infinite) value and fill the diagonal with 0 because the city's distance to itself is always zero.
2. Fill the distance matrix with the given edges.
3. Apply Floyd–Warshall algorithm to find all minimum distances between cities.
4. Initialize the `res` and `minReachable`, loop through each city.
5. Inside the loop, count the number of cities that can be reached with a distance of at most `distanceThreshold`.
6. Update `minReachable` and `res` when the count is less than or equal to the current minimum including the greatest number.
7. Return the resulting city index.

## A solution in Javascript

```javascript
function findTheCity(n, edges, distanceThreshold) {
    const INF = Infinity;
    const dist = Array.from({ length: n }, () => Array(n).fill(INF));

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

    for (const [fr, to, w] of edges) {
        dist[fr][to] = dist[to][fr] = w;
    }

    for (let k = 0; k < n; ++k) {
        for (let i = 0; i < n; ++i) {
            for (let j = 0; j < n; ++j) {
                dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
            }
        }
    }

    let res = -1, minReachable = n + 1;
    for (let i = 0; i < n; ++i) {
        let cnt = 0;
        for (const d of dist[i]) {
            if (d <= distanceThreshold) ++cnt;
        }
        if (cnt <= minReachable) {
            minReachable = cnt;
            res = i;
        }
    }
    return res;
}
```
1. Initialize the distance matrix with `INF` (infinite) value and fill the diagonal with 0 because the city's distance to itself is always zero.
2. Fill the distance matrix with the given edges.
3. Apply Floyd–Warshall algorithm to find all minimum distances between cities.
4. Initialize the `res` and `minReachable`, loop through each city.
5. Inside the loop, count the number of cities that can be reached with a distance of at most `distanceThreshold`.
6. Update `minReachable` and `res` when the count is less than or equal to the current minimum including the greatest number.
7. Return the resulting city index.