# Number of Distinct Roll Sequences

- slug: number-of-distinct-roll-sequences
- difficulty: Hard

You are given an integer `n`. You roll a fair 6-sided dice `n` times. Determine the total number of **distinct** sequences of rolls possible such that the following conditions are satisfied:

1.  The **greatest common divisor** of any **adjacent** values in the sequence is equal to `1`.
2.  There is **at least** a gap of `2` rolls between **equal** valued rolls. More formally, if the value of the `ith` roll is **equal** to the value of the `jth` roll, then `abs(i - j) > 2`.

Return _the **total number** of distinct sequences possible_. Since the answer may be very large, return it **modulo** `109 + 7`.

Two sequences are considered distinct if at least one element is different.

**Example 1:**

**Input:** n = 4
**Output:** 184
**Explanation:** Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.
Some invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).
(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).
(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.
There are a total of 184 distinct sequences possible, so we return 184.

**Example 2:**

**Input:** n = 2
**Output:** 22
**Explanation:** Some of the possible sequences are (1, 2), (2, 1), (3, 2).
Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.
There are a total of 22 distinct sequences possible, so we return 22.

**Constraints:**

*   `1 <= n <= 104`

## A solution in Java

```java
public int[] bobArrows(int numArrows, int[] aliceArrows) {
    int[] bob = new int[12];
    for (int i = 11; i >= 0 && numArrows > 0; i--) {
        if (aliceArrows[i] == 0) {
            int shot = Math.min(numArrows, i + 1);
            bob[i] = shot;
            numArrows -= shot;
        }
    }
    return bob;
}
```
To maximize Bob's total points, he should prioritize shooting at sections with higher scores where Alice has not shot any arrows. The algorithm follows these steps:

1. Initialize an array `bob` representing Bob's arrows shot in each section. Fill it with zeroes.
2. Traverse the array `aliceArrows` from the last element (highest score) to the first element (lowest score).
3. If the current element of `aliceArrows` is 0 (Alice hasn't shot any arrows in the current section) and Bob still has arrows left, calculate the number of arrows Bob should shoot in this section as `min(numArrows, i+1)` (`i+1` is equal to the score of the current section).
4. Update the corresponding element of `bob` array with the number of arrows to be shot and decrement `numArrows` accordingly.
5. Repeat steps 3-4 for each section until either Bob runs out of arrows or all 12 sections have been checked.
6. Return Bob's shots taken in each section as the result.

## A solution in C++

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

vector<int> bobArrows(int numArrows, vector<int> aliceArrows) {
    vector<int> bob(12, 0);
    for (int i = 11; i >= 0 && numArrows > 0; --i) {
        if (aliceArrows[i] == 0) {
            int shot = min(numArrows, i+1);
            bob[i] = shot;
            numArrows -= shot;
        }
    }
    return bob;
}
```
To maximize Bob's total points, he should prioritize shooting at sections with higher scores where Alice has not shot any arrows. The algorithm follows these steps:

1. Initialize an array `bob` representing Bob's arrows shot in each section. Fill it with zeroes.
2. Traverse the array `aliceArrows` from the last element (highest score) to the first element (lowest score).
3. If the current element of `aliceArrows` is 0 (Alice hasn't shot any arrows in the current section) and Bob still has arrows left, calculate the number of arrows Bob should shoot in this section as `min(numArrows, i+1)` (`i+1` is equal to the score of the current section).
4. Update the corresponding element of `bob` array with the number of arrows to be shot and decrement `numArrows` accordingly.
5. Repeat steps 3-4 for each section until either Bob runs out of arrows or all 12 sections have been checked.
6. Return Bob's shots taken in each section as the result.

## A solution in Python

```python
def bob_arrows(num_arrows, alice_arrows):
    bob = [0] * 12
    for i in range(11, -1, -1):
        if num_arrows > 0 and alice_arrows[i] == 0:
            shot = min(num_arrows, i+1)
            bob[i] = shot
            num_arrows -= shot
    return bob
```
To maximize Bob's total points, he should prioritize shooting at sections with higher scores where Alice has not shot any arrows. The algorithm follows these steps:

1. Initialize an array `bob` representing Bob's arrows shot in each section. Fill it with zeroes.
2. Traverse the array `aliceArrows` from the last element (highest score) to the first element (lowest score).
3. If the current element of `aliceArrows` is 0 (Alice hasn't shot any arrows in the current section) and Bob still has arrows left, calculate the number of arrows Bob should shoot in this section as `min(numArrows, i+1)` (`i+1` is equal to the score of the current section).
4. Update the corresponding element of `bob` array with the number of arrows to be shot and decrement `numArrows` accordingly.
5. Repeat steps 3-4 for each section until either Bob runs out of arrows or all 12 sections have been checked.
6. Return Bob's shots taken in each section as the result.

## A solution in Javascript

```javascript
function bobArrows(numArrows, aliceArrows) {
    let bob = Array(12).fill(0);
    for (let i = 11; i >= 0 && numArrows > 0; i--) {
        if (aliceArrows[i] === 0) {
            let shot = Math.min(numArrows, i + 1);
            bob[i] = shot;
            numArrows -= shot;
        }
    }
    return bob;
}
```
To maximize Bob's total points, he should prioritize shooting at sections with higher scores where Alice has not shot any arrows. The algorithm follows these steps:

1. Initialize an array `bob` representing Bob's arrows shot in each section. Fill it with zeroes.
2. Traverse the array `aliceArrows` from the last element (highest score) to the first element (lowest score).
3. If the current element of `aliceArrows` is 0 (Alice hasn't shot any arrows in the current section) and Bob still has arrows left, calculate the number of arrows Bob should shoot in this section as `min(numArrows, i+1)` (`i+1` is equal to the score of the current section).
4. Update the corresponding element of `bob` array with the number of arrows to be shot and decrement `numArrows` accordingly.
5. Repeat steps 3-4 for each section until either Bob runs out of arrows or all 12 sections have been checked.
6. Return Bob's shots taken in each section as the result.


# Check if Matrix Is X-Matrix

- slug: check-if-matrix-is-x-matrix
- difficulty: Easy

A square matrix is said to be an **X-Matrix** if **both** of the following conditions hold:

1.  All the elements in the diagonals of the matrix are **non-zero**.
2.  All other elements are 0.

Given a 2D integer array `grid` of size `n x n` representing a square matrix, return `true` _if_ `grid` _is an X-Matrix_. Otherwise, return `false`.

**Example 1:**

**Input:** grid = \[\[2,0,0,1\],\[0,3,1,0\],\[0,5,2,0\],\[4,0,0,2\]\]
**Output:** true
**Explanation:** Refer to the diagram above.
An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
Thus, grid is an X-Matrix.

**Example 2:**

**Input:** grid = \[\[5,7,0\],\[0,3,1\],\[0,5,0\]\]
**Output:** false
**Explanation:** Refer to the diagram above.
An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
Thus, grid is not an X-Matrix.

**Constraints:**

*   `n == grid.length == grid[i].length`
*   `3 <= n <= 100`
*   `0 <= grid[i][j] <= 105`

## A solution in Java

```java
import java.util.ArrayList;

public ArrayList<Integer> longestRepeatSubstring(String s, String queryCharacters, int[] queryIndices) {
    int k = queryCharacters.length();
    ArrayList<Integer> lengths = new ArrayList<>();

    StringBuilder sCopy = new StringBuilder(s);

    for (int i = 0; i < k; i++) {
        sCopy.setCharAt(queryIndices[i], queryCharacters.charAt(i));
        int maxLen = 0, curLen = 1;
        for (int j = 1; j < sCopy.length(); j++) {
            if (sCopy.charAt(j) == sCopy.charAt(j-1)) {
                curLen++;
            } else {
                maxLen = Math.max(maxLen, curLen);
                curLen = 1;
            }
        }
        maxLen = Math.max(maxLen, curLen);
        lengths.add(maxLen);
    }

    return lengths;
}
```
1. Initialize an empty list/array `lengths` to store the results.
2. Create a copy of the string `s`, as we will modify it in each query.
3. Iterate through each query using a for loop based on the length of queryCharacters.
    a. Update the character at the given index in `sCopy` using the current query.
    b. Initialize `maxLen` as the maximum length of substring found so far and `curLen` as the current length of the repeating substring.
    c. Iterate through the modified string and compare adjacent characters.
        i. If the characters are the same, increment `curLen`.
        ii. If the characters are different, update `maxLen` with the greater value between `maxLen` and `curLen`, and reset `curLen` to 1.
   d. After the loop ends, update `maxLen` with the greater value between `maxLen` and `curLen`.
   e. Append `maxLen` to the `lengths` list/array.
4. Return the `lengths` list/array containing the length of the longest substring of `sCopy` consisting of only one repeating character after each query.

## A solution in C++

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

vector<int> longestRepeatSubstring(const string& s, const string& queryCharacters, const vector<int>& queryIndices) {
    int k = queryCharacters.size();
    vector<int> lengths(k);
    string sCopy = s;

    for (int i = 0; i < k; ++i) {
        sCopy[queryIndices[i]] = queryCharacters[i];
        int maxLen = 0, curLen = 1;
        for (int j = 1; j < sCopy.size(); ++j) {
            if (sCopy[j] == sCopy[j-1]) {
                curLen++;
            } else {
                maxLen = max(maxLen, curLen);
                curLen = 1;
            }
        }
        maxLen = max(maxLen, curLen);
        lengths[i] = maxLen;
    }

    return lengths;
}
```
1. Initialize an empty list/array `lengths` to store the results.
2. Create a copy of the string `s`, as we will modify it in each query.
3. Iterate through each query using a for loop based on the length of queryCharacters.
    a. Update the character at the given index in `sCopy` using the current query.
    b. Initialize `maxLen` as the maximum length of substring found so far and `curLen` as the current length of the repeating substring.
    c. Iterate through the modified string and compare adjacent characters.
        i. If the characters are the same, increment `curLen`.
        ii. If the characters are different, update `maxLen` with the greater value between `maxLen` and `curLen`, and reset `curLen` to 1.
   d. After the loop ends, update `maxLen` with the greater value between `maxLen` and `curLen`.
   e. Append `maxLen` to the `lengths` list/array.
4. Return the `lengths` list/array containing the length of the longest substring of `sCopy` consisting of only one repeating character after each query.

## A solution in Python

```python
def longest_repeat_substring(s, query_characters, query_indices):
    k = len(query_characters)
    lengths = []
    s_copy = list(s)

    for i in range(k):
        s_copy[query_indices[i]] = query_characters[i]
        max_len = cur_len = 1
        for j in range(1, len(s_copy)):
            if s_copy[j] == s_copy[j-1]:
                cur_len += 1
            else:
                max_len = max(max_len, cur_len)
                cur_len = 1
        max_len = max(max_len, cur_len)
        lengths.append(max_len)

    return lengths
```
1. Initialize an empty list/array `lengths` to store the results.
2. Create a copy of the string `s`, as we will modify it in each query.
3. Iterate through each query using a for loop based on the length of queryCharacters.
    a. Update the character at the given index in `sCopy` using the current query.
    b. Initialize `maxLen` as the maximum length of substring found so far and `curLen` as the current length of the repeating substring.
    c. Iterate through the modified string and compare adjacent characters.
        i. If the characters are the same, increment `curLen`.
        ii. If the characters are different, update `maxLen` with the greater value between `maxLen` and `curLen`, and reset `curLen` to 1.
   d. After the loop ends, update `maxLen` with the greater value between `maxLen` and `curLen`.
   e. Append `maxLen` to the `lengths` list/array.
4. Return the `lengths` list/array containing the length of the longest substring of `sCopy` consisting of only one repeating character after each query.

## A solution in Javascript

```javascript
function longestRepeatSubstring(s, queryCharacters, queryIndices) {
    const k = queryCharacters.length;
    const lengths = [];
    let sCopy = s.split('');

    for (let i = 0; i < k; i++) {
        sCopy[queryIndices[i]] = queryCharacters[i];
        let maxLen = 0, curLen = 1;
        for (let j = 1; j < sCopy.length; j++) {
            if (sCopy[j] === sCopy[j-1]) {
                curLen++;
            } else {
                maxLen = Math.max(maxLen, curLen);
                curLen = 1;
            }
        }
        maxLen = Math.max(maxLen, curLen);
        lengths.push(maxLen);
    }

    return lengths;
}
```
1. Initialize an empty list/array `lengths` to store the results.
2. Create a copy of the string `s`, as we will modify it in each query.
3. Iterate through each query using a for loop based on the length of queryCharacters.
    a. Update the character at the given index in `sCopy` using the current query.
    b. Initialize `maxLen` as the maximum length of substring found so far and `curLen` as the current length of the repeating substring.
    c. Iterate through the modified string and compare adjacent characters.
        i. If the characters are the same, increment `curLen`.
        ii. If the characters are different, update `maxLen` with the greater value between `maxLen` and `curLen`, and reset `curLen` to 1.
   d. After the loop ends, update `maxLen` with the greater value between `maxLen` and `curLen`.
   e. Append `maxLen` to the `lengths` list/array.
4. Return the `lengths` list/array containing the length of the longest substring of `sCopy` consisting of only one repeating character after each query.


# Count Number of Ways to Place Houses

- slug: count-number-of-ways-to-place-houses
- difficulty: Medium

There is a street with `n * 2` **plots**, where there are `n` plots on each side of the street. The plots on each side are numbered from `1` to `n`. On each plot, a house can be placed.

Return _the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street_. Since the answer may be very large, return it **modulo** `109 + 7`.

Note that if a house is placed on the `ith` plot on one side of the street, a house can also be placed on the `ith` plot on the other side of the street.

**Example 1:**

**Input:** n = 1
**Output:** 4
**Explanation:**
Possible arrangements:
1. All plots are empty.
2. A house is placed on one side of the street.
3. A house is placed on the other side of the street.
4. Two houses are placed, one on each side of the street.

**Example 2:**

**Input:** n = 2
**Output:** 9
**Explanation:** The 9 possible arrangements are shown in the diagram above.

**Constraints:**

*   `1 <= n <= 104`

## A solution in Java

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

public List<Integer> kDistantIndices(int[] nums, int key, int k) {
  List<Integer> result = new ArrayList<>();
  for (int i = 0; i < nums.length; i++) {
    for (int j = Math.max(0, i - k); j <= Math.min(i + k, nums.length - 1); j++) {
      if (nums[j] == key) {
        result.add(i);
        break;
      }
    }
  }
  return result;
}
```
The algorithm iterates through the nums array using a nested loop. The outer loop iterates through each index i in the nums array. The inner loop iterates through the indices j in the range [i - k, i + k]. The inner loop checks whether the value in nums[j] is equal to the key. If so, it adds i to the result list and breaks the inner loop to move on to the next index i in the outer loop. This ensures that each valid k-distant index is added to the results list only once. After completing the iteration through the nums array, the algorithm returns the result list containing all k-distant indices sorted in increasing order.

## A solution in C++

```cpp
#include <vector>

std::vector<int> kDistantIndices(std::vector<int>& nums, int key, int k) {
  std::vector<int> result;
  for (int i = 0; i < nums.size(); ++i) {
    for (int j = std::max(0, i - k); j <= std::min(i + k, static_cast<int>(nums.size()) - 1); ++j) {
      if (nums[j] == key) {
        result.push_back(i);
        break;
      }
    }
  }
  return result;
}
```
The algorithm iterates through the nums array using a nested loop. The outer loop iterates through each index i in the nums array. The inner loop iterates through the indices j in the range [i - k, i + k]. The inner loop checks whether the value in nums[j] is equal to the key. If so, it adds i to the result list and breaks the inner loop to move on to the next index i in the outer loop. This ensures that each valid k-distant index is added to the results list only once. After completing the iteration through the nums array, the algorithm returns the result list containing all k-distant indices sorted in increasing order.

## A solution in Python

```python
def k_distant_indices(nums, key, k):
    result = []
    for i in range(len(nums)):
        for j in range(max(0, i - k), min(i + k + 1, len(nums))):
            if nums[j] == key:
                result.append(i)
                break
    return result
```
The algorithm iterates through the nums array using a nested loop. The outer loop iterates through each index i in the nums array. The inner loop iterates through the indices j in the range [i - k, i + k]. The inner loop checks whether the value in nums[j] is equal to the key. If so, it adds i to the result list and breaks the inner loop to move on to the next index i in the outer loop. This ensures that each valid k-distant index is added to the results list only once. After completing the iteration through the nums array, the algorithm returns the result list containing all k-distant indices sorted in increasing order.

## A solution in Javascript

```javascript
function kDistantIndices(nums, key, k) {
  const result = [];
  for (let i = 0; i < nums.length; i++) {
    for (let j = Math.max(0, i - k); j <= Math.min(i + k, nums.length - 1); j++) {
      if (nums[j] === key) {
        result.push(i);
        break;
      }
    }
  }
  return result;
}
```
The algorithm iterates through the nums array using a nested loop. The outer loop iterates through each index i in the nums array. The inner loop iterates through the indices j in the range [i - k, i + k]. The inner loop checks whether the value in nums[j] is equal to the key. If so, it adds i to the result list and breaks the inner loop to move on to the next index i in the outer loop. This ensures that each valid k-distant index is added to the results list only once. After completing the iteration through the nums array, the algorithm returns the result list containing all k-distant indices sorted in increasing order.


# Maximum Score Of Spliced Array

- slug: maximum-score-of-spliced-array
- difficulty: Hard

You are given two **0-indexed** integer arrays `nums1` and `nums2`, both of length `n`.

You can choose two integers `left` and `right` where `0 <= left <= right < n` and **swap** the subarray `nums1[left...right]` with the subarray `nums2[left...right]`.

*   For example, if `nums1 = [1,2,3,4,5]` and `nums2 = [11,12,13,14,15]` and you choose `left = 1` and `right = 2`, `nums1` becomes `[1,**12,13**,4,5]` and `nums2` becomes `[11,**2,3**,14,15]`.

You may choose to apply the mentioned operation **once** or not do anything.

The **score** of the arrays is the **maximum** of `sum(nums1)` and `sum(nums2)`, where `sum(arr)` is the sum of all the elements in the array `arr`.

Return _the **maximum possible score**_.

A **subarray** is a contiguous sequence of elements within an array. `arr[left...right]` denotes the subarray that contains the elements of `nums` between indices `left` and `right` (**inclusive**).

**Example 1:**

**Input:** nums1 = \[60,60,60\], nums2 = \[10,90,10\]
**Output:** 210
**Explanation:** Choosing left = 1 and right = 1, we have nums1 = \[60,**90**,60\] and nums2 = \[10,**60**,10\].
The score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.

**Example 2:**

**Input:** nums1 = \[20,40,20,70,30\], nums2 = \[50,20,50,40,20\]
**Output:** 220
**Explanation:** Choosing left = 3, right = 4, we have nums1 = \[20,40,20,**40,20**\] and nums2 = \[50,20,50,**70,30**\].
The score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.

**Example 3:**

**Input:** nums1 = \[7,11,13\], nums2 = \[1,1,1\]
**Output:** 31
**Explanation:** We choose not to swap any subarray.
The score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.

**Constraints:**

*   `n == nums1.length == nums2.length`
*   `1 <= n <= 105`
*   `1 <= nums1[i], nums2[i] <= 104`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int shortestPath(int n, int[][] edges, int src1, int src2, int dest) {
        List<List<int[]>> graph = new ArrayList<>();

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

        for (int[] edge : edges) {
            graph.get(edge[0]).add(new int[]{edge[1], edge[2]});
        }

        int[] src1ToAll = dijkstra(graph, src1);
        int[] src2ToAll = dijkstra(graph, src2);

        int minWeight = Integer.MAX_VALUE;
        for (int[] edge : edges) {
            int u = edge[0];
            int v = edge[1];
            int w = edge[2];

            minWeight = Math.min(minWeight, src1ToAll[u] + w + src2ToAll[v]);
        }

        return minWeight == Integer.MAX_VALUE ? -1 : minWeight;
    }

    private int[] dijkstra(List<List<int[]>> graph, int src) {
        int n = graph.size();
        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);

        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
        dist[src] = 0;
        pq.offer(new int[]{0, src});

        while (!pq.isEmpty()) {
            int[] cur = pq.poll();
            int d = cur[0];
            int u = cur[1];

            if (d != dist[u]) continue;

            for (int[] edge : graph.get(u)) {
                int v = edge[0];
                int w = edge[1];

                if (dist[u] + w < dist[v]) {
                    dist[v] = dist[u] + w;
                    pq.offer(new int[]{dist[v], v});
                }
            }
        }

        return dist;
    }
}
```
In this problem, we need to find the minimum weight subgraph such that we can reach `dest` from both `src1` and `src2`.

1. First, we convert the input `edges` into an adjacency list representation of the input graph for easier traversal.
2. Next, we define a `dijkstra(src)` function, which takes a source node `src` as input and returns the shortest paths from `src` to all other nodes of the graph.
3. Now we find the shortest paths from `src1` to all other nodes and from `src2` to all other nodes, using the `dijkstra` function.
4. Finally, we loop over all the input edges, and for each edge (u, v, w), we sum up the weights of the shortest paths from `src1` to u, from src2 to v, and the weight w of the edge itself. We keep track of the minimum weight found, and return it.

If the minimum weight is still `INT_MAX`, `Integer.MAX_VALUE`, `float('inf')`, or `Infinity` in C++, Java, Python, and JavaScript respectively, that means there is no valid path, so we return -1. Otherwise, we return the minimum weight.

The time complexity of this solution is O(n + m * log(m)) where n is the number of nodes and m is the number of edges in the graph. This is because Dijkstra's algorithm runs in O(n + m * log(m)) and we call it twice. Also, we loop through all the edges in the end to find the minimum weight.

## A solution in C++

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

using namespace std;

int shortestPath(int n, vector<vector<int>>& edges, int src1, int src2, int dest) {
    vector<vector<pair<int, int>>> graph(n);

    for (const auto& edge : edges) {
        graph[edge[0]].emplace_back(edge[1], edge[2]);
    }

    auto dijkstra = [&](int src) {
        vector<int> dist(n, INT_MAX);
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

        dist[src] = 0;
        pq.emplace(0, src);

        while (!pq.empty()) {
            int u = pq.top().second;
            int d = pq.top().first;
            pq.pop();

            if (d != dist[u]) continue;

            for (const auto& edge : graph[u]) {
                int v = edge.first;
                int w = edge.second;

                if (dist[u] + w < dist[v]) {
                    dist[v] = dist[u] + w;
                    pq.emplace(dist[v], v);
                }
            }
        }

        return dist;
    };

    vector<int> src1_to_all = dijkstra(src1);
    vector<int> src2_to_all = dijkstra(src2);

    int min_weight = INT_MAX;
    for (const auto& edge : edges) {
        int u = edge[0];
        int v = edge[1];
        int w = edge[2];
        min_weight = min(min_weight, src1_to_all[u] + w + src2_to_all[v]);
    }

    return min_weight == INT_MAX ? -1 : min_weight;
}
```
In this problem, we need to find the minimum weight subgraph such that we can reach `dest` from both `src1` and `src2`.

1. First, we convert the input `edges` into an adjacency list representation of the input graph for easier traversal.
2. Next, we define a `dijkstra(src)` function, which takes a source node `src` as input and returns the shortest paths from `src` to all other nodes of the graph.
3. Now we find the shortest paths from `src1` to all other nodes and from `src2` to all other nodes, using the `dijkstra` function.
4. Finally, we loop over all the input edges, and for each edge (u, v, w), we sum up the weights of the shortest paths from `src1` to u, from src2 to v, and the weight w of the edge itself. We keep track of the minimum weight found, and return it.

If the minimum weight is still `INT_MAX`, `Integer.MAX_VALUE`, `float('inf')`, or `Infinity` in C++, Java, Python, and JavaScript respectively, that means there is no valid path, so we return -1. Otherwise, we return the minimum weight.

The time complexity of this solution is O(n + m * log(m)) where n is the number of nodes and m is the number of edges in the graph. This is because Dijkstra's algorithm runs in O(n + m * log(m)) and we call it twice. Also, we loop through all the edges in the end to find the minimum weight.

## A solution in Python

```python
import heapq
from collections import defaultdict

def shortest_path(n, edges, src1, src2, dest):
    graph = defaultdict(list)

    for u, v, w in edges:
        graph[u].append((v, w))

    def dijkstra(src):
        dist = [float('inf')] * n
        pq = [(0, src)]

        dist[src] = 0

        while pq:
            d, u = heapq.heappop(pq)

            if d != dist[u]:
                continue

            for v, w in graph[u]:
                if dist[u] + w < dist[v]:
                    dist[v] = dist[u] + w
                    heapq.heappush(pq, (dist[v], v))

        return dist

    src1_to_all = dijkstra(src1)
    src2_to_all = dijkstra(src2)

    min_weight = float('inf')
    for u, v, w in edges:
        min_weight = min(min_weight, src1_to_all[u] + w + src2_to_all[v])

    return -1 if min_weight == float('inf') else min_weight
```
In this problem, we need to find the minimum weight subgraph such that we can reach `dest` from both `src1` and `src2`.

1. First, we convert the input `edges` into an adjacency list representation of the input graph for easier traversal.
2. Next, we define a `dijkstra(src)` function, which takes a source node `src` as input and returns the shortest paths from `src` to all other nodes of the graph.
3. Now we find the shortest paths from `src1` to all other nodes and from `src2` to all other nodes, using the `dijkstra` function.
4. Finally, we loop over all the input edges, and for each edge (u, v, w), we sum up the weights of the shortest paths from `src1` to u, from src2 to v, and the weight w of the edge itself. We keep track of the minimum weight found, and return it.

If the minimum weight is still `INT_MAX`, `Integer.MAX_VALUE`, `float('inf')`, or `Infinity` in C++, Java, Python, and JavaScript respectively, that means there is no valid path, so we return -1. Otherwise, we return the minimum weight.

The time complexity of this solution is O(n + m * log(m)) where n is the number of nodes and m is the number of edges in the graph. This is because Dijkstra's algorithm runs in O(n + m * log(m)) and we call it twice. Also, we loop through all the edges in the end to find the minimum weight.

## A solution in Javascript

```javascript
function shortestPath(n, edges, src1, src2, dest) {
    const graph = new Array(n).fill(null).map(() => []);

    edges.forEach(([u, v, w]) => {
        graph[u].push([v, w]);
    });

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

        dist[src] = 0;

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

            if (d !== dist[u]) continue;

            for (const [v, w] of graph[u]) {
                if (dist[u] + w < dist[v]) {
                    dist[v] = dist[u] + w;
                    pq.push([dist[v], v]);
                }
            }
        }

        return dist;
    }

    const src1ToAll = dijkstra(src1);
    const src2ToAll = dijkstra(src2);

    let minWeight = Infinity;
    edges.forEach(([u, v, w]) => {
        minWeight = Math.min(minWeight, src1ToAll[u] + w + src2ToAll[v]);
    });

    return minWeight === Infinity ? -1 : minWeight;
}
```
In this problem, we need to find the minimum weight subgraph such that we can reach `dest` from both `src1` and `src2`.

1. First, we convert the input `edges` into an adjacency list representation of the input graph for easier traversal.
2. Next, we define a `dijkstra(src)` function, which takes a source node `src` as input and returns the shortest paths from `src` to all other nodes of the graph.
3. Now we find the shortest paths from `src1` to all other nodes and from `src2` to all other nodes, using the `dijkstra` function.
4. Finally, we loop over all the input edges, and for each edge (u, v, w), we sum up the weights of the shortest paths from `src1` to u, from src2 to v, and the weight w of the edge itself. We keep track of the minimum weight found, and return it.

If the minimum weight is still `INT_MAX`, `Integer.MAX_VALUE`, `float('inf')`, or `Infinity` in C++, Java, Python, and JavaScript respectively, that means there is no valid path, so we return -1. Otherwise, we return the minimum weight.

The time complexity of this solution is O(n + m * log(m)) where n is the number of nodes and m is the number of edges in the graph. This is because Dijkstra's algorithm runs in O(n + m * log(m)) and we call it twice. Also, we loop through all the edges in the end to find the minimum weight.


# Minimum Score After Removals on a Tree

- slug: minimum-score-after-removals-on-a-tree
- difficulty: Hard

There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.

You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.

Remove two **distinct** edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined:

1.  Get the XOR of all the values of the nodes for **each** of the three components respectively.
2.  The **difference** between the **largest** XOR value and the **smallest** XOR value is the **score** of the pair.

*   For example, say the three components have the node values: `[4,5,7]`, `[1,9]`, and `[3,3,3]`. The three XOR values are `4 ^ 5 ^ 7 = **6**`, `1 ^ 9 = **8**`, and `3 ^ 3 ^ 3 = **3**`. The largest XOR value is `8` and the smallest XOR value is `3`. The score is then `8 - 3 = 5`.

Return _the **minimum** score of any possible pair of edge removals on the given tree_.

**Example 1:**

**Input:** nums = \[1,5,5,4,11\], edges = \[\[0,1\],\[1,2\],\[1,3\],\[3,4\]\]
**Output:** 9
**Explanation:** The diagram above shows a way to make a pair of removals.
- The 1st component has nodes \[1,3,4\] with values \[5,4,11\]. Its XOR value is 5 ^ 4 ^ 11 = 10.
- The 2nd component has node \[0\] with value \[1\]. Its XOR value is 1 = 1.
- The 3rd component has node \[2\] with value \[5\]. Its XOR value is 5 = 5.
The score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.
It can be shown that no other pair of removals will obtain a smaller score than 9.

**Example 2:**

**Input:** nums = \[5,5,2,4,4,2\], edges = \[\[0,1\],\[1,2\],\[5,2\],\[4,3\],\[1,3\]\]
**Output:** 0
**Explanation:** The diagram above shows a way to make a pair of removals.
- The 1st component has nodes \[3,4\] with values \[4,4\]. Its XOR value is 4 ^ 4 = 0.
- The 2nd component has nodes \[1,0\] with values \[5,5\]. Its XOR value is 5 ^ 5 = 0.
- The 3rd component has nodes \[2,5\] with values \[2,2\]. Its XOR value is 2 ^ 2 = 0.
The score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.
We cannot obtain a smaller score than 0.

**Constraints:**

*   `n == nums.length`
*   `3 <= n <= 1000`
*   `1 <= nums[i] <= 108`
*   `edges.length == n - 1`
*   `edges[i].length == 2`
*   `0 <= ai, bi < n`
*   `ai != bi`
*   `edges` represents a valid tree.

## A solution in Java

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

public int dfs(int node, int parent, int[] xor_values, List<Integer>[] tree) {
    int xor_value = xor_values[node];
    for (int child : tree[node]) {
        if (child != parent) {
            xor_value ^= dfs(child, node, xor_values, tree);
        }
    }
    return xor_value;
}

public int minimumScore(int[] nums, int[][] edges) {
    int n = nums.length;
    List<Integer>[] tree = new ArrayList[n];

    for (int i = 0; i < n; i++) {
        tree[i] = new ArrayList<>();
    }

    for (int[] edge : edges) {
        tree[edge[0]].add(edge[1]);
        tree[edge[1]].add(edge[0]);
    }

    int[] xor_values = new int[n];
    for (int i = 0; i < n; i++) {
        xor_values[i] = dfs(i, -1, nums, tree);
    }

    int ans = Integer.MAX_VALUE;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int xor1 = xor_values[i];
            int xor2 = xor_values[j] ^ nums[i];
            int xor3 = nums[i] ^ nums[j];
            int max_xor = Math.max(Math.max(xor1, xor2), xor3);
            int min_xor = Math.min(Math.min(xor1, xor2), xor3);
            ans = Math.min(ans, max_xor - min_xor);
        }
    }

    return ans;
}
```
1. Construct the tree using an adjacency list.
2. Calculate the XOR values for each subtree rooted at each node using a Depth First Search function. The DFS function will return the XOR value of the subtree rooted at a specific node by XOR'ing its value with the XOR values of its children subtrees.
3. Iterate over all distinct pairs of nodes, and calculate the three XOR values using the precomputed XOR values of these nodes.
   - xor1: the XOR value of the subtree rooted at the first node
   - xor2: the XOR value of the subtree rooted at the second node without the xor1 value. This can be computed as xor_values[second_node] ^ nums[first_node] (using the property that x ^ x = 0)
   - xor3: the XOR of the remaining nodes, which can be computed as nums[first_node] ^ nums[second_node] (since xor1 ^ xor2 ^ xor3 = 0)
