# Checking Existence of Edge Length Limited Paths II

- slug: checking-existence-of-edge-length-limited-paths-ii
- difficulty: Hard

An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes, and the graph may not be connected.

Implement the `DistanceLimitedPathsExist` class:

*   `DistanceLimitedPathsExist(int n, int[][] edgeList)` Initializes the class with an undirected graph.
*   `boolean query(int p, int q, int limit)` Returns `true` if there exists a path from `p` to `q` such that each edge on the path has a distance **strictly less than** `limit`, and otherwise `false`.

**Example 1:**

**Input**
\[ "DistanceLimitedPathsExist ",  "query ",  "query ",  "query ",  "query "\]
\[\[6, \[\[0, 2, 4\], \[0, 3, 2\], \[1, 2, 3\], \[2, 3, 1\], \[4, 5, 5\]\]\], \[2, 3, 2\], \[1, 3, 3\], \[2, 0, 3\], \[0, 5, 6\]\]
**Output**
\[null, true, false, true, false\]

**Explanation**
DistanceLimitedPathsExist distanceLimitedPathsExist = new DistanceLimitedPathsExist(6, \[\[0, 2, 4\], \[0, 3, 2\], \[1, 2, 3\], \[2, 3, 1\], \[4, 5, 5\]\]);
distanceLimitedPathsExist.query(2, 3, 2); // return true. There is an edge from 2 to 3 of distance 1, which is less than 2.
distanceLimitedPathsExist.query(1, 3, 3); // return false. There is no way to go from 1 to 3 with distances **strictly** less than 3.
distanceLimitedPathsExist.query(2, 0, 3); // return true. There is a way to go from 2 to 0 with distance < 3: travel from 2 to 3 to 0.
distanceLimitedPathsExist.query(0, 5, 6); // return false. There are no paths from 0 to 5.

`**Constraints:**`

*   `2 <= n <= 104`
*   `0 <= edgeList.length <= 104`
*   `edgeList[i].length == 3`
*   `0 <= ui, vi, p, q <= n-1`
*   `ui != vi`
*   `p != q`
*   `1 <= disi, limit <= 109`
*   At most `104` calls will be made to `query`.

## A solution in Java

```java
import java.util.Arrays;
import java.util.ArrayList;

class DistanceLimitedPathsExist {
    public DistanceLimitedPathsExist(int n, int[][] edgeList) {
        id = new int[n];
        for (int i = 0; i < n; ++i) {
            id[i] = i;
        }
        Arrays.sort(edgeList, (a, b) -> Integer.compare(a[2], b[2]));
        for (int[] edge : edgeList) {
            int p = find(edge[0]);
            int q = find(edge[1]);
            if (p != q) {
                id[p] = id[q];
                mst.add(edge);
            }
        }
    }

    public boolean query(int p, int q, int limit) {
        for (int[] edge : mst) {
            if (edge[2] >= limit) break;
            p = union_set(edge[0], p);
            q = union_set(edge[1], q);
            if (p == q) return true;
        }
        return false;
    }

    private int find(int x) {
        if (id[x] != x) {
            id[x] = find(id[x]);
        }
        return id[x];
    }

    private int union_set(int x, int y) {
        int px = find(x);
        int py = find(y);
        if (px != py) {
            id[px] = py;
        }
        return py;
    }

    private int[] id;
    private ArrayList<int[]> mst = new ArrayList<>();
}
```
The solution is based on the Kruskal algorithm, which helps to find the minimum spanning tree (MST). In this case, it will construct a data structure that represents the graph in MST form. We first initialize the disjoint set data structure for union-find operations.

In the constructor, we sort the `edgeList` by the edge weights (distance). Then, we iterate through the sorted edge list, performing union-find operations based on the minimum cost. We add the merged edges to the `mst` data structure.

For the `query()` function, we iterate through the MST and attempt to create a path from `p` to `q` with the given distance constraints. If the path is found, we return `true`, and if not, we return `false`.

The `find()` and `union_set()` are simple helper functions for the union-find operations.

Note that this algorithm does not guarantee the overall minimum distance between two nodes but helps to find paths with distances less than the given `limit`. To find the minimum distance for all pairs of nodes, you could use the Floyd-Warshall algorithm. However, implementing Floyd-Warshall is not necessary for this problem statement.

## A solution in C++

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

class DistanceLimitedPathsExist {
public:
    DistanceLimitedPathsExist(int n, const std::vector<std::vector<int>>& edgeList) {
        id.resize(n);
        for (int i = 0; i < n; ++i) {
            id[i] = i;
        }
        std::sort(edgeList.begin(), edgeList.end(), [](const auto& a, const auto& b) {
            return a[2] < b[2];
        });
        for (const auto& edge : edgeList) {
            int p = find(edge[0]);
            int q = find(edge[1]);
            if (p != q) {
                id[p] = id[q];
                mst.emplace_back(edge);
            }
        }
    }

    bool query(int p, int q, int limit) {
        for (const auto& edge : mst) {
            if (edge[2] >= limit) break;
            p = union_set(edge[0], p);
            q = union_set(edge[1], q);
            if (p == q) return true;
        }
        return false;
    }

private:
    int find(int x) {
        if (id[x] != x) {
            id[x] = find(id[x]);
        }
        return id[x];
    }

    int union_set(int x, int y) {
        int px = find(x);
        int py = find(y);
        if (px != py) {
            id[px] = py;
        }
        return py;
    }

    std::vector<int> id;
    std::vector<std::vector<int>> mst;
};
```
The solution is based on the Kruskal algorithm, which helps to find the minimum spanning tree (MST). In this case, it will construct a data structure that represents the graph in MST form. We first initialize the disjoint set data structure for union-find operations.

In the constructor, we sort the `edgeList` by the edge weights (distance). Then, we iterate through the sorted edge list, performing union-find operations based on the minimum cost. We add the merged edges to the `mst` data structure.

For the `query()` function, we iterate through the MST and attempt to create a path from `p` to `q` with the given distance constraints. If the path is found, we return `true`, and if not, we return `false`.

The `find()` and `union_set()` are simple helper functions for the union-find operations.

Note that this algorithm does not guarantee the overall minimum distance between two nodes but helps to find paths with distances less than the given `limit`. To find the minimum distance for all pairs of nodes, you could use the Floyd-Warshall algorithm. However, implementing Floyd-Warshall is not necessary for this problem statement.

## A solution in Python

```python
class DistanceLimitedPathsExist:
    def __init__(self, n: int, edgeList: List[List[int]]):
        self.id = list(range(n))
        edgeList.sort(key=lambda x: x[2])
        self.mst = []
        for edge in edgeList:
            p, q = self.find(edge[0]), self.find(edge[1])
            if p != q:
                self.id[p] = self.id[q]
                self.mst.append(edge)

    def query(self, p: int, q: int, limit: int) -> bool:
        for edge in self.mst:
            if edge[2] >= limit:
                break
            p, q = self.union_set(edge[0], p), self.union_set(edge[1], q)
            if p == q:
                return True
        return False

    def find(self, x: int) -> int:
        if self.id[x] != x:
            self.id[x] = self.find(self.id[x])
        return self.id[x]

    def union_set(self, x: int, y: int) -> int:
        px, py = self.find(x), self.find(y)
        if px != py:
            self.id[px] = py
        return py
```
The solution is based on the Kruskal algorithm, which helps to find the minimum spanning tree (MST). In this case, it will construct a data structure that represents the graph in MST form. We first initialize the disjoint set data structure for union-find operations.

In the constructor, we sort the `edgeList` by the edge weights (distance). Then, we iterate through the sorted edge list, performing union-find operations based on the minimum cost. We add the merged edges to the `mst` data structure.

For the `query()` function, we iterate through the MST and attempt to create a path from `p` to `q` with the given distance constraints. If the path is found, we return `true`, and if not, we return `false`.

The `find()` and `union_set()` are simple helper functions for the union-find operations.

Note that this algorithm does not guarantee the overall minimum distance between two nodes but helps to find paths with distances less than the given `limit`. To find the minimum distance for all pairs of nodes, you could use the Floyd-Warshall algorithm. However, implementing Floyd-Warshall is not necessary for this problem statement.

## A solution in Javascript

```javascript
class DistanceLimitedPathsExist {
    constructor(n, edgeList) {
        this.id = Array.from({ length: n }, (_, i) => i);
        edgeList.sort((a, b) => a[2] - b[2]);
        this.mst = [];
        for (const edge of edgeList) {
            const p = this.find(edge[0]);
            const q = this.find(edge[1]);
            if (p !== q) {
                this.id[p] = this.id[q];
                this.mst.push(edge);
            }
        }
    }

    query(p, q, limit) {
        for (const edge of this.mst) {
            if (edge[2] >= limit) break;
            p = this.union_set(edge[0], p);
            q = this.union_set(edge[1], q);
            if (p === q) return true;
        }
        return false;
    }

    find(x) {
        if (this.id[x] !== x) {
            this.id[x] = this.find(this.id[x]);
        }
        return this.id[x];
    }

    union_set(x, y) {
        const px = this.find(x);
        const py = this.find(y);
        if (px !== py) {
            this.id[px] = py;
        }
        return py;
    }
}
```
The solution is based on the Kruskal algorithm, which helps to find the minimum spanning tree (MST). In this case, it will construct a data structure that represents the graph in MST form. We first initialize the disjoint set data structure for union-find operations.

In the constructor, we sort the `edgeList` by the edge weights (distance). Then, we iterate through the sorted edge list, performing union-find operations based on the minimum cost. We add the merged edges to the `mst` data structure.

For the `query()` function, we iterate through the MST and attempt to create a path from `p` to `q` with the given distance constraints. If the path is found, we return `true`, and if not, we return `false`.

The `find()` and `union_set()` are simple helper functions for the union-find operations.

Note that this algorithm does not guarantee the overall minimum distance between two nodes but helps to find paths with distances less than the given `limit`. To find the minimum distance for all pairs of nodes, you could use the Floyd-Warshall algorithm. However, implementing Floyd-Warshall is not necessary for this problem statement.


# Number Of Rectangles That Can Form The Largest Square

- slug: number-of-rectangles-that-can-form-the-largest-square
- difficulty: Easy

You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`.

You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`.

Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles.

Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`.

**Example 1:**

**Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\]
**Output:** 3
**Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\].
The largest possible square is of length 5, and you can get it out of 3 rectangles.

**Example 2:**

**Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\]
**Output:** 3

**Constraints:**

*   `1 <= rectangles.length <= 1000`
*   `rectangles[i].length == 2`
*   `1 <= li, wi <= 109`
*   `li != wi`

## A solution in Java

```java
public int numberOfSets(int n, int k) {
    long mod = 1000000007;
    long[][] dp = new long[n][k + 1];
    long[] presum = new long[n];
    Arrays.fill(presum, 1);

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

    return (int) dp[n - 1][k];
}
```
The problem can be solved using dynamic programming. We create a 2D array `dp` of dimensions (n, k + 1), where `dp[i][j]` stores the number of ways to draw `j` non-overlapping line segments up to point `i`. We also maintain an array `presum` which is the prefix sum of the `dp` array.

We then loop through `j` from 1 to k and `i` from 0 to n-1, calculating `dp[i][j]` using the values in `presum` and `dp` arrays. To avoid recomputing values, we update the `presum` array iteratively.

Finally, we return the value in `dp[n - 1][k]` which is the number of ways to draw k non-overlapping line segments up to point n-1.

## A solution in C++

```cpp
int numberOfSets(int n, int k) {
    long long mod = 1e9 + 7;
    vector<vector<long long>> dp(n, vector<long long>(k + 1, 0));
    vector<long long> presum(n, 1);

    for (int j = 1; j <= k; ++j) {
        for (int i = 0; i < n; ++i) {
            dp[i][j] = presum[i];
            if (i) {
                dp[i][j] += dp[i - 1][j];
            }
            dp[i][j] %= mod;
            presum[i] = (presum[i] + dp[i][j - 1]) % mod;
        }
    }

    return dp[n - 1][k];
}
```
The problem can be solved using dynamic programming. We create a 2D array `dp` of dimensions (n, k + 1), where `dp[i][j]` stores the number of ways to draw `j` non-overlapping line segments up to point `i`. We also maintain an array `presum` which is the prefix sum of the `dp` array.

We then loop through `j` from 1 to k and `i` from 0 to n-1, calculating `dp[i][j]` using the values in `presum` and `dp` arrays. To avoid recomputing values, we update the `presum` array iteratively.

Finally, we return the value in `dp[n - 1][k]` which is the number of ways to draw k non-overlapping line segments up to point n-1.

## A solution in Python

```python
def numberOfSets(n, k):
    mod = 10**9 + 7
    dp = [[0] * (k + 1) for _ in range(n)]
    presum = [1] * n

    for j in range(1, k + 1):
        for i in range(n):
            dp[i][j] = presum[i]
            if i > 0:
                dp[i][j] += dp[i - 1][j]
            dp[i][j] %= mod
            presum[i] = (presum[i] + dp[i][j - 1]) % mod

    return dp[n - 1][k]
```
The problem can be solved using dynamic programming. We create a 2D array `dp` of dimensions (n, k + 1), where `dp[i][j]` stores the number of ways to draw `j` non-overlapping line segments up to point `i`. We also maintain an array `presum` which is the prefix sum of the `dp` array.

We then loop through `j` from 1 to k and `i` from 0 to n-1, calculating `dp[i][j]` using the values in `presum` and `dp` arrays. To avoid recomputing values, we update the `presum` array iteratively.

Finally, we return the value in `dp[n - 1][k]` which is the number of ways to draw k non-overlapping line segments up to point n-1.

## A solution in Javascript

```javascript
function numberOfSets(n, k) {
    const mod = 1e9 + 7;
    const dp = Array.from({ length: n }, () => Array(k + 1).fill(0));
    const presum = Array(n).fill(1);

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

    return dp[n - 1][k];
}
```
The problem can be solved using dynamic programming. We create a 2D array `dp` of dimensions (n, k + 1), where `dp[i][j]` stores the number of ways to draw `j` non-overlapping line segments up to point `i`. We also maintain an array `presum` which is the prefix sum of the `dp` array.

We then loop through `j` from 1 to k and `i` from 0 to n-1, calculating `dp[i][j]` using the values in `presum` and `dp` arrays. To avoid recomputing values, we update the `presum` array iteratively.

Finally, we return the value in `dp[n - 1][k]` which is the number of ways to draw k non-overlapping line segments up to point n-1.


# Tuple with Same Product

- slug: tuple-with-same-product
- difficulty: Medium

Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._

**Example 1:**

**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)

**Example 2:**

**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `1 <= nums[i] <= 104`
*   All elements in `nums` are **distinct**.

## A solution in Java

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

public int[] bestCoordinate(List<int[]> towers, int radius) {
    int max_quality = 0, best_x = 0, best_y = 0;

    for (int x = 0; x <= 50; ++x) {
        for (int y = 0; y <= 50; ++y) {
            int sum_quality = 0;
            for (int[] tower : towers) {
                double dist = Math.sqrt(Math.pow(x - tower[0], 2) + Math.pow(y - tower[1], 2));
                if (dist <= radius) {
                    sum_quality += tower[2] / (1 + dist);
                }
            }
            if (sum_quality > max_quality) {
                max_quality = sum_quality;
                best_x = x;
                best_y = y;
            }
        }
    }

    return new int[]{best_x, best_y};
}
```
The algorithm iterates through all integral coordinate points with x and y from 0 to 50 inclusive. For each point, it calculates the network quality at that point by iterating through all the given network towers. It calculates the distance between the current point and the tower and checks if the point is reachable. If yes, it calculates the signal quality for the current tower using the formula ⌊qi / (1 + d)⌋, and adds it to the sum_quality. After iterating through all the towers, it checks if the sum_quality is greater than max_quality. If yes, it updates max_quality and best_x, best_y to the current point's x and y. Finally, it returns the lexicographically minimum non-negative coordinate where the network quality is maximum.

The time complexity of this solution is O(n * m), where n is the number of integral coordinate points, and m is the number of network towers. In this case, there are 51 x 51 = 2601 integral points.

## A solution in C++

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

std::vector<int> bestCoordinate(std::vector<std::vector<int>>& towers, int radius) {
    int max_quality = 0, best_x = 0, best_y = 0;

    for (int x = 0; x <= 50; ++x) {
        for (int y = 0; y <= 50; ++y) {
            int sum_quality = 0;
            for (const auto& tower : towers) {
                double dist = std::sqrt(std::pow(x - tower[0], 2) + std::pow(y - tower[1], 2));
                if (dist <= radius) {
                    sum_quality += tower[2] / (1 + dist);
                }
            }
            if (sum_quality > max_quality) {
                max_quality = sum_quality;
                best_x = x;
                best_y = y;
            }
        }
    }

    return {best_x, best_y};
}
```
The algorithm iterates through all integral coordinate points with x and y from 0 to 50 inclusive. For each point, it calculates the network quality at that point by iterating through all the given network towers. It calculates the distance between the current point and the tower and checks if the point is reachable. If yes, it calculates the signal quality for the current tower using the formula ⌊qi / (1 + d)⌋, and adds it to the sum_quality. After iterating through all the towers, it checks if the sum_quality is greater than max_quality. If yes, it updates max_quality and best_x, best_y to the current point's x and y. Finally, it returns the lexicographically minimum non-negative coordinate where the network quality is maximum.

The time complexity of this solution is O(n * m), where n is the number of integral coordinate points, and m is the number of network towers. In this case, there are 51 x 51 = 2601 integral points.

## A solution in Python

```python
from math import sqrt

def best_coordinate(towers, radius):
    max_quality = 0
    best_x, best_y = 0, 0

    for x in range(51):
        for y in range(51):
            sum_quality = 0
            for tower in towers:
                dist = sqrt((x - tower[0])**2 + (y - tower[1])**2)
                if dist <= radius:
                    sum_quality += tower[2] // (1 + dist)
            if sum_quality > max_quality:
                max_quality = sum_quality
                best_x, best_y = x, y

    return [best_x, best_y]
```
The algorithm iterates through all integral coordinate points with x and y from 0 to 50 inclusive. For each point, it calculates the network quality at that point by iterating through all the given network towers. It calculates the distance between the current point and the tower and checks if the point is reachable. If yes, it calculates the signal quality for the current tower using the formula ⌊qi / (1 + d)⌋, and adds it to the sum_quality. After iterating through all the towers, it checks if the sum_quality is greater than max_quality. If yes, it updates max_quality and best_x, best_y to the current point's x and y. Finally, it returns the lexicographically minimum non-negative coordinate where the network quality is maximum.

The time complexity of this solution is O(n * m), where n is the number of integral coordinate points, and m is the number of network towers. In this case, there are 51 x 51 = 2601 integral points.

## A solution in Javascript

```javascript
function bestCoordinate(towers, radius) {
    let max_quality = 0, best_x = 0, best_y = 0;

    for (let x = 0; x <= 50; ++x) {
        for (let y = 0; y <= 50; ++y) {
            let sum_quality = 0;
            for (const tower of towers) {
                const dist = Math.sqrt(Math.pow(x - tower[0], 2) + Math.pow(y - tower[1], 2));
                if (dist <= radius) {
                    sum_quality += Math.floor(tower[2] / (1 + dist));
                }
            }
            if (sum_quality > max_quality) {
                max_quality = sum_quality;
                best_x = x;
                best_y = y;
            }
        }
    }

    return [best_x, best_y];
}
```
The algorithm iterates through all integral coordinate points with x and y from 0 to 50 inclusive. For each point, it calculates the network quality at that point by iterating through all the given network towers. It calculates the distance between the current point and the tower and checks if the point is reachable. If yes, it calculates the signal quality for the current tower using the formula ⌊qi / (1 + d)⌋, and adds it to the sum_quality. After iterating through all the towers, it checks if the sum_quality is greater than max_quality. If yes, it updates max_quality and best_x, best_y to the current point's x and y. Finally, it returns the lexicographically minimum non-negative coordinate where the network quality is maximum.

The time complexity of this solution is O(n * m), where n is the number of integral coordinate points, and m is the number of network towers. In this case, there are 51 x 51 = 2601 integral points.


# Largest Submatrix With Rearrangements

- slug: largest-submatrix-with-rearrangements
- difficulty: Medium

You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.

Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._

**Example 1:**

**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.

**Example 2:**

**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.

**Example 3:**

**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.

**Constraints:**

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

## A solution in Java