4. Calculate the difference between the largest and smallest among xor1, xor2, and xor3, and update the minimum score if the difference is smaller than the current minimum.
5. Return the minimum score found.

## A solution in C++

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

int dfs(int node, int parent, vector<int>& xor_values, vector<vector<int>>& tree) {
    int xor_value = xor_values[node];
    for (int child : tree[node]) {
        if (child != parent) {
            xor_value ^= dfs(child, node, xor_values, tree);
        }
    }
    return xor_value;
}

int minimumScore(vector<int>& nums, vector<vector<int>>& edges) {
    int n = nums.size();
    vector<vector<int>> tree(n);

    for (vector<int>& edge : edges) {
        tree[edge[0]].push_back(edge[1]);
        tree[edge[1]].push_back(edge[0]);
    }

    vector<int> xor_values(n);
    for (int i = 0; i < n; ++i) {
        xor_values[i] = dfs(i, -1, nums, tree);
    }

    int ans = INT_MAX;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            int xor1 = xor_values[i];
            int xor2 = xor_values[j] ^ nums[i];
            int xor3 = nums[i] ^ nums[j];
            int max_xor = max({xor1, xor2, xor3});
            int min_xor = min({xor1, xor2, xor3});
            ans = min(ans, max_xor - min_xor);
        }
    }

    return ans;
}
```
1. Construct the tree using an adjacency list.
2. Calculate the XOR values for each subtree rooted at each node using a Depth First Search function. The DFS function will return the XOR value of the subtree rooted at a specific node by XOR'ing its value with the XOR values of its children subtrees.
3. Iterate over all distinct pairs of nodes, and calculate the three XOR values using the precomputed XOR values of these nodes.
   - xor1: the XOR value of the subtree rooted at the first node
   - xor2: the XOR value of the subtree rooted at the second node without the xor1 value. This can be computed as xor_values[second_node] ^ nums[first_node] (using the property that x ^ x = 0)
   - xor3: the XOR of the remaining nodes, which can be computed as nums[first_node] ^ nums[second_node] (since xor1 ^ xor2 ^ xor3 = 0)
4. Calculate the difference between the largest and smallest among xor1, xor2, and xor3, and update the minimum score if the difference is smaller than the current minimum.
5. Return the minimum score found.

## A solution in Python

```python
def dfs(node, parent, xor_values, tree):
    xor_value = xor_values[node]
    for child in tree[node]:
        if child != parent:
            xor_value ^= dfs(child, node, xor_values, tree)
    return xor_value