```java
public boolean canMouseWin(char[][] grid, int catJump, int mouseJump) {
    int rows = grid.length;
    int cols = grid[0].length;
    int cat_r = 0, cat_c = 0, mouse_r = 0, mouse_c = 0;

    for (int r = 0; r < rows; ++r)
        for (int c = 0; c < cols; ++c) {
            if (grid[r][c] == 'C') {
                cat_r = r;
                cat_c = c;
            } else if (grid[r][c] == 'M') {
                mouse_r = r;
                mouse_c = c;
            }
        }

    int[] dirs = {-1, 0, 1, 0, -1};
    return dfs(grid, mouse_r, mouse_c, cat_r, cat_c, 0, Math.abs(cat_r - mouse_r) + Math.abs(cat_c - mouse_c), catJump, mouseJump, dirs, new HashSet<>());
}

private boolean dfs(char[][] grid, int r_m, int c_m, int r_c, int c_c, int cnt, int dst_m_c, int catJump, int mouseJump, int[] dirs, Set<String> seen) {
    if (cnt >= 100)
        return false;
    if (r_m < 0 || r_m >= grid.length || c_m < 0 || c_m >= grid[0].length)
        return false;
    if (r_c < 0 || r_c >= grid.length || c_c < 0 || c_c >= grid[0].length)
        return true;
    if (seen.contains(r_m + "-" + c_m + "-" + r_c + "-" + c_c))
        return false;

    if (grid[r_m][c_m] == 'F' || cnt != dst_m_c) {
        return true;
    } else if (grid[r_m][c_m] == '#' || cnt + 1 == dst_m_c) {
        return false;
    }

    boolean res = false;
    for(int i = 0; i < 4; i++){
        int jump = (dst_m_c == cnt) ? catJump : mouseJump;
        res |= !dfs(grid, r_m + jump * dirs[i], c_m + jump * dirs[i+1], r_c + dirs[i] * dirs[(i + 2) % 4], c_c + dirs[i+1] * dirs[(i + 3) % 4], cnt + 1, dst_m_c, catJump, mouseJump, dirs, seen);
        if(jump == 1) break;
    }

    if(!res)
        seen.add(r_m + "-" + c_m + "-" + r_c + "-" + c_c);

    return res;
}
```
1. Find the positions of the cat and the mouse on the grid.
2. Compute the initial distance between cat and mouse in terms of the number of steps at the beginning of the game.
3. The DFS function will be called recursively, with updated positions for both cat and mouse. The function returns a boolean value that indicates whether the mouse can win.
4. Base cases for DFS function:
    1. When the game takes more than 100 steps, assume the mouse cannot win.
    2. If the mouse is out of bounds, assume the mouse loses.
    3. If the cat is out of bounds, assume the mouse wins.
    4. If the mouse reaches the food or the cell the mouse is in is an odd number of steps away from the food, the mouse wins.
    5. If the mouse is standing in a wall or the cell the mouse is in is an even number of steps away from the food, the mouse loses.
5. When the DFS function is called, it tries all possible directions (up, down, left, and right) by adjusting the row, and column of both cat and mouse.
6. If a new position is found such that the mouse can win, we return true. If no winning position is found, we return false.
7. The overall function returns true if the mouse can win, and false otherwise.

## A solution in C++

```cpp
bool canMouseWin(vector<vector<char>>& grid, int catJump, int mouseJump) {
    int rows = grid.size();
    int cols = grid[0].size();
    int cat_r, cat_c, mouse_r, mouse_c, steps = 0;

    for (int r = 0; r < rows; ++r)
        for (int c = 0; c < cols; ++c) {
            if (grid[r][c] == 'C') {
                cat_r = r;
                cat_c = c;
            } else if (grid[r][c] == 'M') {
                mouse_r = r;
                mouse_c = c;
            }
        }

    vector<int> dirs = {-1, 0, 1, 0, -1};
    function<bool(int, int, int, int, int, int)> dfs = [&](int r_m, int c_m, int r_c, int c_c, int cnt, int dst_m_c) {
        if (cnt >= 100) // The game is taking more than 100 steps
            return false;
        if (r_m < 0 || r_m >= rows || c_m < 0 || c_m >= cols) // Mouse out of bounds
            return false;
        if (r_c < 0 || r_c >= rows || c_c < 0 || c_c >= cols) // Cat out of bounds
            return true;
        if (grid[r_m][c_m] == 'F' || cnt != dst_m_c) { // Mouse reached food or cell is odd steps away from food
            return true;
        } else if (grid[r_m][c_m] == '#' || cnt + 1 == dst_m_c) { // Wall or cell is even steps away from food
            return false;
        }

        bool res = false;
        for(int i = 0; i < 4; i++){
            int jump = (dst_m_c == cnt) ? catJump : mouseJump;
            res |= !dfs(r_m + jump * dirs[i], c_m + jump * dirs[i+1], r_c + dirs[i] * dirs[(i + 2) % 4], c_c + dirs[i+1] * dirs[(i + 3) % 4], cnt + 1, dst_m_c);
            if(jump == 1) break;
        }
        return res;
    };

    return dfs(mouse_r, mouse_c, cat_r, cat_c, 0, abs(cat_r - mouse_r) + abs(cat_c - mouse_c));
}
```
1. Find the positions of the cat and the mouse on the grid.
2. Compute the initial distance between cat and mouse in terms of the number of steps at the beginning of the game.
3. The DFS function will be called recursively, with updated positions for both cat and mouse. The function returns a boolean value that indicates whether the mouse can win.
4. Base cases for DFS function:
    1. When the game takes more than 100 steps, assume the mouse cannot win.
    2. If the mouse is out of bounds, assume the mouse loses.
    3. If the cat is out of bounds, assume the mouse wins.
    4. If the mouse reaches the food or the cell the mouse is in is an odd number of steps away from the food, the mouse wins.
    5. If the mouse is standing in a wall or the cell the mouse is in is an even number of steps away from the food, the mouse loses.
5. When the DFS function is called, it tries all possible directions (up, down, left, and right) by adjusting the row, and column of both cat and mouse.
6. If a new position is found such that the mouse can win, we return true. If no winning position is found, we return false.
7. The overall function returns true if the mouse can win, and false otherwise.

## A solution in Python

```python
def canMouseWin(grid: List[List[str]], catJump: int, mouseJump: int) -> bool:
    rows, cols = len(grid), len(grid[0])
    cat_r = cat_c = mouse_r = mouse_c = 0

    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 'C':
                cat_r, cat_c = r, c
            elif grid[r][c] == 'M':
                mouse_r, mouse_c = r, c

    dirs = [-1, 0, 1, 0, -1]

    def dfs(r_m, c_m, r_c, c_c, cnt, dst_m_c):
        if cnt >= 100:
            return False
        if r_m < 0 or r_m >= rows or c_m < 0 or c_m >= cols:
            return False
        if r_c < 0 or r_c >= rows or c_c < 0 or c_c >= cols:
            return True
        if grid[r_m][c_m] == 'F' or cnt != dst_m_c:
            return True
        elif grid[r_m][c_m] == '#' or cnt + 1 == dst_m_c:
            return False

        res = False
        for i in range(4):
            jump = catJump if dst_m_c == cnt else mouseJump
            res |= not dfs(r_m + jump * dirs[i], c_m + jump * dirs[i + 1], r_c + dirs[i] * dirs[(i + 2) % 4], c_c + dirs[i+1] * dirs[(i + 3) % 4], cnt + 1, dst_m_c)
            if jump == 1:
                break

        return res

    return dfs(mouse_r, mouse_c, cat_r, cat_c, 0, abs(cat_r - mouse_r) + abs(cat_c - mouse_c))
```
1. Find the positions of the cat and the mouse on the grid.
2. Compute the initial distance between cat and mouse in terms of the number of steps at the beginning of the game.
3. The DFS function will be called recursively, with updated positions for both cat and mouse. The function returns a boolean value that indicates whether the mouse can win.
4. Base cases for DFS function:
    1. When the game takes more than 100 steps, assume the mouse cannot win.
    2. If the mouse is out of bounds, assume the mouse loses.
    3. If the cat is out of bounds, assume the mouse wins.
    4. If the mouse reaches the food or the cell the mouse is in is an odd number of steps away from the food, the mouse wins.
    5. If the mouse is standing in a wall or the cell the mouse is in is an even number of steps away from the food, the mouse loses.
5. When the DFS function is called, it tries all possible directions (up, down, left, and right) by adjusting the row, and column of both cat and mouse.
6. If a new position is found such that the mouse can win, we return true. If no winning position is found, we return false.
7. The overall function returns true if the mouse can win, and false otherwise.

## A solution in Javascript

```javascript
function canMouseWin(grid, catJump, mouseJump) {
    const rows = grid.length;
    const cols = grid[0].length;
    let cat_r, cat_c, mouse_r, mouse_c;

    for (let r = 0; r < rows; ++r)
        for (let c = 0; c < cols; ++c) {
            if (grid[r][c] === 'C') {
                cat_r = r;
                cat_c = c;
            } else if (grid[r][c] === 'M') {
                mouse_r = r;
                mouse_c = c;
            }
        }

    const dirs = [-1, 0, 1, 0, -1];

    function dfs(r_m, c_m, r_c, c_c, cnt, dst_m_c) {
        if (cnt >= 100)
            return false;
        if (r_m < 0 || r_m >= rows || c_m < 0 || c_m >= cols)
            return false;
        if (r_c < 0 || r_c >= rows || c_c < 0 || c_c >= cols)
            return true;
        if (grid[r_m][c_m] === 'F' || cnt !== dst_m_c) {
            return true;
        } else if (grid[r_m][c_m] === '#' || cnt + 1 === dst_m_c) {
            return false;
        }

        let res = false;
        for(let i = 0; i < 4; i++){
            let jump = (dst_m_c === cnt) ? catJump : mouseJump;
            res |= !dfs(r_m + jump * dirs[i], c_m + jump * dirs[i+1], r_c + dirs[i] * dirs[(i + 2) % 4], c_c + dirs[i+1] * dirs[(i + 3) % 4], cnt + 1, dst_m_c);
            if(jump === 1) break;
        }

        return res;
    }

    return dfs(mouse_r, mouse_c, cat_r, cat_c, 0, Math.abs(cat_r - mouse_r) + Math.abs(cat_c - mouse_c));
}
```
1. Find the positions of the cat and the mouse on the grid.
2. Compute the initial distance between cat and mouse in terms of the number of steps at the beginning of the game.
3. The DFS function will be called recursively, with updated positions for both cat and mouse. The function returns a boolean value that indicates whether the mouse can win.
4. Base cases for DFS function:
    1. When the game takes more than 100 steps, assume the mouse cannot win.
    2. If the mouse is out of bounds, assume the mouse loses.
    3. If the cat is out of bounds, assume the mouse wins.
    4. If the mouse reaches the food or the cell the mouse is in is an odd number of steps away from the food, the mouse wins.
    5. If the mouse is standing in a wall or the cell the mouse is in is an even number of steps away from the food, the mouse loses.
5. When the DFS function is called, it tries all possible directions (up, down, left, and right) by adjusting the row, and column of both cat and mouse.
6. If a new position is found such that the mouse can win, we return true. If no winning position is found, we return false.
7. The overall function returns true if the mouse can win, and false otherwise.


# Cat and Mouse II

- slug: cat-and-mouse-ii
- difficulty: Hard

A game is played by a cat and a mouse named Cat and Mouse.

The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food.

*   Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse).
*   Floors are represented by the character `'.'` and can be walked on.
*   Walls are represented by the character `'#'` and cannot be walked on.
*   Food is represented by the character `'F'` and can be walked on.
*   There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.

Mouse and Cat play according to the following rules:

*   Mouse **moves first**, then they take turns to move.
*   During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`.
*   `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.
*   Staying in the same position is allowed.
*   Mouse can jump over Cat.

The game can end in 4 ways:

*   If Cat occupies the same position as Mouse, Cat wins.
*   If Cat reaches the food first, Cat wins.
*   If Mouse reaches the food first, Mouse wins.
*   If Mouse cannot get to the food within 1000 turns, Cat wins.

Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`.

**Example 1:**

**Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2
**Output:** true
**Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse.

**Example 2:**

**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4
**Output:** true

**Example 3:**

**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3
**Output:** false

**Constraints:**

*   `rows == grid.length`
*   `cols = grid[i].length`
*   `1 <= rows, cols <= 8`
*   `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`.
*   There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
*   `1 <= catJump, mouseJump <= 8`

## A solution in Java

```java
import java.util.ArrayList;

class Fancy {
    private ArrayList<Integer> sequence;

    public Fancy() {
        sequence = new ArrayList<>();
    }

    public void append(int val) {
        sequence.add(val);
    }

    public void addAll(int inc) {
        for (int i = 0; i < sequence.size(); i++) {
            sequence.set(i, sequence.get(i) + inc);
        }
    }

    public void multAll(int m) {
        for (int i = 0; i < sequence.size(); i++) {
            sequence.set(i, sequence.get(i) * m);
        }
    }

    public int getIndex(int idx) {
        if (idx >= sequence.size()) return -1;
        return sequence.get(idx);
    }
}
```
The Fancy class has a sequence that stores integers. The following methods are implemented:
1. append(val) - Appends the given value to the sequence.
2. addAll(inc) - Adds the given increment to all elements in the sequence.
3. multAll(m) - Multiplies all elements in the sequence with the given multiplier.
4. getIndex(idx) - Returns the element at the given index in the sequence or -1 if the index is out of bounds.

Each coded implementation in C++, Java, Python, and JavaScript maintains a sequence and manipulates it based on the methods called. The implementation details are the same across these languages, and the basic concepts rely on the usage of arrays, iterating over elements, and modifying elements in the array based on the operations requested.

## A solution in C++

```cpp
class Fancy {
public:
    Fancy() {}

    void append(int val) {
        sequence.push_back(val);
    }

    void addAll(int inc) {
        for(auto& num : sequence) {
            num += inc;
        }
    }

    void multAll(int m) {
        for(auto& num : sequence) {
            num *= m;
        }
    }

    int getIndex(int idx) {
        if(idx >= sequence.size()) return -1;
        return sequence[idx];
    }
private:
    vector<int> sequence;
};
```
The Fancy class has a sequence that stores integers. The following methods are implemented:
1. append(val) - Appends the given value to the sequence.
2. addAll(inc) - Adds the given increment to all elements in the sequence.
3. multAll(m) - Multiplies all elements in the sequence with the given multiplier.
4. getIndex(idx) - Returns the element at the given index in the sequence or -1 if the index is out of bounds.

Each coded implementation in C++, Java, Python, and JavaScript maintains a sequence and manipulates it based on the methods called. The implementation details are the same across these languages, and the basic concepts rely on the usage of arrays, iterating over elements, and modifying elements in the array based on the operations requested.

## A solution in Python

```python
class Fancy:
    def __init__(self):
        self.sequence = []

    def append(self, val):
        self.sequence.append(val)

    def addAll(self, inc):
        self.sequence = [num + inc for num in self.sequence]

    def multAll(self, m):
        self.sequence = [num * m for num in self.sequence]

    def getIndex(self, idx):
        if idx >= len(self.sequence):
            return -1
        return self.sequence[idx]
```
The Fancy class has a sequence that stores integers. The following methods are implemented:
1. append(val) - Appends the given value to the sequence.
2. addAll(inc) - Adds the given increment to all elements in the sequence.
3. multAll(m) - Multiplies all elements in the sequence with the given multiplier.
4. getIndex(idx) - Returns the element at the given index in the sequence or -1 if the index is out of bounds.

Each coded implementation in C++, Java, Python, and JavaScript maintains a sequence and manipulates it based on the methods called. The implementation details are the same across these languages, and the basic concepts rely on the usage of arrays, iterating over elements, and modifying elements in the array based on the operations requested.

## A solution in Javascript

```javascript
class Fancy {
    constructor() {
        this.sequence = [];
    }

    append(val) {
        this.sequence.push(val);
    }

    addAll(inc) {
        this.sequence = this.sequence.map(num => num + inc);
    }

    multAll(m) {
        this.sequence = this.sequence.map(num => num * m);
    }

    getIndex(idx) {
        if (idx >= this.sequence.length) return -1;
        return this.sequence[idx];
    }
}
```
The Fancy class has a sequence that stores integers. The following methods are implemented:
1. append(val) - Appends the given value to the sequence.
2. addAll(inc) - Adds the given increment to all elements in the sequence.
3. multAll(m) - Multiplies all elements in the sequence with the given multiplier.
4. getIndex(idx) - Returns the element at the given index in the sequence or -1 if the index is out of bounds.

Each coded implementation in C++, Java, Python, and JavaScript maintains a sequence and manipulates it based on the methods called. The implementation details are the same across these languages, and the basic concepts rely on the usage of arrays, iterating over elements, and modifying elements in the array based on the operations requested.


# Shortest Path to Get Food

- slug: shortest-path-to-get-food
- difficulty: Medium

You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell.

You are given an `m x n` character matrix, `grid`, of these different types of cells:

*   `'*'` is your location. There is **exactly one** `'*'` cell.
*   `'#'` is a food cell. There may be **multiple** food cells.
*   `'O'` is free space, and you can travel through these cells.
*   `'X'` is an obstacle, and you cannot travel through these cells.

You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle.

Return _the **length** of the shortest path for you to reach **any** food cell_. If there is no path for you to reach food, return `-1`.

**Example 1:**

**Input:** grid = \[\[ "X ", "X ", "X ", "X ", "X ", "X "\],\[ "X ", "\* ", "O ", "O ", "O ", "X "\],\[ "X ", "O ", "O ", "# ", "O ", "X "\],\[ "X ", "X ", "X ", "X ", "X ", "X "\]\]
**Output:** 3
**Explanation:** It takes 3 steps to reach the food.

**Example 2:**

**Input:** grid = \[\[ "X ", "X ", "X ", "X ", "X "\],\[ "X ", "\* ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "# ", "X "\],\[ "X ", "X ", "X ", "X ", "X "\]\]
**Output:** -1
**Explanation:** It is not possible to reach the food.

**Example 3:**

**Input:** grid = \[\[ "X ", "X ", "X ", "X ", "X ", "X ", "X ", "X "\],\[ "X ", "\* ", "O ", "X ", "O ", "# ", "O ", "X "\],\[ "X ", "O ", "O ", "X ", "O ", "O ", "X ", "X "\],\[ "X ", "O ", "O ", "O ", "O ", "# ", "O ", "X "\],\[ "X ", "X ", "X ", "X ", "X ", "X ", "X ", "X "\]\]
**Output:** 6
**Explanation:** There can be multiple food cells. It only takes 6 steps to reach the bottom food.

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 200`
*   `grid[row][col]` is `'*'`, `'X'`, `'O'`, or `'#'`.
*   The `grid` contains **exactly one** `'*'`.

## A solution in Java

```java
public int findSpecialInteger(int[] nums) {
    for (int x = 1; x <= nums.length; ++x) {
        int count = 0;
        for (int num : nums) {
            if (num >= x) {
                ++count;
            }
        }
        if (count == x) {
            return x;
        }
    }
    return -1;
}
```
The algorithm iterates through all integer values of x from 1 to the length of nums. For each value of x, it counts how many elements in nums are greater than or equal to x. If the count is equal to x, the array is considered special and the value of x is returned. If no such x is found after iterating through all possible values, the algorithm returns -1.

## A solution in C++

```cpp
int findSpecialInteger(const std::vector<int>& nums) {
    for (int x = 1; x <= nums.size(); ++x) {
        int count = 0;
        for (int num : nums) {
            if (num >= x) {
                ++count;
            }
        }
        if (count == x) {
            return x;
        }
    }
    return -1;
}
```
The algorithm iterates through all integer values of x from 1 to the length of nums. For each value of x, it counts how many elements in nums are greater than or equal to x. If the count is equal to x, the array is considered special and the value of x is returned. If no such x is found after iterating through all possible values, the algorithm returns -1.

## A solution in Python

```python
def find_special_integer(nums):
    for x in range(1, len(nums) + 1):
        count = sum(1 for num in nums if num >= x)
        if count == x:
            return x
    return -1
```
The algorithm iterates through all integer values of x from 1 to the length of nums. For each value of x, it counts how many elements in nums are greater than or equal to x. If the count is equal to x, the array is considered special and the value of x is returned. If no such x is found after iterating through all possible values, the algorithm returns -1.

## A solution in Javascript

```javascript
function findSpecialInteger(nums) {
    for (let x = 1; x <= nums.length; ++x) {
        let count = 0;
        for (let num of nums) {
            if (num >= x) {
                ++count;
            }
        }
        if (count === x) {
            return x;
        }
    }
    return -1;
}
```
The algorithm iterates through all integer values of x from 1 to the length of nums. For each value of x, it counts how many elements in nums are greater than or equal to x. If the count is equal to x, the array is considered special and the value of x is returned. If no such x is found after iterating through all possible values, the algorithm returns -1.


# Find the Highest Altitude

- slug: find-the-highest-altitude
- difficulty: Easy

There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.

You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._

**Example 1:**