def minimumScore(nums, edges):
    n = len(nums)
    tree = [[] for _ in range(n)]

    for edge in edges:
        tree[edge[0]].append(edge[1])
        tree[edge[1]].append(edge[0])

    xor_values = [dfs(i, -1, nums, tree) for i in range(n)]

    ans = float('inf')
    for i in range(n):
        for j in range(i + 1, n):
            xor1 = xor_values[i]
            xor2 = xor_values[j] ^ nums[i]
            xor3 = nums[i] ^ nums[j]
            max_xor = max(xor1, xor2, xor3)
            min_xor = min(xor1, xor2, xor3)
            ans = min(ans, max_xor - min_xor)

    return ans
```
1. Construct the tree using an adjacency list.
2. Calculate the XOR values for each subtree rooted at each node using a Depth First Search function. The DFS function will return the XOR value of the subtree rooted at a specific node by XOR'ing its value with the XOR values of its children subtrees.
3. Iterate over all distinct pairs of nodes, and calculate the three XOR values using the precomputed XOR values of these nodes.
   - xor1: the XOR value of the subtree rooted at the first node
   - xor2: the XOR value of the subtree rooted at the second node without the xor1 value. This can be computed as xor_values[second_node] ^ nums[first_node] (using the property that x ^ x = 0)
   - xor3: the XOR of the remaining nodes, which can be computed as nums[first_node] ^ nums[second_node] (since xor1 ^ xor2 ^ xor3 = 0)
4. Calculate the difference between the largest and smallest among xor1, xor2, and xor3, and update the minimum score if the difference is smaller than the current minimum.
5. Return the minimum score found.

## A solution in Javascript

```javascript
function dfs(node, parent, xor_values, tree) {
    let xor_value = xor_values[node];
    for (let child of tree[node]) {
        if (child !== parent) {
            xor_value ^= dfs(child, node, xor_values, tree);
        }
    }
    return xor_value;
}

function minimumScore(nums, edges) {
    const n = nums.length;
    const tree = Array.from({length: n}, () => []);

    for (let edge of edges) {
        tree[edge[0]].push(edge[1]);
        tree[edge[1]].push(edge[0]);
    }

    const xor_values = Array.from({length: n}, (_, i) => dfs(i, -1, nums, tree));

    let ans = Infinity;
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            const xor1 = xor_values[i];
            const xor2 = xor_values[j] ^ nums[i];
            const xor3 = nums[i] ^ nums[j];
            const max_xor = Math.max(xor1, xor2, xor3);
            const min_xor = Math.min(xor1, xor2, xor3);
            ans = Math.min(ans, max_xor - min_xor);
        }
    }

    return ans;
}
```
1. Construct the tree using an adjacency list.
2. Calculate the XOR values for each subtree rooted at each node using a Depth First Search function. The DFS function will return the XOR value of the subtree rooted at a specific node by XOR'ing its value with the XOR values of its children subtrees.
3. Iterate over all distinct pairs of nodes, and calculate the three XOR values using the precomputed XOR values of these nodes.
   - xor1: the XOR value of the subtree rooted at the first node
   - xor2: the XOR value of the subtree rooted at the second node without the xor1 value. This can be computed as xor_values[second_node] ^ nums[first_node] (using the property that x ^ x = 0)
   - xor3: the XOR of the remaining nodes, which can be computed as nums[first_node] ^ nums[second_node] (since xor1 ^ xor2 ^ xor3 = 0)
4. Calculate the difference between the largest and smallest among xor1, xor2, and xor3, and update the minimum score if the difference is smaller than the current minimum.
5. Return the minimum score found.


# Find Minimum Time to Finish All Jobs II

- slug: find-minimum-time-to-finish-all-jobs-ii
- difficulty: Medium

You are given two **0-indexed** integer arrays `jobs` and `workers` of **equal** length, where `jobs[i]` is the amount of time needed to complete the `ith` job, and `workers[j]` is the amount of time the `jth` worker can work each day.

Each job should be assigned to **exactly** one worker, such that each worker completes **exactly** one job.

Return _the **minimum** number of days needed to complete all the jobs after assignment._

**Example 1:**

**Input:** jobs = \[5,2,4\], workers = \[1,7,5\]
**Output:** 2
**Explanation:**
- Assign the 2nd worker to the 0th job. It takes them 1 day to finish the job.
- Assign the 0th worker to the 1st job. It takes them 2 days to finish the job.
- Assign the 1st worker to the 2nd job. It takes them 1 day to finish the job.
It takes 2 days for all the jobs to be completed, so return 2.
It can be proven that 2 days is the minimum number of days needed.

**Example 2:**

**Input:** jobs = \[3,18,15,9\], workers = \[6,5,1,3\]
**Output:** 3
**Explanation:**
- Assign the 2nd worker to the 0th job. It takes them 3 days to finish the job.
- Assign the 0th worker to the 1st job. It takes them 3 days to finish the job.
- Assign the 1st worker to the 2nd job. It takes them 3 days to finish the job.
- Assign the 3rd worker to the 3rd job. It takes them 3 days to finish the job.
It takes 3 days for all the jobs to be completed, so return 3.
It can be proven that 3 days is the minimum number of days needed.

**Constraints:**

*   `n == jobs.length == workers.length`
*   `1 <= n <= 105`
*   `1 <= jobs[i], workers[i] <= 105`

## A solution in Java

```java
public int minBitFlips(int start, int goal) {
    int xorValue = start ^ goal;
    int flips = 0;
    while (xorValue != 0) {
        flips += xorValue & 1;
        xorValue >>= 1;
    }
    return flips;
}
```
The algorithm for solving this problem consists of the following steps:

1. Use bitwise XOR (^) to get a binary value representing the differing bits between 'start' and 'goal'.
2. Iterate through the binary XOR value counting the number of 1's, which represent the required bit flips.
3. End when all the bits have been parsed and return the number of flips required.

This approach has a time complexity of O(log n), where n is the larger of the two input integers.

## A solution in C++

```cpp
int minBitFlips(int start, int goal) {
    int xorValue = start ^ goal;
    int flips = 0;
    while (xorValue) {
        flips += xorValue & 1;
        xorValue >>= 1;
    }
    return flips;
}
```
The algorithm for solving this problem consists of the following steps:

1. Use bitwise XOR (^) to get a binary value representing the differing bits between 'start' and 'goal'.
2. Iterate through the binary XOR value counting the number of 1's, which represent the required bit flips.
3. End when all the bits have been parsed and return the number of flips required.

This approach has a time complexity of O(log n), where n is the larger of the two input integers.

## A solution in Python

```python
def min_bit_flips(start, goal):
    xor_value = start ^ goal
    flips = 0
    while xor_value:
        flips += xor_value & 1
        xor_value >>= 1
    return flips