**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.

**Example 2:**

**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.

**Constraints:**

*   `n == gain.length`
*   `1 <= n <= 100`
*   `-100 <= gain[i] <= 100`

## A solution in Java

```java
int minOperations(int n) {
    int operations = 0;
    while (n > 0) {
        if (n % 2 == 0) {
            n /= 2;
        } else {
            n--;
        }
        operations++;
    }
    return operations;
}
```
The algorithm initializes a variable `operations` to store the number of operations taken. It then enters a loop that iterates while `n` is greater than 0. In each iteration, it checks whether `n` is divisible by 2 (i.e., even). If it is, the algorithm divides `n` by 2; otherwise, it decrements `n` by 1. In each loop iteration, the algorithm also increments the `operations` counter. The loop ends when `n` reaches 0, and the algorithm returns the total count of operations performed.

This algorithm finds the minimum number of operations required because dividing `n` by 2 is more optimal than decrementing `n` by 1 whenever `n` is even, as it reduces the number more rapidly.

## A solution in C++

```cpp
int min_operations(int n) {
    int operations = 0;
    while (n > 0) {
        if (n % 2 == 0) {
            n /= 2;
        } else {
            n--;
        }
        operations++;
    }
    return operations;
}
```
The algorithm initializes a variable `operations` to store the number of operations taken. It then enters a loop that iterates while `n` is greater than 0. In each iteration, it checks whether `n` is divisible by 2 (i.e., even). If it is, the algorithm divides `n` by 2; otherwise, it decrements `n` by 1. In each loop iteration, the algorithm also increments the `operations` counter. The loop ends when `n` reaches 0, and the algorithm returns the total count of operations performed.

This algorithm finds the minimum number of operations required because dividing `n` by 2 is more optimal than decrementing `n` by 1 whenever `n` is even, as it reduces the number more rapidly.

## A solution in Python

```python
def min_operations(n):
    operations = 0
    while n > 0:
        if n % 2 == 0:
            n //= 2
        else:
            n -= 1
        operations += 1
    return operations
```
The algorithm initializes a variable `operations` to store the number of operations taken. It then enters a loop that iterates while `n` is greater than 0. In each iteration, it checks whether `n` is divisible by 2 (i.e., even). If it is, the algorithm divides `n` by 2; otherwise, it decrements `n` by 1. In each loop iteration, the algorithm also increments the `operations` counter. The loop ends when `n` reaches 0, and the algorithm returns the total count of operations performed.

This algorithm finds the minimum number of operations required because dividing `n` by 2 is more optimal than decrementing `n` by 1 whenever `n` is even, as it reduces the number more rapidly.

## A solution in Javascript

```javascript
function minOperations(n) {
    let operations = 0;
    while (n > 0) {
        if (n % 2 === 0) {
            n /= 2;
        } else {
            n--;
        }
        operations++;
    }
    return operations;
}
```
The algorithm initializes a variable `operations` to store the number of operations taken. It then enters a loop that iterates while `n` is greater than 0. In each iteration, it checks whether `n` is divisible by 2 (i.e., even). If it is, the algorithm divides `n` by 2; otherwise, it decrements `n` by 1. In each loop iteration, the algorithm also increments the `operations` counter. The loop ends when `n` reaches 0, and the algorithm returns the total count of operations performed.

This algorithm finds the minimum number of operations required because dividing `n` by 2 is more optimal than decrementing `n` by 1 whenever `n` is even, as it reduces the number more rapidly.


# Minimum Number of People to Teach

- slug: minimum-number-of-people-to-teach
- difficulty: Medium

On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language.

You are given an integer `n`, an array `languages`, and an array `friendships` where:

*   There are `n` languages numbered `1` through `n`,
*   `languages[i]` is the set of languages the `ith` user knows, and
*   `friendships[i] = [ui, vi]` denotes a friendship between the users `ui` and `vi`.

You can choose **one** language and teach it to some users so that all friends can communicate with each other. Return _the_ _**minimum**_ _number of users you need to teach._

Note that friendships are not transitive, meaning if `x` is a friend of `y` and `y` is a friend of `z`, this doesn't guarantee that `x` is a friend of `z`.

**Example 1:**

**Input:** n = 2, languages = \[\[1\],\[2\],\[1,2\]\], friendships = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** 1
**Explanation:** You can either teach user 1 the second language or user 2 the first language.

**Example 2:**

**Input:** n = 3, languages = \[\[2\],\[1,3\],\[1,2\],\[3\]\], friendships = \[\[1,4\],\[1,2\],\[3,4\],\[2,3\]\]
**Output:** 2
**Explanation:** Teach the third language to users 1 and 3, yielding two users to teach.

**Constraints:**

*   `2 <= n <= 500`
*   `languages.length == m`
*   `1 <= m <= 500`
*   `1 <= languages[i].length <= n`
*   `1 <= languages[i][j] <= n`
*   `1 <= ui < vi <= languages.length`
*   `1 <= friendships.length <= 500`
*   All tuples `(ui, vi)` are unique
*   `languages[i]` contains only unique values

## A solution in Java

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

public int visiblePoints(List<List<Integer>> points, int angle, List<Integer> location) {
    List<Double> angles = new ArrayList<>();
    for (List<Integer> point : points) {
        if (!point.equals(location)) {
            angles.add(getAngle(point.get(0), point.get(1), location.get(0), location.get(1)));
        }
    }
    Collections.sort(angles);
    int n = angles.size();
    for (int i = 0; i < n; i++) {
        angles.add(angles.get(i) + 360);
    }
    int max_points = 0;
    int j = 0;
    for (int i = 0; i < 2 * n; i++) {
        while (angles.get(i) - angles.get(j) > angle) {
            j++;
        }
        max_points = Math.max(max_points, i - j + 1);
    }
    return max_points + (int) points.stream().filter(point -> point.equals(location)).count();
}

private double getAngle(int x, int y, int px, int py) {
    return Math.atan2(y - py, x - px) * 180 / Math.PI;
}
```
1. Calculate the angles of each point relative to the current position and the east direction, and add the angles to the `angles` list. Skip the points at the observer's location.
2. Sort the `angles` list in ascending order.
3. Copy the `angles` list while adding 360 to each angle at the end of the list.
4. Initialize two pointers i and j, and a variable max_points to store the maximum number of points in the field of view.
5. Iterate through the angles list using pointer i. If the difference between the i-th angle and the j-th angle is greater than the given angle, increment j. Update max_points with the maximum of max_points and i - j + 1.
6. Finally, add the number of points at the observer's location to the max_points and return it.

## A solution in C++

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

using namespace std;

double getAngle(int x, int y, int px, int py) {
    return atan2(y - py, x - px) * 180 / M_PI;
}

int visiblePoints(vector<vector<int>>& points, int angle, vector<int>& location) {
    vector<double> angles;
    for (const auto& point : points) {
        if (point != location) {
            angles.push_back(getAngle(point[0], point[1], location[0], location[1]));
        }
    }
    sort(angles.begin(), angles.end());
    int n = angles.size();
    for (int i = 0; i < n; i++) {
        angles.push_back(angles[i] + 360);
    }
    int max_points = 0;
    int j = 0;
    for (int i = 0; i < 2 * n; i++) {
        while (angles[i] - angles[j] > angle) {
            j++;
        }
        max_points = max(max_points, i - j + 1);
    }
    return max_points + count(points.begin(), points.end(), location);
}
```
1. Calculate the angles of each point relative to the current position and the east direction, and add the angles to the `angles` list. Skip the points at the observer's location.
2. Sort the `angles` list in ascending order.
3. Copy the `angles` list while adding 360 to each angle at the end of the list.
4. Initialize two pointers i and j, and a variable max_points to store the maximum number of points in the field of view.
5. Iterate through the angles list using pointer i. If the difference between the i-th angle and the j-th angle is greater than the given angle, increment j. Update max_points with the maximum of max_points and i - j + 1.
6. Finally, add the number of points at the observer's location to the max_points and return it.

## A solution in Python

```python
from math import atan2, degrees

def visiblePoints(points, angle, location):
    angles = [degrees(atan2(y - location[1], x - location[0])) for x, y in points if [x, y] != location]
    angles.sort()
    angles += [a + 360 for a in angles]
    n = len(angles)
    max_points, j = 0, 0
    for i in range(2 * n):
        while angles[i] - angles[j] > angle:
            j += 1
        max_points = max(max_points, i - j + 1)
    return max_points + points.count(location)
```
1. Calculate the angles of each point relative to the current position and the east direction, and add the angles to the `angles` list. Skip the points at the observer's location.
2. Sort the `angles` list in ascending order.
3. Copy the `angles` list while adding 360 to each angle at the end of the list.
4. Initialize two pointers i and j, and a variable max_points to store the maximum number of points in the field of view.
5. Iterate through the angles list using pointer i. If the difference between the i-th angle and the j-th angle is greater than the given angle, increment j. Update max_points with the maximum of max_points and i - j + 1.
6. Finally, add the number of points at the observer's location to the max_points and return it.

## A solution in Javascript

```javascript
function visiblePoints(points, angle, location) {
    const angles = points.filter(point => point[0] !== location[0] || point[1] !== location[1])
        .map(point => Math.atan2(point[1] - location[1], point[0] - location[0]) * 180 / Math.PI)
        .sort((a, b) => a - b);
    angles.push(...angles.map(a => a + 360));
    let max_points = 0;
    let j = 0;
    const n = angles.length;
    for (let i = 0; i < 2 * n; i++) {
        while (angles[i] - angles[j] > angle) {
            j += 1;
        }
        max_points = Math.max(max_points, i - j + 1);
    }
    const locationsAtPoint = points.filter(point => point[0] === location[0] && point[1] === location[1]).length;
    return max_points + locationsAtPoint;
}
```
1. Calculate the angles of each point relative to the current position and the east direction, and add the angles to the `angles` list. Skip the points at the observer's location.
2. Sort the `angles` list in ascending order.
3. Copy the `angles` list while adding 360 to each angle at the end of the list.
4. Initialize two pointers i and j, and a variable max_points to store the maximum number of points in the field of view.
5. Iterate through the angles list using pointer i. If the difference between the i-th angle and the j-th angle is greater than the given angle, increment j. Update max_points with the maximum of max_points and i - j + 1.
6. Finally, add the number of points at the observer's location to the max_points and return it.


# Decode XORed Permutation

- slug: decode-xored-permutation
- difficulty: Medium

There is an integer array `perm` that is a permutation of the first `n` positive integers, where `n` is always **odd**.