```
The algorithm for solving this problem consists of the following steps:

1. Use bitwise XOR (^) to get a binary value representing the differing bits between 'start' and 'goal'.
2. Iterate through the binary XOR value counting the number of 1's, which represent the required bit flips.
3. End when all the bits have been parsed and return the number of flips required.

This approach has a time complexity of O(log n), where n is the larger of the two input integers.

## A solution in Javascript

```javascript
function minBitFlips(start, goal) {
    let xorValue = start ^ goal;
    let flips = 0;
    while (xorValue) {
        flips += xorValue & 1;
        xorValue >>= 1;
    }
    return flips;
}
```
The algorithm for solving this problem consists of the following steps:

1. Use bitwise XOR (^) to get a binary value representing the differing bits between 'start' and 'goal'.
2. Iterate through the binary XOR value counting the number of 1's, which represent the required bit flips.
3. End when all the bits have been parsed and return the number of flips required.

This approach has a time complexity of O(log n), where n is the larger of the two input integers.


# Decode the Message

- slug: decode-the-message
- difficulty: Easy

You are given the strings `key` and `message`, which represent a cipher key and a secret message, respectively. The steps to decode `message` are as follows:

1.  Use the **first** appearance of all 26 lowercase English letters in `key` as the **order** of the substitution table.
2.  Align the substitution table with the regular English alphabet.
3.  Each letter in `message` is then **substituted** using the table.
4.  Spaces `' '` are transformed to themselves.

*   For example, given `key = "**hap**p**y** **bo**y "` (actual key would have **at least one** instance of each letter in the alphabet), we have the partial substitution table of (`'h' -> 'a'`, `'a' -> 'b'`, `'p' -> 'c'`, `'y' -> 'd'`, `'b' -> 'e'`, `'o' -> 'f'`).

Return _the decoded message_.

**Example 1:**

**Input:** key =  "the quick brown fox jumps over the lazy dog ", message =  "vkbs bs t suepuv "
**Output:**  "this is a secret "
**Explanation:** The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in  "**the** **quick** **brown** **f**o**x** **j**u**mps** o**v**er the **lazy** **d**o**g** ".

**Example 2:**

**Input:** key =  "eljuxhpwnyrdgtqkviszcfmabo ", message =  "zwx hnfx lqantp mnoeius ycgk vcnjrdb "
**Output:**  "the five boxing wizards jump quickly "
**Explanation:** The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in  "**eljuxhpwnyrdgtqkviszcfmabo** ".

**Constraints:**

*   `26 <= key.length <= 2000`
*   `key` consists of lowercase English letters and `' '`.
*   `key` contains every letter in the English alphabet (`'a'` to `'z'`) **at least once**.
*   `1 <= message.length <= 2000`
*   `message` consists of lowercase English letters and `' '`.

## A solution in Java

```java
public int validSelections(String s) {
    int res = 0;
    for (int i = 1; i < s.length() - 1; i++) {
        if (!s.substring(i - 1, i).equals(s.substring(i, i + 1)) &&
            !s.substring(i, i + 1).equals(s.substring(i + 1, i + 2)) &&
            !s.substring(i - 1, i).equals(s.substring(i + 1, i + 2))) {
            res++;
        }
    }
    return res;
}
```
We iterate through the binary string `s` starting from index 1 till the second-last character in the string. For each character `s[i]`, we check three conditions:
1. s[i-1] should be different from s[i]
2. s[i] should be different from s[i+1]
3. s[i+1] should be different from s[i-1]

If all these conditions are met for the current index `i`, then we can increment the result counter. Finally, we return the result counter, which is the number of valid ways to select 3 buildings.

## A solution in C++

```cpp
#include <string>

int validSelections(const std::string& s) {
    int res = 0;
    for (int i = 1; i < s.size() - 1; ++i) {
        if (s[i - 1] != s[i] && s[i] != s[i + 1] && s[i + 1] != s[i - 1]) {
            res++;
        }
    }
    return res;
}
```
We iterate through the binary string `s` starting from index 1 till the second-last character in the string. For each character `s[i]`, we check three conditions:
1. s[i-1] should be different from s[i]
2. s[i] should be different from s[i+1]
3. s[i+1] should be different from s[i-1]

If all these conditions are met for the current index `i`, then we can increment the result counter. Finally, we return the result counter, which is the number of valid ways to select 3 buildings.

## A solution in Python

```python
def valid_selections(s: str) -> int:
    res = 0
    for i in range(1, len(s) - 1):
        if s[i - 1] != s[i] and s[i] != s[i + 1] and s[i - 1] != s[i + 1]:
            res += 1
    return res
```
We iterate through the binary string `s` starting from index 1 till the second-last character in the string. For each character `s[i]`, we check three conditions:
1. s[i-1] should be different from s[i]
2. s[i] should be different from s[i+1]
3. s[i+1] should be different from s[i-1]

If all these conditions are met for the current index `i`, then we can increment the result counter. Finally, we return the result counter, which is the number of valid ways to select 3 buildings.

## A solution in Javascript

```javascript
function validSelections(s) {
    let res = 0;
    for (let i = 1; i < s.length - 1; i++) {
        if (s[i - 1] !== s[i] && s[i] !== s[i + 1] && s[i - 1] !== s[i + 1]) {
            res++;
        }
    }
    return res;
}
```
We iterate through the binary string `s` starting from index 1 till the second-last character in the string. For each character `s[i]`, we check three conditions:
1. s[i-1] should be different from s[i]
2. s[i] should be different from s[i+1]
3. s[i+1] should be different from s[i-1]

If all these conditions are met for the current index `i`, then we can increment the result counter. Finally, we return the result counter, which is the number of valid ways to select 3 buildings.


# Spiral Matrix IV

- slug: spiral-matrix-iv
- difficulty: Medium

You are given two integers `m` and `n`, which represent the dimensions of a matrix.

You are also given the `head` of a linked list of integers.

Generate an `m x n` matrix that contains the integers in the linked list presented in **spiral** order **(clockwise)**, starting from the **top-left** of the matrix. If there are remaining empty spaces, fill them with `-1`.

Return _the generated matrix_.

**Example 1:**

**Input:** m = 3, n = 5, head = \[3,0,2,6,8,1,7,9,4,2,5,5,0\]
**Output:** \[\[3,0,2,6,8\],\[5,0,-1,-1,1\],\[5,2,4,9,7\]\]
**Explanation:** The diagram above shows how the values are printed in the matrix.
Note that the remaining spaces in the matrix are filled with -1.

**Example 2:**

**Input:** m = 1, n = 4, head = \[0,1,2\]
**Output:** \[\[0,1,2,-1\]\]
**Explanation:** The diagram above shows how the values are printed from left to right in the matrix.
The last space in the matrix is set to -1.

**Constraints:**

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

## A solution in Java

```java
public int sumPrefixScores(String s) {
    int n = s.length();
    int sumScores = 0;
    int longestCommonPrefix = 0;
    for (int i = n - 1; i >= 0; i--) {
        if (s.charAt(i) == s.charAt(n - 1 - longestCommonPrefix)) {
            longestCommonPrefix++;
        } else {
            longestCommonPrefix = 0;
        }
        sumScores += longestCommonPrefix;
    }
    return sumScores;
}
```
We iterate through the input string in reverse order. For each character, we check if it is equal to the corresponding character in the longest common prefix (LCP) of s[i] and s[n]. If they are equal, we increment the LCP, otherwise, we set the LCP to zero. The sum of the scores is updated by adding the current value of LCP to the running sum. Finally, the sum of all LCP scores is returned.

## A solution in C++

```cpp
#include <string>

int sum_prefix_scores(const std::string& s) {
    int n = s.length();
    int sum_scores = 0;
    int longest_common_prefix = 0;
    for (int i = n - 1; i >= 0; --i) {
        if (s[i] == s[n - 1 - longest_common_prefix]) {
            longest_common_prefix++;
        } else {
            longest_common_prefix = 0;
        }
        sum_scores += longest_common_prefix;
    }
    return sum_scores;
}
```
We iterate through the input string in reverse order. For each character, we check if it is equal to the corresponding character in the longest common prefix (LCP) of s[i] and s[n]. If they are equal, we increment the LCP, otherwise, we set the LCP to zero. The sum of the scores is updated by adding the current value of LCP to the running sum. Finally, the sum of all LCP scores is returned.

## A solution in Python

```python
def sum_prefix_scores(s: str) -> int:
    n = len(s)
    sum_scores = 0
    longest_common_prefix = 0
    for i in range(n - 1, -1, -1):
        if s[i] == s[n - 1 - longest_common_prefix]:
            longest_common_prefix += 1
        else:
            longest_common_prefix = 0
        sum_scores += longest_common_prefix
    return sum_scores
```
We iterate through the input string in reverse order. For each character, we check if it is equal to the corresponding character in the longest common prefix (LCP) of s[i] and s[n]. If they are equal, we increment the LCP, otherwise, we set the LCP to zero. The sum of the scores is updated by adding the current value of LCP to the running sum. Finally, the sum of all LCP scores is returned.

## A solution in Javascript

```javascript
function sumPrefixScores(s) {
    let n = s.length;
    let sumScores = 0;
    let longestCommonPrefix = 0;
    for (let i = n - 1; i >= 0; i--) {
        if (s[i] === s[n - 1 - longestCommonPrefix]) {
            longestCommonPrefix++;
        } else {
            longestCommonPrefix = 0;
        }
        sumScores += longestCommonPrefix;
    }
    return sumScores;
}
```
We iterate through the input string in reverse order. For each character, we check if it is equal to the corresponding character in the longest common prefix (LCP) of s[i] and s[n]. If they are equal, we increment the LCP, otherwise, we set the LCP to zero. The sum of the scores is updated by adding the current value of LCP to the running sum. Finally, the sum of all LCP scores is returned.


# Number of People Aware of a Secret

- slug: number-of-people-aware-of-a-secret
- difficulty: Medium

On day `1`, one person discovers a secret.

You are given an integer `delay`, which means that each person will **share** the secret with a new person **every day**, starting from `delay` days after discovering the secret. You are also given an integer `forget`, which means that each person will **forget** the secret `forget` days after discovering it. A person **cannot** share the secret on the same day they forgot it, or on any day afterwards.

Given an integer `n`, return _the number of people who know the secret at the end of day_ `n`. Since the answer may be very large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** n = 6, delay = 2, forget = 4
**Output:** 5
**Explanation:**
Day 1: Suppose the first person is named A. (1 person)
Day 2: A is the only person who knows the secret. (1 person)
Day 3: A shares the secret with a new person, B. (2 people)
Day 4: A shares the secret with a new person, C. (3 people)
Day 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)
Day 6: B shares the secret with E, and C shares the secret with F. (5 people)

**Example 2:**

**Input:** n = 4, delay = 1, forget = 3
**Output:** 6
**Explanation:**
Day 1: The first person is named A. (1 person)
Day 2: A shares the secret with B. (2 people)
Day 3: A and B share the secret with 2 new people, C and D. (4 people)
Day 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)

**Constraints:**

*   `2 <= n <= 1000`
*   `1 <= delay < forget <= n`

## A solution in Java

```java
import java.util.Arrays;

public int largestSwapPermutations(int num) {
    String numStr = String.valueOf(num);
    char[] evenDigits = numStr.replaceAll("[13579]", "").toCharArray();
    char[] oddDigits = numStr.replaceAll("[02468]", "").toCharArray();

    Arrays.sort(evenDigits);
    Arrays.sort(oddDigits);

    StringBuilder result = new StringBuilder();

    for (char c : numStr.toCharArray()) {
        if (Character.getNumericValue(c) % 2 == 0) {
            result.insert(0, evenDigits[evenDigits.length - 1]);
            evenDigits = Arrays.copyOf(evenDigits, evenDigits.length - 1);
        } else {
            result.insert(0, oddDigits[oddDigits.length - 1]);
            oddDigits = Arrays.copyOf(oddDigits, oddDigits.length - 1);
        }
    }

    return Integer.parseInt(result.toString());
}
```
1. Convert the input integer to a string.
2. Create two lists, one for even digits and the other for odd digits. Add each digit from the input string to the appropriate list.
3. Sort both lists of even and odd digits in descending order.
4. Create an empty string called `result`.
5. Iterate over the input string. For each digit, check if it's even or odd. Then, take the first element from the corresponding sorted list (either even or odd) and append it to `result`. Remove the element from the list after appending it.
6. Convert the result string back to an integer and return it.

## A solution in C++

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

std::string largestSwap(std::string num) {
    std::string even_digits = "";
    std::string odd_digits = "";

    for (char c : num) {
        if ((c - '0') % 2 == 0) {
            even_digits.push_back(c);
        } else {
            odd_digits.push_back(c);
        }
    }

    std::sort(even_digits.rbegin(), even_digits.rend());
    std::sort(odd_digits.rbegin(), odd_digits.rend());

    std::string result = "";
    size_t even_index = 0, odd_index = 0;

    for (char c : num) {
        if ((c - '0') % 2 == 0) {
            result.push_back(even_digits[even_index++]);
        } else {
            result.push_back(odd_digits[odd_index++]);
        }
    }

    return result;
}

int largestSwapPermutations(int num) {
    std::string num_str = std::to_string(num);
    return std::stoi(largestSwap(num_str));
}
```
1. Convert the input integer to a string.
2. Create two lists, one for even digits and the other for odd digits. Add each digit from the input string to the appropriate list.
3. Sort both lists of even and odd digits in descending order.
4. Create an empty string called `result`.
5. Iterate over the input string. For each digit, check if it's even or odd. Then, take the first element from the corresponding sorted list (either even or odd) and append it to `result`. Remove the element from the list after appending it.
6. Convert the result string back to an integer and return it.

## A solution in Python

```python
def largest_swap_permutations(num):
    num_str = str(num)
    even_digits = sorted([c for c in num_str if int(c) % 2 == 0], reverse=True)
    odd_digits = sorted([c for c in num_str if int(c) % 2 == 1], reverse=True)

    result = []
    for c in num_str:
        if int(c) % 2 == 0:
            result.append(even_digits.pop(0))
        else:
            result.append(odd_digits.pop(0))

    return int(''.join(result))
```
1. Convert the input integer to a string.
2. Create two lists, one for even digits and the other for odd digits. Add each digit from the input string to the appropriate list.
3. Sort both lists of even and odd digits in descending order.
4. Create an empty string called `result`.
5. Iterate over the input string. For each digit, check if it's even or odd. Then, take the first element from the corresponding sorted list (either even or odd) and append it to `result`. Remove the element from the list after appending it.
6. Convert the result string back to an integer and return it.

## A solution in Javascript

```javascript
function largestSwapPermutations(num) {
    const numStr = num.toString();
    const evenDigits = numStr.split('').filter(c => c % 2 === 0).sort((a, b) => b - a);
    const oddDigits = numStr.split('').filter(c => c % 2 !== 0).sort((a, b) => b - a);

    const result = numStr.split('').map(c => {
        if (c % 2 === 0) {
            return evenDigits.shift();
        } else {
            return oddDigits.shift();
        }
    }).join('');

    return parseInt(result, 10);
}
```
1. Convert the input integer to a string.
2. Create two lists, one for even digits and the other for odd digits. Add each digit from the input string to the appropriate list.
3. Sort both lists of even and odd digits in descending order.
4. Create an empty string called `result`.
5. Iterate over the input string. For each digit, check if it's even or odd. Then, take the first element from the corresponding sorted list (either even or odd) and append it to `result`. Remove the element from the list after appending it.
6. Convert the result string back to an integer and return it.


# Number of Increasing Paths in a Grid

- slug: number-of-increasing-paths-in-a-grid
- difficulty: Hard

You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions.

Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `109 + 7`.

Two paths are considered different if they do not have exactly the same sequence of visited cells.

**Example 1:**

**Input:** grid = \[\[1,1\],\[3,4\]\]
**Output:** 8
**Explanation:** The strictly increasing paths are:
- Paths with length 1: \[1\], \[1\], \[3\], \[4\].
- Paths with length 2: \[1 -> 3\], \[1 -> 4\], \[3 -> 4\].
- Paths with length 3: \[1 -> 3 -> 4\].
The total number of paths is 4 + 3 + 1 = 8.

**Example 2:**

**Input:** grid = \[\[1\],\[2\]\]
**Output:** 3
**Explanation:** The strictly increasing paths are:
- Paths with length 1: \[1\], \[2\].
- Paths with length 2: \[1 -> 2\].
The total number of paths is 2 + 1 = 3.

**Constraints:**

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

## A solution in Java

```java
public String addParentheses(String expression) {
    return "(" + expression + ")";
}
```
The algorithm simply takes input expression and adds an opening parenthesis at the beginning of the expression, and a closing parenthesis at the end of the expression. Since the expression is in the form of "<num1>+<num2>", adding parenthesis around the whole expression does not change the value. Thus, it returns the smallest possible value as originally asked.

## A solution in C++

```cpp
#include<string>

std::string addParentheses(std::string expression) {
    return "(" + expression + ")";
}
```
The algorithm simply takes input expression and adds an opening parenthesis at the beginning of the expression, and a closing parenthesis at the end of the expression. Since the expression is in the form of "<num1>+<num2>", adding parenthesis around the whole expression does not change the value. Thus, it returns the smallest possible value as originally asked.

## A solution in Python

```python
def add_parentheses(expression: str) -> str:
    return f"({expression})"
```
The algorithm simply takes input expression and adds an opening parenthesis at the beginning of the expression, and a closing parenthesis at the end of the expression. Since the expression is in the form of "<num1>+<num2>", adding parenthesis around the whole expression does not change the value. Thus, it returns the smallest possible value as originally asked.

## A solution in Javascript

```javascript
function addParentheses(expression) {
    return "(" + expression + ")";
}
```
The algorithm simply takes input expression and adds an opening parenthesis at the beginning of the expression, and a closing parenthesis at the end of the expression. Since the expression is in the form of "<num1>+<num2>", adding parenthesis around the whole expression does not change the value. Thus, it returns the smallest possible value as originally asked.


# Valid Palindrome IV

- slug: valid-palindrome-iv
- difficulty: Medium

You are given a **0-indexed** string `s` consisting of only lowercase English letters. In one operation, you can change **any** character of `s` to any **other** character.

Return `true` _if you can make_ `s` _a palindrome after performing **exactly** one or two operations, or return_ `false` _otherwise._

**Example 1:**

**Input:** s =  "abcdba "
**Output:** true
**Explanation:** One way to make s a palindrome using 1 operation is:
- Change s\[2\] to 'd'. Now, s =  "abddba ".
One operation could be performed to make s a palindrome so return true.

**Example 2:**

**Input:** s =  "aa "
**Output:** true
**Explanation:** One way to make s a palindrome using 2 operations is:
- Change s\[0\] to 'b'. Now, s =  "ba ".
- Change s\[1\] to 'b'. Now, s =  "bb ".
Two operations could be performed to make s a palindrome so return true.

**Example 3:**

**Input:** s =  "abcdef "
**Output:** false
**Explanation:** It is not possible to make s a palindrome using one or two operations so return false.

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int maxBeauty(int[] flowers, int newFlowers, int target, int full, int partial) {
    int beauty = 0;
    for (int f : flowers)
        beauty += (f >= target) ? full : partial * f;

    Arrays.sort(flowers);

    for (int i = 0; i < flowers.length && newFlowers > 0; ++i) {
        int needed = target - flowers[i];
        if (needed <= newFlowers) {
            beauty += full - partial * flowers[i];
            flowers[i] = target;
            newFlowers -= needed;
        }
    }

    return beauty;
}
```
1. Calculate the initial beauty of the gardens using the number of flowers already planted.
2. Sort the gardens by the number of flowers in non-descending order.
3. For each garden (in non-descending order):
   a. Calculate the number of flowers needed to reach the target.
   b. If the number of needed flowers is less than or equal to the maximum number of new flowers Alice can plant, then update the beauty of the gardens, set this particular garden's number of flowers to the target, and subtract the number of needed flowers from newFlowers.
4. Return the maximum total beauty after planting newFlowers.

## A solution in C++

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

int maxBeauty(std::vector<int>& flowers, int newFlowers, int target, int full, int partial) {
    int beauty = 0;
    for (int f : flowers)
        beauty += (f >= target) ? full : partial * f;

    std::sort(flowers.begin(), flowers.end());

    for (int i = 0; i < flowers.size() && newFlowers > 0; ++i) {
        int needed = target - flowers[i];
        if (needed <= newFlowers) {
            beauty += full - partial * flowers[i];
            flowers[i] = target;
            newFlowers -= needed;
        }
    }

    return beauty;
}
```
1. Calculate the initial beauty of the gardens using the number of flowers already planted.
2. Sort the gardens by the number of flowers in non-descending order.
3. For each garden (in non-descending order):
   a. Calculate the number of flowers needed to reach the target.
   b. If the number of needed flowers is less than or equal to the maximum number of new flowers Alice can plant, then update the beauty of the gardens, set this particular garden's number of flowers to the target, and subtract the number of needed flowers from newFlowers.
4. Return the maximum total beauty after planting newFlowers.

## A solution in Python

```python
def max_beauty(flowers, new_flowers, target, full, partial):
    beauty = sum(full if f >= target else partial * f for f in flowers)
    flowers.sort()

    for i in range(len(flowers)):
        needed = target - flowers[i]
        if needed <= new_flowers:
            beauty += full - partial * flowers[i]
            flowers[i] = target
            new_flowers -= needed

    return beauty
```
1. Calculate the initial beauty of the gardens using the number of flowers already planted.
2. Sort the gardens by the number of flowers in non-descending order.
3. For each garden (in non-descending order):
   a. Calculate the number of flowers needed to reach the target.
   b. If the number of needed flowers is less than or equal to the maximum number of new flowers Alice can plant, then update the beauty of the gardens, set this particular garden's number of flowers to the target, and subtract the number of needed flowers from newFlowers.
4. Return the maximum total beauty after planting newFlowers.

## A solution in Javascript

```javascript
function maxBeauty(flowers, newFlowers, target, full, partial) {
    let beauty = flowers.reduce((acc, f) => acc + (f >= target ? full : partial * f), 0);
    flowers.sort((a, b) => a - b);

    for (let i = 0; i < flowers.length && newFlowers > 0; ++i) {
        let needed = target - flowers[i];
        if (needed <= newFlowers) {
            beauty += full - partial * flowers[i];
            flowers[i] = target;
            newFlowers -= needed;
        }
    }

    return beauty;
}
```
1. Calculate the initial beauty of the gardens using the number of flowers already planted.
2. Sort the gardens by the number of flowers in non-descending order.
3. For each garden (in non-descending order):
   a. Calculate the number of flowers needed to reach the target.
   b. If the number of needed flowers is less than or equal to the maximum number of new flowers Alice can plant, then update the beauty of the gardens, set this particular garden's number of flowers to the target, and subtract the number of needed flowers from newFlowers.