It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = perm[i] XOR perm[i + 1]`. For example, if `perm = [1,3,2]`, then `encoded = [2,1]`.

Given the `encoded` array, return _the original array_ `perm`. It is guaranteed that the answer exists and is unique.

**Example 1:**

**Input:** encoded = \[3,1\]
**Output:** \[1,2,3\]
**Explanation:** If perm = \[1,2,3\], then encoded = \[1 XOR 2,2 XOR 3\] = \[3,1\]

**Example 2:**

**Input:** encoded = \[6,5,4,6\]
**Output:** \[2,4,1,5,3\]

**Constraints:**

*   `3 <= n < 105`
*   `n` is odd.
*   `encoded.length == n - 1`

## A solution in Java

```java
public int[] decode(int[] encoded) {
    int n = encoded.length + 1;
    int totalXor = 0;

    for (int i = 1; i <= n; i++) {
        totalXor ^= i;
    }

    int nonFirstXor = 0;
    for (int i = 1; i < n - 1; i += 2) {
        nonFirstXor ^= encoded[i];
    }

    int[] perm = new int[n];
    perm[0] = totalXor ^ nonFirstXor;

    for (int i = 1; i < n; i++) {
        perm[i] = perm[i - 1] ^ encoded[i - 1];
    }

    return perm;
}
```
1. Calculate the XOR of all numbers from 1 to n, which is called `totalXor`.
2. Calculate the XOR of all even indices of `encoded` array, which is called `nonFirstXor`.
3. The first number in `perm` can be calculated as `totalXor ^ nonFirstXor`.
4. Iterate through the array from 1 to n-1 to fill in the rest of the `perm` array. The value of `perm[i]` is calculated as `perm[i - 1] ^ encoded[i - 1]`.
5. Return the `perm` array.

## A solution in C++

```cpp
#include <vector>

std::vector<int> decode(std::vector<int>& encoded) {
    int n = encoded.size() + 1;
    int totalXor = 0;
    for (int i = 1; i <= n; i++) {
        totalXor ^= i;
    }

    int nonFirstXor = 0;
    for (int i = 1; i < n - 1; i += 2) {
        nonFirstXor ^= encoded[i];
    }

    std::vector<int> perm(n);
    perm[0] = totalXor ^ nonFirstXor;

    for (int i = 1; i < n; i++) {
        perm[i] = perm[i - 1] ^ encoded[i - 1];
    }

    return perm;
}
```
1. Calculate the XOR of all numbers from 1 to n, which is called `totalXor`.
2. Calculate the XOR of all even indices of `encoded` array, which is called `nonFirstXor`.
3. The first number in `perm` can be calculated as `totalXor ^ nonFirstXor`.
4. Iterate through the array from 1 to n-1 to fill in the rest of the `perm` array. The value of `perm[i]` is calculated as `perm[i - 1] ^ encoded[i - 1]`.
5. Return the `perm` array.

## A solution in Python

```python
def decode(encoded):
    n = len(encoded) + 1
    total_xor = 0

    for i in range(1, n + 1):
        total_xor ^= i

    non_first_xor = 0
    for i in range(1, n - 1, 2):
        non_first_xor ^= encoded[i]

    perm = [total_xor ^ non_first_xor]
    for i in range(1, n):
        perm.append(perm[-1] ^ encoded[i - 1])

    return perm
```
1. Calculate the XOR of all numbers from 1 to n, which is called `totalXor`.
2. Calculate the XOR of all even indices of `encoded` array, which is called `nonFirstXor`.
3. The first number in `perm` can be calculated as `totalXor ^ nonFirstXor`.
4. Iterate through the array from 1 to n-1 to fill in the rest of the `perm` array. The value of `perm[i]` is calculated as `perm[i - 1] ^ encoded[i - 1]`.
5. Return the `perm` array.

## A solution in Javascript

```javascript
function decode(encoded) {
    const n = encoded.length + 1;
    let totalXor = 0;

    for (let i = 1; i <= n; i++) {
        totalXor ^= i;
    }

    let nonFirstXor = 0;
    for (let i = 1; i < n - 1; i += 2) {
        nonFirstXor ^= encoded[i];
    }

    const perm = new Array(n);
    perm[0] = totalXor ^ nonFirstXor;

    for (let i = 1; i < n; i++) {
        perm[i] = perm[i - 1] ^ encoded[i - 1];
    }

    return perm;
}
```
1. Calculate the XOR of all numbers from 1 to n, which is called `totalXor`.
2. Calculate the XOR of all even indices of `encoded` array, which is called `nonFirstXor`.
3. The first number in `perm` can be calculated as `totalXor ^ nonFirstXor`.
4. Iterate through the array from 1 to n-1 to fill in the rest of the `perm` array. The value of `perm[i]` is calculated as `perm[i - 1] ^ encoded[i - 1]`.
5. Return the `perm` array.


# Count Ways to Make Array With Product

- slug: count-ways-to-make-array-with-product
- difficulty: Hard

You are given a 2D integer array, `queries`. For each `queries[i]`, where `queries[i] = [ni, ki]`, find the number of different ways you can place positive integers into an array of size `ni` such that the product of the integers is `ki`. As the number of ways may be too large, the answer to the `ith` query is the number of ways **modulo** `109 + 7`.

Return _an integer array_ `answer` _where_ `answer.length == queries.length`_, and_ `answer[i]` _is the answer to the_ `ith` _query._

**Example 1:**

**Input:** queries = \[\[2,6\],\[5,1\],\[73,660\]\]
**Output:** \[4,1,50734910\]
**Explanation:** Each query is independent.
\[2,6\]: There are 4 ways to fill an array of size 2 that multiply to 6: \[1,6\], \[2,3\], \[3,2\], \[6,1\].
\[5,1\]: There is 1 way to fill an array of size 5 that multiply to 1: \[1,1,1,1,1\].
\[73,660\]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910.

**Example 2:**

**Input:** queries = \[\[1,1\],\[2,2\],\[3,3\],\[4,4\],\[5,5\]\]
**Output:** \[1,2,3,10,5\]

**Constraints:**

*   `1 <= queries.length <= 104`
*   `1 <= ni, ki <= 104`

## A solution in Java

```java
import java.util.*;

public class Solution {
    private static final int MOD = 1_000_000_007;

    private static int mul(int a, int b) {
        return (int)(((long) a * b) % MOD);
    }

    private static int powMod(int a, int b) {
        int res = 1;
        while (b > 0) {
            if ((b & 1) == 1) {
                res = mul(res, a);
            }
            a = mul(a, a);
            b >>= 1;
        }
        return res;
    }

    private static int ways(int n, int k, Map<String, Integer> mem) {
        if (n == 1) return k;

        String key = n + "," + k;
        if (mem.containsKey(key)) {
            return mem.get(key);
        }

        if (k == 1) {
            mem.put(key, 1);
            return 1;
        }
        if (n > k) {
            mem.put(key, 0);
            return 0;
        }

        int res = mul(ways(n, k - 1, mem), n);
        res = (res - mul(n - 1, ways(n - 1, k - 1, mem)) + MOD) % MOD;

        mem.put(key, res);
        return res;
    }

    public int[] waysToFillArray(int[][] queries) {
        Map<String, Integer> mem = new HashMap<>();
        int[] ans = new int[queries.length];

        for (int i = 0; i < queries.length; i++) {
            ans[i] = ways(queries[i][0], queries[i][1], mem);
        }

        return ans;
    }
}
```
The approach to solving this problem involves dynamic programming with memoization. We will write a recursive function `ways(n, k, mem)` that returns the number of different ways the problem can be solved for integers n and k. The memoization is done using a 2-tuple (Python), a string concatenation (Java and JavaScript), and a hash map with the key being the product of n and a large number (C++) in the `mem` variable.

We take the following recursive cases:

1. If n is 1, the only integer that satisfies the condition is k itself (since the product of only integer k is k). In this case, the number of ways is k.

2. If there is already an entry in our memoization data structure for the tuple (or string/combination) `(n, k)`, we return the cached value since we already know the result of this subproblem.

3. If k is 1, we would only have a product of 1 with all 1's in the array, so the number of ways is 1.

4. If n > k, there are no ways to fill an array of size n with a product of k since we are counting only positive integers. In this case, the number of ways is 0.

For the recursive part, we take two subproblems:

1. The number of ways if the current array element is 1: which is `ways(n-1, k, mem)` multiplied by `n`. The reasoning is that there are `n` elements to place a 1 in the array while we mutate the product of the remaining integers.

2. The number of ways if the current array element is not 1, i.e., equal to k: which is `ways(n-1, k-1, mem)` multiplied by `(n-1)`. This comes from the fact that we have a product of k with (n-1) elements and each element can be chosen in (`n-1`) ways.

We then find the difference between these two values and return it.

Finally, in the helper function, `waysToFillArray(queries)`, we simply iterate through the queries, and for each pair `(ni, ki)`, we call `ways(ni, ki, mem)` to find the number of ways and append it to the answer array which is then returned as the final result.

## A solution in C++

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

const int MOD = 1e9 + 7;

int mul(int a, int b) {
    return (1LL * a * b) % MOD;
}

int powMod(int a, int b) {
    int res = 1;
    while (b) {
        if (b & 1) res = mul(res, a);
        a = mul(a, a);
        b >>= 1;
    }
    return res;
}

int ways(int n, int k, unordered_map<int, int>& mem) {
    if (n == 1) return k;
    int& res = mem[n * 50000 + k];
    if (res) return res;

    if (k == 1) {
        return res = 1;
    }
    if (n > k) {
        return res = 0;
    }

    res = mul(ways(n, k - 1, mem), n);
    res = (res - mul(n - 1, ways(n - 1, k - 1, mem)) + MOD) % MOD;

    return res;
}

vector<int> waysToFillArray(vector<vector<int>>& queries) {
    unordered_map<int, int> mem;
    vector<int> ans;
    for (auto& q : queries) {
        ans.push_back(ways(q[0], q[1], mem));
    }
    return ans;
}
```
The approach to solving this problem involves dynamic programming with memoization. We will write a recursive function `ways(n, k, mem)` that returns the number of different ways the problem can be solved for integers n and k. The memoization is done using a 2-tuple (Python), a string concatenation (Java and JavaScript), and a hash map with the key being the product of n and a large number (C++) in the `mem` variable.

We take the following recursive cases:

1. If n is 1, the only integer that satisfies the condition is k itself (since the product of only integer k is k). In this case, the number of ways is k.