4. Return the maximum total beauty after planting newFlowers.


# Evaluate Boolean Binary Tree

- slug: evaluate-boolean-binary-tree
- difficulty: Easy

You are given the `root` of a **full binary tree** with the following properties:

*   **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`.
*   **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `AND`.

The **evaluation** of a node is as follows:

*   If the node is a leaf node, the evaluation is the **value** of the node, i.e. `True` or `False`.
*   Otherwise, **evaluate** the node's two children and **apply** the boolean operation of its value with the children's evaluations.

Return _the boolean result of **evaluating** the_ `root` _node._

A **full binary tree** is a binary tree where each node has either `0` or `2` children.

A **leaf node** is a node that has zero children.

**Example 1:**

**Input:** root = \[2,1,3,null,null,0,1\]
**Output:** true
**Explanation:** The above diagram illustrates the evaluation process.
The AND node evaluates to False AND True = False.
The OR node evaluates to True OR False = True.
The root node evaluates to True, so we return true.

**Example 2:**

**Input:** root = \[0\]
**Output:** false
**Explanation:** The root node is a leaf node and it evaluates to false, so we return false.

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 1000]`.
*   `0 <= Node.val <= 3`
*   Every node has either `0` or `2` children.
*   Leaf nodes have a value of `0` or `1`.
*   Non-leaf nodes have a value of `2` or `3`.

## A solution in Java

```java
public boolean evalTree(TreeNode root) {
    if (root.left == null && root.right == null)
        return root.val == 1;
    boolean left = evalTree(root.left);
    boolean right = evalTree(root.right);

    if (root.val == 2)
        return left || right;
    return left && right;
}
```
This problem uses a binary tree to calculate boolean values.

The algorithm for this problem is a recursive depth-first search.
1. If the current node is a leaf node, return its value (`True` / `False`).
2. If the current node is a non-leaf node, recursively compute the values of its left and right children.
3. If the current node is an `OR` node, return the result of `left || right`. If it's an `AND` node, return the result of `left && right`.

The base case here is when the node is a leaf node, and the recursion will stop, returning its boolean value. At each level of recursion, it will evaluate the operator associated with the node and build up the final result.

## A solution in C++

```cpp
bool evalTree(TreeNode* root) {
    if (!root->left && !root->right)
        return root->val;
    bool left = evalTree(root->left);
    bool right = evalTree(root->right);

    if (root->val == 2)
        return left || right;
    return left && right;
}
```
This problem uses a binary tree to calculate boolean values.

The algorithm for this problem is a recursive depth-first search.
1. If the current node is a leaf node, return its value (`True` / `False`).
2. If the current node is a non-leaf node, recursively compute the values of its left and right children.
3. If the current node is an `OR` node, return the result of `left || right`. If it's an `AND` node, return the result of `left && right`.

The base case here is when the node is a leaf node, and the recursion will stop, returning its boolean value. At each level of recursion, it will evaluate the operator associated with the node and build up the final result.

## A solution in Python

```python
def evalTree(root: 'TreeNode') -> bool:
    if not root.left and not root.right:
        return root.val == 1
    left = evalTree(root.left)
    right = evalTree(root.right)

    if root.val == 2:
        return left or right
    return left and right
```
This problem uses a binary tree to calculate boolean values.

The algorithm for this problem is a recursive depth-first search.
1. If the current node is a leaf node, return its value (`True` / `False`).
2. If the current node is a non-leaf node, recursively compute the values of its left and right children.
3. If the current node is an `OR` node, return the result of `left || right`. If it's an `AND` node, return the result of `left && right`.

The base case here is when the node is a leaf node, and the recursion will stop, returning its boolean value. At each level of recursion, it will evaluate the operator associated with the node and build up the final result.

## A solution in Javascript

```javascript
function evalTree(root) {
    if (!root.left && !root.right)
        return root.val === 1;
    const left = evalTree(root.left);
    const right = evalTree(root.right);

    if (root.val === 2)
        return left || right;
    return left && right;
}
```
This problem uses a binary tree to calculate boolean values.

The algorithm for this problem is a recursive depth-first search.
1. If the current node is a leaf node, return its value (`True` / `False`).
2. If the current node is a non-leaf node, recursively compute the values of its left and right children.
3. If the current node is an `OR` node, return the result of `left || right`. If it's an `AND` node, return the result of `left && right`.

The base case here is when the node is a leaf node, and the recursion will stop, returning its boolean value. At each level of recursion, it will evaluate the operator associated with the node and build up the final result.


# The Latest Time to Catch a Bus

- slug: the-latest-time-to-catch-a-bus
- difficulty: Medium

You are given a **0-indexed** integer array `buses` of length `n`, where `buses[i]` represents the departure time of the `ith` bus. You are also given a **0-indexed** integer array `passengers` of length `m`, where `passengers[j]` represents the arrival time of the `jth` passenger. All bus departure times are unique. All passenger arrival times are unique.

You are given an integer `capacity`, which represents the **maximum** number of passengers that can get on each bus.

When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at `x` minutes if you arrive at `y` minutes where `y <= x`, and the bus is not full. Passengers with the **earliest** arrival times get on the bus first.

More formally when a bus arrives, either:

*   If `capacity` or fewer passengers are waiting for a bus, they will **all** get on the bus, or
*   The `capacity` passengers with the **earliest** arrival times will get on the bus.

Return _the latest time you may arrive at the bus station to catch a bus_. You **cannot** arrive at the same time as another passenger.

**Note:** The arrays `buses` and `passengers` are not necessarily sorted.

**Example 1:**

**Input:** buses = \[10,20\], passengers = \[2,17,18,19\], capacity = 2
**Output:** 16
**Explanation:** Suppose you arrive at time 16.
At time 10, the first bus departs with the 0th passenger.
At time 20, the second bus departs with you and the 1st passenger.
Note that you may not arrive at the same time as another passenger, which is why you must arrive before the 1st passenger to catch the bus.

**Example 2:**

**Input:** buses = \[20,30,10\], passengers = \[19,13,26,4,25,11,21\], capacity = 2
**Output:** 20
**Explanation:** Suppose you arrive at time 20.
At time 10, the first bus departs with the 3rd passenger.
At time 20, the second bus departs with the 5th and 1st passengers.
At time 30, the third bus departs with the 0th passenger and you.
Notice if you had arrived any later, then the 6th passenger would have taken your seat on the third bus.

**Constraints:**

*   `n == buses.length`
*   `m == passengers.length`
*   `1 <= n, m, capacity <= 105`
*   `2 <= buses[i], passengers[i] <= 109`
*   Each element in `buses` is **unique**.
*   Each element in `passengers` is **unique**.

## A solution in Java

```java
import java.util.Arrays;

public int lastPassengerTime(int[] buses, int[] passengers, int capacity) {
    Arrays.sort(buses);
    Arrays.sort(passengers);

    int lastIndex = 0;
    for (int bus : buses) {
        int cnt = 0;
        while (lastIndex < passengers.length && passengers[lastIndex] <= bus && cnt < capacity) {
            cnt++;
            lastIndex++;
        }
    }

    return lastIndex == 0 ? buses[0] - 1 : passengers[lastIndex - 1] - 1;
}
```
1. Sort both `buses` and `passengers` arrays in increasing order.
2. Initialize the variable `lastIndex` to 0, which will keep track of the index of the last passenger that got on a bus.
3. Iterate through the sorted `buses` array.
4. For each bus, count how many passengers can get on it (up to `capacity`). Update the `lastIndex` as passengers get on the bus.
5. After iterating through all buses, if `lastIndex` is still 0, return the first bus departure time minus 1. Otherwise, return the arrival time of the last passenger who got on a bus minus 1. This is because you cannot arrive at the same time as another passenger.

## A solution in C++

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

int lastPassengerTime(vector<int> &buses, vector<int> &passengers, int capacity) {
    sort(buses.begin(), buses.end());
    sort(passengers.begin(), passengers.end());

    int lastIndex = 0;
    for (int bus : buses) {
        int cnt = 0;
        while (lastIndex < passengers.size() && passengers[lastIndex] <= bus && cnt < capacity) {
            cnt++;
            lastIndex++;
        }
    }

    return lastIndex == 0 ? buses[0] - 1 : passengers[lastIndex - 1] - 1;
}
```
1. Sort both `buses` and `passengers` arrays in increasing order.
2. Initialize the variable `lastIndex` to 0, which will keep track of the index of the last passenger that got on a bus.
3. Iterate through the sorted `buses` array.
4. For each bus, count how many passengers can get on it (up to `capacity`). Update the `lastIndex` as passengers get on the bus.
5. After iterating through all buses, if `lastIndex` is still 0, return the first bus departure time minus 1. Otherwise, return the arrival time of the last passenger who got on a bus minus 1. This is because you cannot arrive at the same time as another passenger.

## A solution in Python

```python
def last_passenger_time(buses, passengers, capacity):
    buses.sort()
    passengers.sort()

    last_index = 0
    for bus in buses:
        cnt = 0
        while last_index < len(passengers) and passengers[last_index] <= bus and cnt < capacity:
            cnt += 1
            last_index += 1

    return buses[0] - 1 if last_index == 0 else passengers[last_index - 1] - 1
```
1. Sort both `buses` and `passengers` arrays in increasing order.
2. Initialize the variable `lastIndex` to 0, which will keep track of the index of the last passenger that got on a bus.
3. Iterate through the sorted `buses` array.
4. For each bus, count how many passengers can get on it (up to `capacity`). Update the `lastIndex` as passengers get on the bus.
5. After iterating through all buses, if `lastIndex` is still 0, return the first bus departure time minus 1. Otherwise, return the arrival time of the last passenger who got on a bus minus 1. This is because you cannot arrive at the same time as another passenger.

## A solution in Javascript

```javascript
function lastPassengerTime(buses, passengers, capacity) {
    buses.sort((a, b) => a - b);
    passengers.sort((a, b) => a - b);

    let lastIndex = 0;
    for (let bus of buses) {
        let cnt = 0;
        while (lastIndex < passengers.length && passengers[lastIndex] <= bus && cnt < capacity) {
            cnt++;
            lastIndex++;
        }
    }

    return lastIndex === 0 ? buses[0] - 1 : passengers[lastIndex - 1] - 1;
}
```
1. Sort both `buses` and `passengers` arrays in increasing order.
2. Initialize the variable `lastIndex` to 0, which will keep track of the index of the last passenger that got on a bus.
3. Iterate through the sorted `buses` array.
4. For each bus, count how many passengers can get on it (up to `capacity`). Update the `lastIndex` as passengers get on the bus.
5. After iterating through all buses, if `lastIndex` is still 0, return the first bus departure time minus 1. Otherwise, return the arrival time of the last passenger who got on a bus minus 1. This is because you cannot arrive at the same time as another passenger.


# Minimum Sum of Squared Difference

- slug: minimum-sum-of-squared-difference
- difficulty: Medium

You are given two positive **0-indexed** integer arrays `nums1` and `nums2`, both of length `n`.

The **sum of squared difference** of arrays `nums1` and `nums2` is defined as the **sum** of `(nums1[i] - nums2[i])2` for each `0 <= i < n`.

You are also given two positive integers `k1` and `k2`. You can modify any of the elements of `nums1` by `+1` or `-1` at most `k1` times. Similarly, you can modify any of the elements of `nums2` by `+1` or `-1` at most `k2` times.

Return _the minimum **sum of squared difference** after modifying array_ `nums1` _at most_ `k1` _times and modifying array_ `nums2` _at most_ `k2` _times_.

**Note**: You are allowed to modify the array elements to become **negative** integers.

**Example 1:**

**Input:** nums1 = \[1,2,3,4\], nums2 = \[2,10,20,19\], k1 = 0, k2 = 0
**Output:** 579
**Explanation:** The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0.
The sum of square difference will be: (1 - 2)2 \+ (2 - 10)2 \+ (3 - 20)2 \+ (4 - 19)2 = 579.

**Example 2:**

**Input:** nums1 = \[1,4,10,12\], nums2 = \[5,8,6,9\], k1 = 1, k2 = 1
**Output:** 43
**Explanation:** One way to obtain the minimum sum of square difference is:
- Increase nums1\[0\] once.
- Increase nums2\[2\] once.
The minimum of the sum of square difference will be:
(2 - 5)2 \+ (4 - 8)2 \+ (10 - 7)2 \+ (12 - 9)2 = 43.
Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.

**Constraints:**

*   `n == nums1.length == nums2.length`
*   `1 <= n <= 105`
*   `0 <= nums1[i], nums2[i] <= 105`
*   `0 <= k1, k2 <= 109`

## A solution in Java

```java
int minSumOfSquaredDifference(int[] nums1, int[] nums2, int k1, int k2) {
    long res = 0;
    for (int i = 0; i < nums1.length; ++i) {
        int diff = Math.abs(nums1[i] - nums2[i]);
        int steps = Math.min(k1 + k2, diff);
        diff -= steps;
        k1 -= Math.min(k1, steps);
        res += (long)diff * diff;
    }
    return (int)res;
}
```
The main algorithm consists of looping through both arrays and calculating the element-wise difference between the elements of `nums1` and `nums2`.

For each difference, we first calculate the minimum between the sum of `k1` and `k2` operations and the absolute difference. Then, we subtract these steps from the actual difference and update the remaining number of modifications for `k1`.

Finally, we add the square of the resulting difference to the final result. At the end of the loop, we should have calculated the minimum sum of squares difference with the given constraints, and the function returns this result.

## A solution in C++

```cpp
int minSumOfSquaredDifference(vector<int>& nums1, vector<int>& nums2, int k1, int k2) {
    int64_t res = 0;
    for (int i = 0; i < nums1.size(); ++i) {
        int diff = abs(nums1[i] - nums2[i]);
        int steps = min(k1 + k2, diff);
        diff -= steps;
        k1 -= min(k1, steps);
        res += 1LL * diff * diff;
    }
    return (int)res;
}
```
The main algorithm consists of looping through both arrays and calculating the element-wise difference between the elements of `nums1` and `nums2`.

For each difference, we first calculate the minimum between the sum of `k1` and `k2` operations and the absolute difference. Then, we subtract these steps from the actual difference and update the remaining number of modifications for `k1`.

Finally, we add the square of the resulting difference to the final result. At the end of the loop, we should have calculated the minimum sum of squares difference with the given constraints, and the function returns this result.

## A solution in Python

```python
def min_sum_of_squared_difference(nums1, nums2, k1, k2):
    res = 0
    for i in range(len(nums1)):
        diff = abs(nums1[i] - nums2[i])
        steps = min(k1 + k2, diff)
        diff -= steps
        k1 -= min(k1, steps)
        res += diff * diff
    return res
```
The main algorithm consists of looping through both arrays and calculating the element-wise difference between the elements of `nums1` and `nums2`.

For each difference, we first calculate the minimum between the sum of `k1` and `k2` operations and the absolute difference. Then, we subtract these steps from the actual difference and update the remaining number of modifications for `k1`.

Finally, we add the square of the resulting difference to the final result. At the end of the loop, we should have calculated the minimum sum of squares difference with the given constraints, and the function returns this result.

## A solution in Javascript

```javascript
function minSumOfSquaredDifference(nums1, nums2, k1, k2) {
    let res = 0;
    for (let i = 0; i < nums1.length; ++i) {
        let diff = Math.abs(nums1[i] - nums2[i]);
        let steps = Math.min(k1 + k2, diff);
        diff -= steps;
        k1 -= Math.min(k1, steps);
        res += diff * diff;
    }
    return res;
}
```
The main algorithm consists of looping through both arrays and calculating the element-wise difference between the elements of `nums1` and `nums2`.

For each difference, we first calculate the minimum between the sum of `k1` and `k2` operations and the absolute difference. Then, we subtract these steps from the actual difference and update the remaining number of modifications for `k1`.

Finally, we add the square of the resulting difference to the final result. At the end of the loop, we should have calculated the minimum sum of squares difference with the given constraints, and the function returns this result.


# Subarray With Elements Greater Than Varying Threshold

- slug: subarray-with-elements-greater-than-varying-threshold
- difficulty: Hard

You are given an integer array `nums` and an integer `threshold`.

Find any subarray of `nums` of length `k` such that **every** element in the subarray is **greater** than `threshold / k`.

Return _the **size** of **any** such subarray_. If there is no such subarray, return `-1`.

A **subarray** is a contiguous non-empty sequence of elements within an array.

**Example 1:**

**Input:** nums = \[1,3,4,3,1\], threshold = 6
**Output:** 3
**Explanation:** The subarray \[3,4,3\] has a size of 3, and every element is greater than 6 / 3 = 2.
Note that this is the only valid subarray.

**Example 2:**

**Input:** nums = \[6,5,6,5,8\], threshold = 7
**Output:** 1
**Explanation:** The subarray \[8\] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned.
Note that the subarray \[6,5\] has a size of 2, and every element is greater than 7 / 2 = 3.5.
Similarly, the subarrays \[6,5,6\], \[6,5,6,5\], \[6,5,6,5,8\] also satisfy the given conditions.
Therefore, 2, 3, 4, or 5 may also be returned.

**Constraints:**

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

## A solution in Java

```java
public int findSubarrayLength(int[] nums, int threshold) {
    int n = nums.length, left = 0, right = 0, sum = 0, maxLength = -1;

    while (right < n) {
        sum += nums[right];
        while (sum * (right - left + 1) < threshold * (right - left + 1)) {
            sum -= nums[left];
            left++;
        }
        maxLength = Math.max(maxLength, right - left + 1);
        right++;
    }

    return maxLength;
}
```
The algorithm is a sliding window approach. We initialize left and right pointers at the beginning of the array, and a sum variable. We also initialize maxLength to -1 to handle the case where there is no valid subarray.

In the loop, we move the right pointer, adding the element at that position to the sum. We then check if the sum times the length of the current window (right - left + 1) is less than the threshold times the length of the current window. If it is, we move the left pointer and subtract that value from the sum to maintain the sum of elements in the window.

At each step, we update maxLength to the maximum of the current maxLength and the length of the current window (right - left + 1). This way, we store the maximum length we've found so far.

After the loop, we return maxLength, which is the final answer.

## A solution in C++

```cpp
int findSubarrayLength(vector<int>& nums, int threshold) {
    int n = nums.size();
    int left = 0, right = 0, sum = 0;
    int maxLength = -1;

    while (right < n) {
        sum += nums[right];
        while (sum * (right - left + 1) < threshold * (right - left + 1)) {
            sum -= nums[left];
            left++;
        }
        maxLength = max(maxLength, right - left + 1);
        right++;
    }

    return maxLength;
}
```
The algorithm is a sliding window approach. We initialize left and right pointers at the beginning of the array, and a sum variable. We also initialize maxLength to -1 to handle the case where there is no valid subarray.

In the loop, we move the right pointer, adding the element at that position to the sum. We then check if the sum times the length of the current window (right - left + 1) is less than the threshold times the length of the current window. If it is, we move the left pointer and subtract that value from the sum to maintain the sum of elements in the window.

At each step, we update maxLength to the maximum of the current maxLength and the length of the current window (right - left + 1). This way, we store the maximum length we've found so far.

After the loop, we return maxLength, which is the final answer.

## A solution in Python

```python
def find_subarray_length(nums, threshold):
    n = len(nums)
    left = 0
    right = 0
    total = 0
    max_length = -1

    while right < n:
        total += nums[right]
        while total * (right - left + 1) < threshold * (right - left + 1):
            total -= nums[left]
            left += 1
        max_length = max(max_length, right - left + 1)
        right += 1

    return max_length
```
The algorithm is a sliding window approach. We initialize left and right pointers at the beginning of the array, and a sum variable. We also initialize maxLength to -1 to handle the case where there is no valid subarray.

In the loop, we move the right pointer, adding the element at that position to the sum. We then check if the sum times the length of the current window (right - left + 1) is less than the threshold times the length of the current window. If it is, we move the left pointer and subtract that value from the sum to maintain the sum of elements in the window.

At each step, we update maxLength to the maximum of the current maxLength and the length of the current window (right - left + 1). This way, we store the maximum length we've found so far.

After the loop, we return maxLength, which is the final answer.

## A solution in Javascript

```javascript
function findSubarrayLength(nums, threshold) {
    let n = nums.length, left = 0, right = 0, sum = 0, maxLength = -1;

    while (right < n) {
        sum += nums[right];
        while (sum * (right - left + 1) < threshold * (right - left + 1)) {
            sum -= nums[left];
            left++;
        }
        maxLength = Math.max(maxLength, right - left + 1);
        right++;
    }

    return maxLength;
}
```
The algorithm is a sliding window approach. We initialize left and right pointers at the beginning of the array, and a sum variable. We also initialize maxLength to -1 to handle the case where there is no valid subarray.

In the loop, we move the right pointer, adding the element at that position to the sum. We then check if the sum times the length of the current window (right - left + 1) is less than the threshold times the length of the current window. If it is, we move the left pointer and subtract that value from the sum to maintain the sum of elements in the window.

At each step, we update maxLength to the maximum of the current maxLength and the length of the current window (right - left + 1). This way, we store the maximum length we've found so far.

After the loop, we return maxLength, which is the final answer.