2. If there is already an entry in our memoization data structure for the tuple (or string/combination) `(n, k)`, we return the cached value since we already know the result of this subproblem.

3. If k is 1, we would only have a product of 1 with all 1's in the array, so the number of ways is 1.

4. If n > k, there are no ways to fill an array of size n with a product of k since we are counting only positive integers. In this case, the number of ways is 0.

For the recursive part, we take two subproblems:

1. The number of ways if the current array element is 1: which is `ways(n-1, k, mem)` multiplied by `n`. The reasoning is that there are `n` elements to place a 1 in the array while we mutate the product of the remaining integers.

2. The number of ways if the current array element is not 1, i.e., equal to k: which is `ways(n-1, k-1, mem)` multiplied by `(n-1)`. This comes from the fact that we have a product of k with (n-1) elements and each element can be chosen in (`n-1`) ways.

We then find the difference between these two values and return it.

Finally, in the helper function, `waysToFillArray(queries)`, we simply iterate through the queries, and for each pair `(ni, ki)`, we call `ways(ni, ki, mem)` to find the number of ways and append it to the answer array which is then returned as the final result.

## A solution in Python

```python
MOD = 10**9 + 7

def mul(a, b):
    return (a * b) % MOD

def ways(n, k, mem):
    if n == 1:
        return k
    if (n_tuple := (n, k)) in mem:
        return mem[n_tuple]
    if k == 1:
        mem[n_tuple] = 1
        return 1
    if n > k:
        mem[n_tuple] = 0
        return 0
    res = mul(ways(n, k - 1, mem), n)
    res = (res - mul(n - 1, ways(n - 1, k - 1, mem)) + MOD) % MOD
    mem[n_tuple] = res
    return res

def waysToFillArray(queries):
    mem = {}
    ans = []
    for q in queries:
        ans.append(ways(q[0], q[1], mem))
    return ans
```
The approach to solving this problem involves dynamic programming with memoization. We will write a recursive function `ways(n, k, mem)` that returns the number of different ways the problem can be solved for integers n and k. The memoization is done using a 2-tuple (Python), a string concatenation (Java and JavaScript), and a hash map with the key being the product of n and a large number (C++) in the `mem` variable.

We take the following recursive cases:

1. If n is 1, the only integer that satisfies the condition is k itself (since the product of only integer k is k). In this case, the number of ways is k.

2. If there is already an entry in our memoization data structure for the tuple (or string/combination) `(n, k)`, we return the cached value since we already know the result of this subproblem.

3. If k is 1, we would only have a product of 1 with all 1's in the array, so the number of ways is 1.

4. If n > k, there are no ways to fill an array of size n with a product of k since we are counting only positive integers. In this case, the number of ways is 0.

For the recursive part, we take two subproblems:

1. The number of ways if the current array element is 1: which is `ways(n-1, k, mem)` multiplied by `n`. The reasoning is that there are `n` elements to place a 1 in the array while we mutate the product of the remaining integers.

2. The number of ways if the current array element is not 1, i.e., equal to k: which is `ways(n-1, k-1, mem)` multiplied by `(n-1)`. This comes from the fact that we have a product of k with (n-1) elements and each element can be chosen in (`n-1`) ways.

We then find the difference between these two values and return it.

Finally, in the helper function, `waysToFillArray(queries)`, we simply iterate through the queries, and for each pair `(ni, ki)`, we call `ways(ni, ki, mem)` to find the number of ways and append it to the answer array which is then returned as the final result.

## A solution in Javascript

```javascript
const MOD = 1e9 + 7;

function mul(a, b) {
  return (BigInt(a) * BigInt(b)) % MOD;
}

function ways(n, k, mem) {
  if (n === 1) return k;
  const key = n + ',' + k;
  if (mem[key]) return mem[key];

  if (k === 1) {
    mem[key] = 1;
    return 1;
  }
  if (n > k) {
    mem[key] = 0;
    return 0;
  }

  let res = mul(ways(n, k - 1, mem), n);
  res = (res - mul(n - 1, ways(n - 1, k - 1, mem)) + MOD) % MOD;

  mem[key] = Number(res);
  return mem[key];
}

function waysToFillArray(queries) {
  const mem = {};
  const ans = [];
  for (let i = 0; i < queries.length; i++) {
    ans.push(ways(queries[i][0], queries[i][1], mem));
  }
  return ans;
}
```
The approach to solving this problem involves dynamic programming with memoization. We will write a recursive function `ways(n, k, mem)` that returns the number of different ways the problem can be solved for integers n and k. The memoization is done using a 2-tuple (Python), a string concatenation (Java and JavaScript), and a hash map with the key being the product of n and a large number (C++) in the `mem` variable.

We take the following recursive cases:

1. If n is 1, the only integer that satisfies the condition is k itself (since the product of only integer k is k). In this case, the number of ways is k.

2. If there is already an entry in our memoization data structure for the tuple (or string/combination) `(n, k)`, we return the cached value since we already know the result of this subproblem.

3. If k is 1, we would only have a product of 1 with all 1's in the array, so the number of ways is 1.

4. If n > k, there are no ways to fill an array of size n with a product of k since we are counting only positive integers. In this case, the number of ways is 0.

For the recursive part, we take two subproblems:

1. The number of ways if the current array element is 1: which is `ways(n-1, k, mem)` multiplied by `n`. The reasoning is that there are `n` elements to place a 1 in the array while we mutate the product of the remaining integers.

2. The number of ways if the current array element is not 1, i.e., equal to k: which is `ways(n-1, k-1, mem)` multiplied by `(n-1)`. This comes from the fact that we have a product of k with (n-1) elements and each element can be chosen in (`n-1`) ways.

We then find the difference between these two values and return it.

Finally, in the helper function, `waysToFillArray(queries)`, we simply iterate through the queries, and for each pair `(ni, ki)`, we call `ways(ni, ki, mem)` to find the number of ways and append it to the answer array which is then returned as the final result.


# Latest Time by Replacing Hidden Digits

- slug: latest-time-by-replacing-hidden-digits
- difficulty: Easy

You are given a string `time` in the form of `hh:mm`, where some of the digits in the string are hidden (represented by `?`).

The valid times are those inclusively between `00:00` and `23:59`.

Return _the latest valid time you can get from_ `time` _by replacing the hidden_ _digits_.

**Example 1:**

**Input:** time =  "2?:?0 "
**Output:**  "23:50 "
**Explanation:** The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.

**Example 2:**

**Input:** time =  "0?:3? "
**Output:**  "09:39 "

**Example 3:**

**Input:** time =  "1?:22 "
**Output:**  "19:22 "

**Constraints:**

*   `time` is in the format `hh:mm`.
*   It is guaranteed that you can produce a valid time from the given string.

## A solution in Java

```java
public String maximumTime(String time) {
    char[] res = time.toCharArray();
    if (res[0] == '?') {
        res[0] = (res[1] <= '3' || res[1] == '?') ? '2' : '1';
    }
    if (res[1] == '?') {
        res[1] = (res[0] == '2') ? '3' : '9';
    }
    if (res[3] == '?') {
        res[3] = '5';
    }
    if (res[4] == '?') {
        res[4] = '9';
    }
    return new String(res);
}
```
The algorithm uses the following steps:
1. For each character in the input string, check if it's a "?".
2. If the character is "?", assign a valid hour or minute value depending on its position in the string and other characters' values.
- If the first "?" is at position 0, check if the character at position 1 is less than or equal to 3 or "?". If true, assign '2' else, assign '1' to position 0.
- If the first "?" is at position 1, check if the character at position 0 is '2'. If true, assign '3' else, assign '9' to position 1.
- If the first "?" is at position 3, assign '5' to it, any value between 00-59 is valid.
- If the first "?" is at position 4, assign '9' to it, any value between 00-59 is valid.

Finally, return the modified string.

## A solution in C++

```cpp
#include <string>

std::string maximumTime(std::string time) {
    if (time[0] == '?') {
        time[0] = (time[1] <= '3' || time[1] == '?') ? '2' : '1';
    }
    if (time[1] == '?') {
        time[1] = (time[0] == '2') ? '3' : '9';
    }
    if (time[3] == '?') {
        time[3] = '5';
    }
    if (time[4] == '?') {
        time[4] = '9';
    }
    return time;
}
```
The algorithm uses the following steps:
1. For each character in the input string, check if it's a "?".
2. If the character is "?", assign a valid hour or minute value depending on its position in the string and other characters' values.
- If the first "?" is at position 0, check if the character at position 1 is less than or equal to 3 or "?". If true, assign '2' else, assign '1' to position 0.
- If the first "?" is at position 1, check if the character at position 0 is '2'. If true, assign '3' else, assign '9' to position 1.
- If the first "?" is at position 3, assign '5' to it, any value between 00-59 is valid.
- If the first "?" is at position 4, assign '9' to it, any value between 00-59 is valid.

Finally, return the modified string.

## A solution in Python

```python
def maximumTime(time: str) -> str:
    time_list = list(time)
    if time_list[0] == '?':
        time_list[0] = '2' if time_list[1] <= '3' or time_list[1] == '?' else '1'
    if time_list[1] == '?':
        time_list[1] = '3' if time_list[0] == '2' else '9'
    if time_list[3] == '?':
        time_list[3] = '5'
    if time_list[4] == '?':
        time_list[4] = '9'
    return "".join(time_list)
```
The algorithm uses the following steps:
1. For each character in the input string, check if it's a "?".
2. If the character is "?", assign a valid hour or minute value depending on its position in the string and other characters' values.
- If the first "?" is at position 0, check if the character at position 1 is less than or equal to 3 or "?". If true, assign '2' else, assign '1' to position 0.
- If the first "?" is at position 1, check if the character at position 0 is '2'. If true, assign '3' else, assign '9' to position 1.
- If the first "?" is at position 3, assign '5' to it, any value between 00-59 is valid.
- If the first "?" is at position 4, assign '9' to it, any value between 00-59 is valid.

Finally, return the modified string.

## A solution in Javascript

```javascript
function maximumTime(time) {
    let res = time.split('');
    if (res[0] === "?") {
        res[0] = (res[1] <= "3" || res[1] === "?") ? "2" : "1";
    }
    if (res[1] === "?") {
        res[1] = (res[0] === "2") ? "3" : "9";
    }
    if (res[3] === "?") {
        res[3] = "5";
    }
    if (res[4] === "?") {
        res[4] = "9";
    }
    return res.join('');
}
```
The algorithm uses the following steps:
1. For each character in the input string, check if it's a "?".
2. If the character is "?", assign a valid hour or minute value depending on its position in the string and other characters' values.
- If the first "?" is at position 0, check if the character at position 1 is less than or equal to 3 or "?". If true, assign '2' else, assign '1' to position 0.
- If the first "?" is at position 1, check if the character at position 0 is '2'. If true, assign '3' else, assign '9' to position 1.
- If the first "?" is at position 3, assign '5' to it, any value between 00-59 is valid.
- If the first "?" is at position 4, assign '9' to it, any value between 00-59 is valid.

Finally, return the modified string.


# Change Minimum Characters to Satisfy One of Three Conditions

- slug: change-minimum-characters-to-satisfy-one-of-three-conditions
- difficulty: Medium

You are given two strings `a` and `b` that consist of lowercase letters. In one operation, you can change any character in `a` or `b` to **any lowercase letter**.

Your goal is to satisfy **one** of the following three conditions:

*   **Every** letter in `a` is **strictly less** than **every** letter in `b` in the alphabet.
*   **Every** letter in `b` is **strictly less** than **every** letter in `a` in the alphabet.
*   **Both** `a` and `b` consist of **only one** distinct letter.

Return _the **minimum** number of operations needed to achieve your goal._

**Example 1:**

**Input:** a =  "aba ", b =  "caa "
**Output:** 2
**Explanation:** Consider the best way to make each condition true:
1) Change b to  "ccc " in 2 operations, then every letter in a is less than every letter in b.
2) Change a to  "bbb " and b to  "aaa " in 3 operations, then every letter in b is less than every letter in a.
3) Change a to  "aaa " and b to  "aaa " in 2 operations, then a and b consist of one distinct letter.
The best way was done in 2 operations (either condition 1 or condition 3).

**Example 2:**

**Input:** a =  "dabadd ", b =  "cda "
**Output:** 3
**Explanation:** The best way is to make condition 1 true by changing b to  "eee ".

**Constraints:**

*   `1 <= a.length, b.length <= 105`
*   `a` and `b` consist only of lowercase letters.

## A solution in Java

```java
int maxDepth(String s) {
    int depth = 0, maxDepth = 0;
    for (char ch : s.toCharArray()) {
        if (ch == '(') depth++;
        else if (ch == ')') depth--;
        maxDepth = Math.max(maxDepth, depth);
    }
    return maxDepth;
}
```
We initialize two variables, `depth` and `maxDepth`, both with an initial value of zero. We then iterate through the given string `s`. For each character in the string:
- If the character is an opening parenthesis '(', we increment the `depth` by 1.
- If the character is a closing parenthesis ')', we decrement the `depth` by 1.
- At each step, we update the `maxDepth` by taking the maximum of the current `maxDepth` and the current `depth`.
After the iteration, we return the `maxDepth` as the nesting depth of the given VPS `s`.

## A solution in C++

```cpp
int maxDepth(string s) {
    int depth = 0, maxDepth = 0;
    for (const char ch : s) {
        if (ch == '(') ++depth;
        else if (ch == ')') --depth;
        maxDepth = max(maxDepth, depth);
    }
    return maxDepth;
}
```
We initialize two variables, `depth` and `maxDepth`, both with an initial value of zero. We then iterate through the given string `s`. For each character in the string:
- If the character is an opening parenthesis '(', we increment the `depth` by 1.
- If the character is a closing parenthesis ')', we decrement the `depth` by 1.
- At each step, we update the `maxDepth` by taking the maximum of the current `maxDepth` and the current `depth`.
After the iteration, we return the `maxDepth` as the nesting depth of the given VPS `s`.

## A solution in Python

```python
def maxDepth(s: str) -> int:
    depth, max_depth = 0, 0
    for ch in s:
        if ch == '(':
            depth += 1
        elif ch == ')':
            depth -= 1
        max_depth = max(max_depth, depth)
    return max_depth
```
We initialize two variables, `depth` and `maxDepth`, both with an initial value of zero. We then iterate through the given string `s`. For each character in the string:
- If the character is an opening parenthesis '(', we increment the `depth` by 1.
- If the character is a closing parenthesis ')', we decrement the `depth` by 1.
- At each step, we update the `maxDepth` by taking the maximum of the current `maxDepth` and the current `depth`.
After the iteration, we return the `maxDepth` as the nesting depth of the given VPS `s`.

## A solution in Javascript

```javascript
function maxDepth(s) {
    let depth = 0, maxDepth = 0;
    for (const ch of s) {
        if (ch === '(') depth++;
        else if (ch === ')') depth--;
        maxDepth = Math.max(maxDepth, depth);
    }
    return maxDepth;
}
```
We initialize two variables, `depth` and `maxDepth`, both with an initial value of zero. We then iterate through the given string `s`. For each character in the string:
- If the character is an opening parenthesis '(', we increment the `depth` by 1.
- If the character is a closing parenthesis ')', we decrement the `depth` by 1.
- At each step, we update the `maxDepth` by taking the maximum of the current `maxDepth` and the current `depth`.
After the iteration, we return the `maxDepth` as the nesting depth of the given VPS `s`.


# Find Kth Largest XOR Coordinate Value

- slug: find-kth-largest-xor-coordinate-value
- difficulty: Medium

You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`.

The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**.

Find the `kth` largest value **(1-indexed)** of all the coordinates of `matrix`.

**Example 1:**

**Input:** matrix = \[\[5,2\],\[1,6\]\], k = 1
**Output:** 7
**Explanation:** The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.

**Example 2:**

**Input:** matrix = \[\[5,2\],\[1,6\]\], k = 2
**Output:** 5
**Explanation:** The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.

**Example 3:**

**Input:** matrix = \[\[5,2\],\[1,6\]\], k = 3
**Output:** 4
**Explanation:** The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.

**Constraints:**

*   `m == matrix.length`
*   `n == matrix[i].length`
*   `1 <= m, n <= 1000`
*   `0 <= matrix[i][j] <= 106`
*   `1 <= k <= m * n`

## A solution in Java

```java
public int maximalNetworkRank(int n, int[][] roads) {
    int[] degree = new int[n];
    Set<String> s = new HashSet<>();

    for (int[] road : roads) {
        degree[road[0]]++;
        degree[road[1]]++;
        String temp = Math.min(road[0], road[1]) + "," + Math.max(road[0], road[1]);
        s.add(temp);
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            String temp = i + "," + j;
            ans = Math.max(ans, degree[i] + degree[j] - (s.contains(temp) ? 1 : 0));
        }
    }
    return ans;
}
```
1. Initialize an array called `degree` of size n, which tracks the degree of each city (number of directly connected roads).
2. Initialize a set `s` to store pairs of connected cities (by storing a string representation of the pair in JavaScript, and tuple in Python).
3. Iterate through the given roads array and increment the degree counter for both cities, and add the pair to the set `s`.
4. Initialize a variable `ans` to store the maximum network rank found.
5. Iterate through all city pairs and calculate their network rank by summing their degrees and subtracting 1 if they are directly connected (detected using the set `s`).
6. Update the `ans` variable to be the maximum of its current value and the calculated network rank for the current city pair.
7. Return the maximum network rank found (`ans`).

## A solution in C++

```cpp
int maximalNetworkRank(int n, vector<vector<int>>& roads) {
    vector<int> degree(n, 0);
    set<pair<int, int>> s;

    for (auto& road : roads) {
        degree[road[0]]++;
        degree[road[1]]++;
        s.insert({min(road[0], road[1]), max(road[0], road[1])});
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            ans = max(ans, degree[i] + degree[j] - (s.count({i, j}) ? 1 : 0));
        }
    }
    return ans;
}
```
1. Initialize an array called `degree` of size n, which tracks the degree of each city (number of directly connected roads).
2. Initialize a set `s` to store pairs of connected cities (by storing a string representation of the pair in JavaScript, and tuple in Python).
3. Iterate through the given roads array and increment the degree counter for both cities, and add the pair to the set `s`.
4. Initialize a variable `ans` to store the maximum network rank found.
5. Iterate through all city pairs and calculate their network rank by summing their degrees and subtracting 1 if they are directly connected (detected using the set `s`).
6. Update the `ans` variable to be the maximum of its current value and the calculated network rank for the current city pair.
7. Return the maximum network rank found (`ans`).

## A solution in Python

```python
def maximalNetworkRank(n, roads):
    degree = [0] * n
    s = set()

    for road in roads:
        degree[road[0]] += 1
        degree[road[1]] += 1
        s.add(tuple(sorted(road)))

    ans = 0
    for i in range(n):
        for j in range(i + 1, n):
            ans = max(ans, degree[i] + degree[j] - (1 if (i, j) in s else 0))
    return ans
```
1. Initialize an array called `degree` of size n, which tracks the degree of each city (number of directly connected roads).
2. Initialize a set `s` to store pairs of connected cities (by storing a string representation of the pair in JavaScript, and tuple in Python).
3. Iterate through the given roads array and increment the degree counter for both cities, and add the pair to the set `s`.
4. Initialize a variable `ans` to store the maximum network rank found.
5. Iterate through all city pairs and calculate their network rank by summing their degrees and subtracting 1 if they are directly connected (detected using the set `s`).
6. Update the `ans` variable to be the maximum of its current value and the calculated network rank for the current city pair.
7. Return the maximum network rank found (`ans`).

## A solution in Javascript

```javascript
function maximalNetworkRank(n, roads) {
    let degree = new Array(n).fill(0);
    let s = new Set();

    for (let road of roads) {
        degree[road[0]]++;
        degree[road[1]]++;
        s.add([Math.min(road[0], road[1]), Math.max(road[0], road[1])].toString());
    }

    let ans = 0;
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            ans = Math.max(ans, degree[i] + degree[j] - (s.has([i, j].toString()) ? 1 : 0));
        }
    }
    return ans;
}
```
1. Initialize an array called `degree` of size n, which tracks the degree of each city (number of directly connected roads).
2. Initialize a set `s` to store pairs of connected cities (by storing a string representation of the pair in JavaScript, and tuple in Python).
3. Iterate through the given roads array and increment the degree counter for both cities, and add the pair to the set `s`.
4. Initialize a variable `ans` to store the maximum network rank found.
5. Iterate through all city pairs and calculate their network rank by summing their degrees and subtracting 1 if they are directly connected (detected using the set `s`).
6. Update the `ans` variable to be the maximum of its current value and the calculated network rank for the current city pair.
7. Return the maximum network rank found (`ans`).