# Reformat Date

- slug: reformat-date
- difficulty: Easy

Given a `date` string in the form `Day Month Year`, where:

*   `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
*   `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
*   `Year` is in the range `[1900, 2100]`.

Convert the date string to the format `YYYY-MM-DD`, where:

*   `YYYY` denotes the 4 digit year.
*   `MM` denotes the 2 digit month.
*   `DD` denotes the 2 digit day.

**Example 1:**

**Input:** date =  "20th Oct 2052 "
**Output:**  "2052-10-20 "

**Example 2:**

**Input:** date =  "6th Jun 1933 "
**Output:**  "1933-06-06 "

**Example 3:**

**Input:** date =  "26th May 1960 "
**Output:**  "1960-05-26 "

**Constraints:**

*   The given dates are guaranteed to be valid, so no error handling is necessary.

## A solution in Java

```java
public boolean hasValidPath(int[][] grid) {
    int m = grid.length;
    int n = grid[0].length;
    boolean[][] visited = new boolean[m][n];

    return dfs(grid, 0, 0, m, n, visited);
}

private boolean dfs(int[][] grid, int x, int y, int m, int n, boolean[][] visited) {
    if (x < 0 || y < 0 || x >= m || y >= n || visited[x][y]) return false;
    if (x == m - 1 && y == n - 1) return true;

    visited[x][y] = true;

    int[] next_x = {-1, 0, 1, 0};
    int[] next_y = {0, 1, 0, -1};

    for (int i = 0; i < 4; i++) {
        int dx = x + next_x[i];
        int dy = y + next_y[i];

        if (dfs(grid, dx, dy, m, n, visited)) return true;
    }

    return false;
}
```
The algorithm performs a depth-first search through the grid starting from the upper-left cell (0,0), marking each visited cell in a separate grid. It iterates 4 different directions for each cell, checking boundaries, and continuing its search if a valid path is found from the next cell in the given direction.

The DFS continues until it reaches the bottom-right cell (m-1, n-1), at which point it returns true. If the algorithm cannot find a path to the bottom-right cell, it returns false.

## A solution in C++

```cpp
#include <vector>

bool hasValidPath(std::vector<std::vector<int>>& grid) {
    int m = grid.size();
    int n = grid[0].size();
    std::vector<std::vector<bool>> visited(m, std::vector<bool>(n, false));

    return dfs(grid, 0, 0, m, n, visited);
}

bool dfs(std::vector<std::vector<int>>& grid, int x, int y, int m, int n, std::vector<std::vector<bool>>& visited) {
    if (x < 0 || y < 0 || x >= m || y >= n || visited[x][y]) return false;
    if (x == m - 1 && y == n - 1) return true;

    visited[x][y] = true;

    int next_x[4] = {-1, 0, 1, 0};
    int next_y[4] = {0, 1, 0, -1};

    for (int i = 0; i < 4; i++) {
        int dx = x + next_x[i];
        int dy = y + next_y[i];

        if (dfs(grid, dx, dy, m, n, visited)) return true;
    }

    return false;
}
```
The algorithm performs a depth-first search through the grid starting from the upper-left cell (0,0), marking each visited cell in a separate grid. It iterates 4 different directions for each cell, checking boundaries, and continuing its search if a valid path is found from the next cell in the given direction.

The DFS continues until it reaches the bottom-right cell (m-1, n-1), at which point it returns true. If the algorithm cannot find a path to the bottom-right cell, it returns false.

## A solution in Python

```python
def hasValidPath(grid):
    m, n = len(grid), len(grid[0])
    visited = [[False for _ in range(n)] for _ in range(m)]

    return dfs(grid, 0, 0, m, n, visited)

def dfs(grid, x, y, m, n, visited):
    if x < 0 or y < 0 or x >= m or y >= n or visited[x][y]:
        return False
    if x == m - 1 and y == n - 1:
        return True

    visited[x][y] = True

    next_x = [-1, 0, 1, 0]
    next_y = [0, 1, 0, -1]

    for i in range(4):
        dx = x + next_x[i]
        dy = y + next_y[i]

        if dfs(grid, dx, dy, m, n, visited):
            return True

    return False
```
The algorithm performs a depth-first search through the grid starting from the upper-left cell (0,0), marking each visited cell in a separate grid. It iterates 4 different directions for each cell, checking boundaries, and continuing its search if a valid path is found from the next cell in the given direction.

The DFS continues until it reaches the bottom-right cell (m-1, n-1), at which point it returns true. If the algorithm cannot find a path to the bottom-right cell, it returns false.

## A solution in Javascript

```javascript
function hasValidPath(grid) {
    const m = grid.length;
    const n = grid[0].length;
    const visited = new Array(m).fill(null).map(() => new Array(n).fill(false));

    return dfs(grid, 0, 0, m, n, visited);
}

function dfs(grid, x, y, m, n, visited) {
    if (x < 0 || y < 0 || x >= m || y >= n || visited[x][y]) return false;
    if (x === m - 1 && y === n - 1) return true;

    visited[x][y] = true;

    const next_x = [-1, 0, 1, 0];
    const next_y = [0, 1, 0, -1];

    for (let i = 0; i < 4; i++) {
        const dx = x + next_x[i];
        const dy = y + next_y[i];

        if (dfs(grid, dx, dy, m, n, visited)) return true;
    }

    return false;
}
```
The algorithm performs a depth-first search through the grid starting from the upper-left cell (0,0), marking each visited cell in a separate grid. It iterates 4 different directions for each cell, checking boundaries, and continuing its search if a valid path is found from the next cell in the given direction.

The DFS continues until it reaches the bottom-right cell (m-1, n-1), at which point it returns true. If the algorithm cannot find a path to the bottom-right cell, it returns false.


# Range Sum of Sorted Subarray Sums

- slug: range-sum-of-sorted-subarray-sums
- difficulty: Medium

You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.

_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed from 1**)_, inclusive, in the new array._ Since the answer can be a huge number return it modulo `109 + 7`.

**Example 1:**

**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 5
**Output:** 13
**Explanation:** All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.

**Example 2:**

**Input:** nums = \[1,2,3,4\], n = 4, left = 3, right = 4
**Output:** 6
**Explanation:** The given array is the same as example 1. We have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.

**Example 3:**

**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 10
**Output:** 50

**Constraints:**

*   `n == nums.length`
*   `1 <= nums.length <= 1000`
*   `1 <= nums[i] <= 100`
*   `1 <= left <= right <= n * (n + 1) / 2`

## A solution in Java

```java
public String longestHappyPrefix(String s) {
    int n = s.length();
    int[] lps = new int[n];
    int len = 0;
    int i = 1;
    while (i < n) {
        if (s.charAt(i) == s.charAt(len)) {
            len++;
            lps[i] = len;
            i++;
        } else {
            if (len != 0) {
                len = lps[len - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return s.substring(0, lps[n - 1]);
}
```
We are utilizing the KMP algorithm on the string that computes the Longest Proper Prefix which is also a suffix (LPS) array. This helps us in identifying the longest happy prefix in linear time.

1. Create an LPS array to store the longest proper prefix at each index.
2. Initialize two-pointer variables, one (`i`) to traverse through the string, and another (`len`) to keep track of the maximum prefix length.
3. Loop through the string and update the LPS array by comparing the characters pointed by both pointers. If the characters match, increase the prefix length and store it in the LPS array.
4. If the characters don't match and the prefix length is not zero, update the prefix length to the value of the previous LPS index.
5. If the prefix length is zero, just set the LPS value for the current index to zero and move to the next index.
6. The last element of the LPS array has the length of the longest happy prefix, so return a substring of the input string from the start to the length of the longest happy prefix.

## A solution in C++

```cpp
std::string longestHappyPrefix(std::string s) {
    int n = s.length();
    std::vector<int> lps(n, 0);
    int len = 0;
    int i = 1;
    while (i < n) {
        if (s[i] == s[len]) {
            len++;
            lps[i] = len;
            i++;
        } else {
            if (len != 0) {
                len = lps[len - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return s.substr(0, lps[n - 1]);
}
```
We are utilizing the KMP algorithm on the string that computes the Longest Proper Prefix which is also a suffix (LPS) array. This helps us in identifying the longest happy prefix in linear time.

1. Create an LPS array to store the longest proper prefix at each index.
2. Initialize two-pointer variables, one (`i`) to traverse through the string, and another (`len`) to keep track of the maximum prefix length.
3. Loop through the string and update the LPS array by comparing the characters pointed by both pointers. If the characters match, increase the prefix length and store it in the LPS array.
4. If the characters don't match and the prefix length is not zero, update the prefix length to the value of the previous LPS index.
5. If the prefix length is zero, just set the LPS value for the current index to zero and move to the next index.
6. The last element of the LPS array has the length of the longest happy prefix, so return a substring of the input string from the start to the length of the longest happy prefix.

## A solution in Python

```python
def longestHappyPrefix(s):
    n = len(s)
    lps = [0] * n
    length = 0
    i = 1
    while i < n:
        if s[i] == s[length]:
            length += 1
            lps[i] = length
            i += 1
        elif length != 0:
            length = lps[length - 1]
        else:
            lps[i] = 0
            i += 1
    return s[:lps[-1]]
```
We are utilizing the KMP algorithm on the string that computes the Longest Proper Prefix which is also a suffix (LPS) array. This helps us in identifying the longest happy prefix in linear time.

1. Create an LPS array to store the longest proper prefix at each index.
2. Initialize two-pointer variables, one (`i`) to traverse through the string, and another (`len`) to keep track of the maximum prefix length.
3. Loop through the string and update the LPS array by comparing the characters pointed by both pointers. If the characters match, increase the prefix length and store it in the LPS array.
4. If the characters don't match and the prefix length is not zero, update the prefix length to the value of the previous LPS index.
5. If the prefix length is zero, just set the LPS value for the current index to zero and move to the next index.
6. The last element of the LPS array has the length of the longest happy prefix, so return a substring of the input string from the start to the length of the longest happy prefix.

## A solution in Javascript

```javascript
function longestHappyPrefix(s) {
    let n = s.length;
    let lps = new Array(n).fill(0);
    let len = 0;
    let i = 1;
    while (i < n) {
        if (s.charAt(i) === s.charAt(len)) {
            len++;
            lps[i] = len;
            i++;
        } else {
            if (len !== 0) {
                len = lps[len - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return s.substring(0, lps[n - 1]);
}
```
We are utilizing the KMP algorithm on the string that computes the Longest Proper Prefix which is also a suffix (LPS) array. This helps us in identifying the longest happy prefix in linear time.

1. Create an LPS array to store the longest proper prefix at each index.
2. Initialize two-pointer variables, one (`i`) to traverse through the string, and another (`len`) to keep track of the maximum prefix length.
3. Loop through the string and update the LPS array by comparing the characters pointed by both pointers. If the characters match, increase the prefix length and store it in the LPS array.
4. If the characters don't match and the prefix length is not zero, update the prefix length to the value of the previous LPS index.
5. If the prefix length is zero, just set the LPS value for the current index to zero and move to the next index.
6. The last element of the LPS array has the length of the longest happy prefix, so return a substring of the input string from the start to the length of the longest happy prefix.


# Minimum Difference Between Largest and Smallest Value in Three Moves

- slug: minimum-difference-between-largest-and-smallest-value-in-three-moves
- difficulty: Medium

You are given an integer array `nums`.

In one move, you can choose one element of `nums` and change it to **any value**.

Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.

**Example 1:**

**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation:** We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes \[5,3,3,4\].
In the second move, change 4 to 3. nums becomes \[5,3,3,3\].
In the third move, change 5 to 3. nums becomes \[3,3,3,3\].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.

**Example 2:**

**Input:** nums = \[1,5,0,10,14\]
**Output:** 1
**Explanation:** We can make at most 3 moves.
In the first move, change 5 to 0. nums becomes \[1,0,0,10,14\].
In the second move, change 10 to 0. nums becomes \[1,0,0,0,14\].
In the third move, change 14 to 1. nums becomes \[1,0,0,0,1\].
After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 0.
It can be shown that there is no way to make the difference 0 in 3 moves.

**Example 3:**

**Input:** nums = \[3,100,20\]
**Output:** 0
**Explanation:** We can make at most 3 moves.
In the first move, change 100 to 7. nums becomes \[4,7,20\].
In the second move, change 20 to 7. nums becomes \[4,7,7\].
In the third move, change 4 to 3. nums becomes \[7,7,7\].
After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.

**Constraints:**

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

## A solution in Java

```java
public int minDifference(int[] nums) {
    int n = nums.length;
    if (n <= 4) return 0;
    Arrays.sort(nums);
    int res = Integer.MAX_VALUE;
    for (int i = 0; i <= 3; ++i)
        res = Math.min(res, nums[n - 4 + i] - nums[i]);
    return res;
}
```
1. First, check if the length of the input array is less than or equal to 4. If it is, return 0 since there's no need to perform any operation on this input.
2. Sort the input array in ascending order.
3. Initialize the result (minimum difference) as the maximum value possible.
4. Loop through the array from the 0-th element to the 3-rd element (inclusive). For each iteration, find the difference between the (n - 4 + i)-th element and the i-th element in the sorted array, where n is the length of the input array. Update the result as the minimum of the current and previous minimum differences.
5. After the loop, return the resulting minimum difference.

## A solution in C++

```cpp
int minDifference(vector<int>& nums) {
    int n = nums.size();
    if (n <= 4) return 0;
    sort(nums.begin(), nums.end());
    int res = INT_MAX;
    for (int i = 0; i <= 3; ++i)
        res = min(res, nums[n - 4 + i] - nums[i]);
    return res;
}
```
1. First, check if the length of the input array is less than or equal to 4. If it is, return 0 since there's no need to perform any operation on this input.
2. Sort the input array in ascending order.
3. Initialize the result (minimum difference) as the maximum value possible.
4. Loop through the array from the 0-th element to the 3-rd element (inclusive). For each iteration, find the difference between the (n - 4 + i)-th element and the i-th element in the sorted array, where n is the length of the input array. Update the result as the minimum of the current and previous minimum differences.
5. After the loop, return the resulting minimum difference.

## A solution in Python

```python
def minDifference(nums):
    n = len(nums)
    if n <= 4: return 0
    nums.sort()
    res = float('inf')
    for i in range(4):
        res = min(res, nums[n - 4 + i] - nums[i])
    return res
```
1. First, check if the length of the input array is less than or equal to 4. If it is, return 0 since there's no need to perform any operation on this input.
2. Sort the input array in ascending order.
3. Initialize the result (minimum difference) as the maximum value possible.
4. Loop through the array from the 0-th element to the 3-rd element (inclusive). For each iteration, find the difference between the (n - 4 + i)-th element and the i-th element in the sorted array, where n is the length of the input array. Update the result as the minimum of the current and previous minimum differences.
5. After the loop, return the resulting minimum difference.

## A solution in Javascript

```javascript
function minDifference(nums) {
    let n = nums.length;
    if (n <= 4) return 0;
    nums.sort((a, b) => a - b);
    let res = Number.MAX_SAFE_INTEGER;
    for (let i = 0; i <= 3; ++i)
        res = Math.min(res, nums[n - 4 + i] - nums[i]);
    return res;
}
```
1. First, check if the length of the input array is less than or equal to 4. If it is, return 0 since there's no need to perform any operation on this input.
2. Sort the input array in ascending order.
3. Initialize the result (minimum difference) as the maximum value possible.
4. Loop through the array from the 0-th element to the 3-rd element (inclusive). For each iteration, find the difference between the (n - 4 + i)-th element and the i-th element in the sorted array, where n is the length of the input array. Update the result as the minimum of the current and previous minimum differences.
5. After the loop, return the resulting minimum difference.


# Stone Game IV

- slug: stone-game-iv
- difficulty: Hard

Alice and Bob take turns playing a game, with Alice starting first.

Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.

Also, if a player cannot make a move, he/she loses the game.

Given a positive integer `n`, return `true` if and only if Alice wins the game otherwise return `false`, assuming both players play optimally.

**Example 1:**

**Input:** n = 1
**Output:** true
**Explanation:** Alice can remove 1 stone winning the game because Bob doesn't have any moves.

**Example 2:**

**Input:** n = 2
**Output:** false
**Explanation:** Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).

**Example 3:**

**Input:** n = 4
**Output:** true
**Explanation:** n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).

**Constraints:**

*   `1 <= n <= 105`

## A solution in Java

```java
import java.util.HashMap;

public int findLucky(int[] arr) {
    HashMap<Integer, Integer> freq = new HashMap<>();

    for (int n : arr) {
        freq.put(n, freq.getOrDefault(n, 0) + 1);
    }

    int lucky = -1;
    for (int key : freq.keySet()) {
        if (key == freq.get(key)) {
            lucky = Math.max(lucky, key);
        }
    }

    return lucky;
}
```
The algorithm starts by initializing an empty hash map called `freq` to store the frequencies of each integer in the array. Then, it iterates over the array and updates the frequencies in the hash map accordingly.

After populating the hash map, the algorithm initializes a variable `lucky` with a value of -1. It then iterates over the key-value pairs in the hash map, checking if the key (the integer from the array) is equal to its value (the frequency). If an integer in the array has a frequency equal to its value, the algorithm updates the `lucky` variable to be the maximum of its current value and the integer in question.

Finally, the `lucky` variable is returned as the largest lucky integer in the array. If no lucky integer is present, the initial value of -1 will be returned.

## A solution in C++

```cpp
#include <unordered_map>

int findLucky(std::vector<int>& arr) {
    std::unordered_map<int, int> freq;

    for (int n : arr) {
        freq[n]++;
    }

    int lucky = -1;
    for (auto &pair : freq) {
        if (pair.first == pair.second) {
            lucky = std::max(lucky, pair.first);
        }
    }

    return lucky;
}
```
The algorithm starts by initializing an empty hash map called `freq` to store the frequencies of each integer in the array. Then, it iterates over the array and updates the frequencies in the hash map accordingly.

After populating the hash map, the algorithm initializes a variable `lucky` with a value of -1. It then iterates over the key-value pairs in the hash map, checking if the key (the integer from the array) is equal to its value (the frequency). If an integer in the array has a frequency equal to its value, the algorithm updates the `lucky` variable to be the maximum of its current value and the integer in question.

Finally, the `lucky` variable is returned as the largest lucky integer in the array. If no lucky integer is present, the initial value of -1 will be returned.

## A solution in Python

```python
def find_lucky(arr):
    freq = {}

    for n in arr:
        if n in freq:
            freq[n] += 1
        else:
            freq[n] = 1

    lucky = -1
    for key, value in freq.items():
        if key == value:
            lucky = max(lucky, key)

    return lucky
```
The algorithm starts by initializing an empty hash map called `freq` to store the frequencies of each integer in the array. Then, it iterates over the array and updates the frequencies in the hash map accordingly.

After populating the hash map, the algorithm initializes a variable `lucky` with a value of -1. It then iterates over the key-value pairs in the hash map, checking if the key (the integer from the array) is equal to its value (the frequency). If an integer in the array has a frequency equal to its value, the algorithm updates the `lucky` variable to be the maximum of its current value and the integer in question.

Finally, the `lucky` variable is returned as the largest lucky integer in the array. If no lucky integer is present, the initial value of -1 will be returned.

## A solution in Javascript

```javascript
function findLucky(arr) {
    let freq = {};

    for (let n of arr) {
        if (n in freq) {
            freq[n]++;
        } else {
            freq[n] = 1;
        }
    }

    let lucky = -1;
    for (let key in freq) {
        let value = freq[key];
        if (parseInt(key) === value) {
            lucky = Math.max(lucky, key);
        }
    }

    return lucky;
}
```
The algorithm starts by initializing an empty hash map called `freq` to store the frequencies of each integer in the array. Then, it iterates over the array and updates the frequencies in the hash map accordingly.

After populating the hash map, the algorithm initializes a variable `lucky` with a value of -1. It then iterates over the key-value pairs in the hash map, checking if the key (the integer from the array) is equal to its value (the frequency). If an integer in the array has a frequency equal to its value, the algorithm updates the `lucky` variable to be the maximum of its current value and the integer in question.

Finally, the `lucky` variable is returned as the largest lucky integer in the array. If no lucky integer is present, the initial value of -1 will be returned.


# Number of Good Pairs

- slug: number-of-good-pairs
- difficulty: Easy

Given an array of integers `nums`, return _the number of **good pairs**_.

A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.

**Example 1:**

**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.

**Example 2:**

**Input:** nums = \[1,1,1,1\]
**Output:** 6
**Explanation:** Each pair in the array are _good_.

**Example 3:**

**Input:** nums = \[1,2,3\]
**Output:** 0

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

class UndergroundSystem {
    private Map<Integer, Pair<String, Integer>> checkInData;
    private Map<String, Pair<Integer, Integer>> travelData;

    public UndergroundSystem() {
        checkInData = new HashMap<>();
        travelData = new HashMap<>();
    }

    public void checkIn(int id, String stationName, int t) {
        checkInData.put(id, new Pair<>(stationName, t));
    }

    public void checkOut(int id, String stationName, int t) {
        String startStation = checkInData.get(id).getKey();
        int startTime = checkInData.get(id).getValue();
        String route = startStation + "_" + stationName;
        int totalTime = travelData.getOrDefault(route, new Pair<>(0, 0)).getKey() + (t - startTime);
        int numTrips = travelData.getOrDefault(route, new Pair<>(0, 0)).getValue() + 1;
        travelData.put(route, new Pair<>(totalTime, numTrips));
    }

    public double getAverageTime(String startStation, String endStation) {
        String route = startStation + "_" + endStation;
        double totalTime = travelData.get(route).getKey();
        int numTrips = travelData.get(route).getValue();
        return totalTime / numTrips;
    }
}
```
The algorithm uses two nested hashmaps (in Python, two nested dictionaries) to keep track of check-in/check-out data and travel-time data:

1. The `check_in_data` hashmap stores the traveler's check-in station and time, with their ID as the key.
2. When a user checks out, the starting station and check-in time are retrieved from `check_in_data` and combined with the check-out station and time to create a route key. The route key is then used to store the total travel time and the number of trips taken for that route in the `travel_data` hashmap.
3. To retrieve the average time between two stations, the algorithm looks up the total time and trip count for the requested route and divides the total time by the trip count.

The algorithm has an O(1) average complexity for all operations (check-in, check-out, and getAverageTime) as it relies on hashing lookups and updates.

## A solution in C++

```cpp
#include <unordered_map>
#include <string>

class UndergroundSystem {
public:
    unordered_map<int, pair<string, int>> check_in_data;
    unordered_map<string, pair<int, int>> travel_data;

    UndergroundSystem() {}

    void checkIn(int id, string stationName, int t) {
        check_in_data[id] = {stationName, t};
    }

    void checkOut(int id, string stationName, int t) {
        string startStation = check_in_data[id].first;
        int startTime = check_in_data[id].second;
        string route = startStation + "_" + stationName;
        travel_data[route].first += (t - startTime);
        travel_data[route].second += 1;
    }

    double getAverageTime(string startStation, string endStation) {
        string route = startStation + "_" + endStation;
        return (double)travel_data[route].first / travel_data[route].second;
    }
};
```
The algorithm uses two nested hashmaps (in Python, two nested dictionaries) to keep track of check-in/check-out data and travel-time data:

1. The `check_in_data` hashmap stores the traveler's check-in station and time, with their ID as the key.
2. When a user checks out, the starting station and check-in time are retrieved from `check_in_data` and combined with the check-out station and time to create a route key. The route key is then used to store the total travel time and the number of trips taken for that route in the `travel_data` hashmap.
3. To retrieve the average time between two stations, the algorithm looks up the total time and trip count for the requested route and divides the total time by the trip count.

The algorithm has an O(1) average complexity for all operations (check-in, check-out, and getAverageTime) as it relies on hashing lookups and updates.

## A solution in Python

```python
class UndergroundSystem:
    def __init__(self):
        self.check_in_data = {}
        self.travel_data = {}

    def checkIn(self, id: int, stationName: str, t: int) -> None:
        self.check_in_data[id] = (stationName, t)

    def checkOut(self, id: int, stationName: str, t: int) -> None:
        start_station, start_time = self.check_in_data[id]
        route = (start_station, stationName)
        if route not in self.travel_data:
            self.travel_data[route] = [0, 0]
        self.travel_data[route][0] += t - start_time
        self.travel_data[route][1] += 1

    def getAverageTime(self, startStation: str, endStation: str) -> float:
        route = (startStation, endStation)
        total_time, num_trips = self.travel_data[route]
        return total_time / num_trips
```
The algorithm uses two nested hashmaps (in Python, two nested dictionaries) to keep track of check-in/check-out data and travel-time data:

1. The `check_in_data` hashmap stores the traveler's check-in station and time, with their ID as the key.
2. When a user checks out, the starting station and check-in time are retrieved from `check_in_data` and combined with the check-out station and time to create a route key. The route key is then used to store the total travel time and the number of trips taken for that route in the `travel_data` hashmap.
3. To retrieve the average time between two stations, the algorithm looks up the total time and trip count for the requested route and divides the total time by the trip count.

The algorithm has an O(1) average complexity for all operations (check-in, check-out, and getAverageTime) as it relies on hashing lookups and updates.

## A solution in Javascript

```javascript
class UndergroundSystem {
    constructor() {
        this.checkInData = new Map();
        this.travelData = new Map();
    }

    checkIn(id, stationName, t) {
        this.checkInData.set(id, [stationName, t]);
    }

    checkOut(id, stationName, t) {
        const [startStation, startTime] = this.checkInData.get(id);
        const route = `${startStation}_${stationName}`;
        const travelInfo = this.travelData.get(route) || [0, 0];
        this.travelData.set(route, [travelInfo[0] + t - startTime, travelInfo[1] + 1]);
    }

    getAverageTime(startStation, endStation) {
        const route = `${startStation}_${endStation}`;
        const [totalTime, numTrips] = this.travelData.get(route);
        return totalTime / numTrips;
    }
}
```
The algorithm uses two nested hashmaps (in Python, two nested dictionaries) to keep track of check-in/check-out data and travel-time data:

1. The `check_in_data` hashmap stores the traveler's check-in station and time, with their ID as the key.
2. When a user checks out, the starting station and check-in time are retrieved from `check_in_data` and combined with the check-out station and time to create a route key. The route key is then used to store the total travel time and the number of trips taken for that route in the `travel_data` hashmap.
3. To retrieve the average time between two stations, the algorithm looks up the total time and trip count for the requested route and divides the total time by the trip count.

The algorithm has an O(1) average complexity for all operations (check-in, check-out, and getAverageTime) as it relies on hashing lookups and updates.


# Number of Substrings With Only 1s

- slug: number-of-substrings-with-only-1s
- difficulty: Medium

Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.

**Example 1:**

**Input:** s =  "0110111 "
**Output:** 9
**Explanation:** There are 9 substring in total with only 1's characters.
 "1 " -> 5 times.
 "11 " -> 3 times.
 "111 " -> 1 time.

**Example 2:**

**Input:** s =  "101 "
**Output:** 2
**Explanation:** Substring  "1 " is shown 2 times in s.

**Example 3:**

**Input:** s =  "111111 "
**Output:** 21
**Explanation:** Each substring contains only 1's characters.

**Constraints:**

*   `1 <= s.length <= 105`
*   `s[i]` is either `'0'` or `'1'`.

## A solution in Java

```java
class Solution {
    private static final int MOD = 1000000007;

    public int countGoodStrings(String s1, String s2, String evil) {
        int n = s1.length();
        int m = evil.length();
        int[][] dp = new int[n + 1][m];

        // Preprocess the KMP prefix function for the evil string
        int[] lps = new int[m];
        int len = 0;
        for (int i = 1; i < m;) {
            if (evil.charAt(i) == evil.charAt(len)) {
                lps[i++] = ++len;
            } else if (len > 0) {
                len = lps[len - 1];
            } else {
                ++i;
            }
        }

        dp[0][0] = 1;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                for (int k = 0; k < 2; ++k) {
                    for (char c = 'a'; c <= (k == 1 ? s2.charAt(i) : 'z'); ++c) {
                        int e = j;
                        while (e > 0 && (c != evil.charAt(e))) {
                            e = lps[e - 1];
                        }

                        if (c != evil.charAt(e)) {
                            e++;
                        }

                        if (e != m) {
                            dp[i + 1][k | ((c < s2.charAt(i)) ? 1 : 0)] += dp[i][k];
                            dp[i + 1][k | ((c < s2.charAt(i)) ? 1 : 0)] %= MOD;
                        }
                    }
                }
            }
        }

        return (dp[n][1] - dp[n][0] + MOD) % MOD;
    }
}
```
The problem requires us to find the good strings between s1 and s2 that do not contain the evil substring. We can accomplish this using dynamic programming and KMP prefix function.

First, we preprocess the KMP prefix function for the evil string. The KMP prefix function can be used to match overlapping substrings within the evil string, which will help us to detect the presence of the evil substring in our generated string candidates.

Next, we create a dp table, with dimensions `[n+1][m]`, where `n` is the length of s1 and s2, and `m` is the length of the evil string. We initialize `dp[0][0]` to 1. The first dimension of the dp table keeps track of the current length of the generated string, while the second dimension keeps track of the length of the longest prefix of the evil string that matches the current suffix of the generated string.

Then, we iterate over the lengths of the string, and for each character in the current length, we check whether the character is a part of the evil substring. If it is not, we update the dp table accordingly. We also use the variable `k` to keep track of whether the generated substring is less than or equal to s2.

Finally, we return the result as `(dp[n][1] - dp[n][0] + MOD) % MOD`. This gives us the number of good strings without the evil substring, between s1 and s2.

## A solution in C++

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

using namespace std;

const int MOD = 1e9 + 7;

int countGoodStrings(string s1, string s2, string evil) {
    int n = s1.size();
    int m = evil.size();
    vector<vector<int>> dp(n + 1, vector<int>(m, 0));

    // Preprocess the KMP prefix function for the evil string
    vector<int> lps(m);
    int len = 0;
    for (int i = 1; i < m;) {
        if (evil[i] == evil[len]) {
            lps[i++] = ++len;
        } else if (len) {
            len = lps[len - 1];
        } else {
            ++i;
        }
    }

    vector<vector<int>> count(s1.size() + 1, vector<int>(2, 0));
    dp[0][0] = 1;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            for (int k = 0; k < 2; ++k) {
                for (char c = 'a'; c <= (k ? s2[i] : 'z'); ++c) {
                    int e = j;
                    while (e && (c != evil[e])) {
                        e = lps[e - 1];
                    }

                    if ((c != evil[e])) {
                        e++;
                    }

                    if (e != m) {
                        dp[i + 1][k | (c < s2[i])] += dp[i][k];
                        dp[i + 1][k | (c < s2[i])] %= MOD;
                    }
                }
            }
        }
    }

    return (dp[n][1] - dp[n][0] + MOD) % MOD;
}
```
The problem requires us to find the good strings between s1 and s2 that do not contain the evil substring. We can accomplish this using dynamic programming and KMP prefix function.

First, we preprocess the KMP prefix function for the evil string. The KMP prefix function can be used to match overlapping substrings within the evil string, which will help us to detect the presence of the evil substring in our generated string candidates.

Next, we create a dp table, with dimensions `[n+1][m]`, where `n` is the length of s1 and s2, and `m` is the length of the evil string. We initialize `dp[0][0]` to 1. The first dimension of the dp table keeps track of the current length of the generated string, while the second dimension keeps track of the length of the longest prefix of the evil string that matches the current suffix of the generated string.

Then, we iterate over the lengths of the string, and for each character in the current length, we check whether the character is a part of the evil substring. If it is not, we update the dp table accordingly. We also use the variable `k` to keep track of whether the generated substring is less than or equal to s2.

Finally, we return the result as `(dp[n][1] - dp[n][0] + MOD) % MOD`. This gives us the number of good strings without the evil substring, between s1 and s2.

## A solution in Python

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

def countGoodStrings(s1, s2, evil):
    n = len(s1)
    m = len(evil)
    dp = [[0] * m for _ in range(n + 1)]

    # Preprocess the KMP prefix function for the evil string
    lps = [0] * m
    len_ = 0
    i = 1
    while i < m:
        if evil[i] == evil[len_]:
            len_ += 1
            lps[i] = len_
            i += 1
        elif len_:
            len_ = lps[len_ - 1]
        else:
            i += 1

    dp[0][0] = 1
    for i in range(n):
        for j in range(m):
            for k in range(2):
                for c in range(ord('a'), ord(s2[i] if k else 'z') + 1):
                    e = j
                    while e and (chr(c) != evil[e]):
                        e = lps[e - 1]

                    if chr(c) != evil[e]:
                        e += 1

                    if e != m:
                        dp[i + 1][k | (c < ord(s2[i]))] += dp[i][k]
                        dp[i + 1][k | (c < ord(s2[i]))] %= MOD

    return (dp[n][1] - dp[n][0] + MOD) % MOD
```
The problem requires us to find the good strings between s1 and s2 that do not contain the evil substring. We can accomplish this using dynamic programming and KMP prefix function.

First, we preprocess the KMP prefix function for the evil string. The KMP prefix function can be used to match overlapping substrings within the evil string, which will help us to detect the presence of the evil substring in our generated string candidates.

Next, we create a dp table, with dimensions `[n+1][m]`, where `n` is the length of s1 and s2, and `m` is the length of the evil string. We initialize `dp[0][0]` to 1. The first dimension of the dp table keeps track of the current length of the generated string, while the second dimension keeps track of the length of the longest prefix of the evil string that matches the current suffix of the generated string.

Then, we iterate over the lengths of the string, and for each character in the current length, we check whether the character is a part of the evil substring. If it is not, we update the dp table accordingly. We also use the variable `k` to keep track of whether the generated substring is less than or equal to s2.

Finally, we return the result as `(dp[n][1] - dp[n][0] + MOD) % MOD`. This gives us the number of good strings without the evil substring, between s1 and s2.

## A solution in Javascript

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

function countGoodStrings(s1, s2, evil) {
    let n = s1.length;
    let m = evil.length;
    let dp = Array.from({length: n + 1}, () => Array(m).fill(0));

    // Preprocess the KMP prefix function for the evil string
    let lps = new Array(m).fill(0);
    let len = 0;
    for (let i = 1; i < m;) {
        if (evil[i] === evil[len]) {
            lps[i++] = ++len;
        } else if (len) {
            len = lps[len - 1];
        } else {
            ++i;
        }
    }

    dp[0][0] = 1;
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            for (let k = 0; k < 2; k++) {
                for (let c = 'a'.charCodeAt(0); c <= (k ? s2.charCodeAt(i) : 'z'.charCodeAt(0)); c++) {
                    let e = j;
                    while (e && (String.fromCharCode(c) !== evil[e])) {
                        e = lps[e - 1];
                    }

                    if (String.fromCharCode(c) !== evil[e]) {
                        e++;
                    }

                    if (e !== m) {
                        dp[i + 1][k | (c < s2.charCodeAt(i))] += dp[i][k];
                        dp[i + 1][k | (c < s2.charCodeAt(i))] %= MOD;
                    }
                }
            }
        }
    }

    return (dp[n][1] - dp[n][0] + MOD) % MOD;
}
```
The problem requires us to find the good strings between s1 and s2 that do not contain the evil substring. We can accomplish this using dynamic programming and KMP prefix function.

First, we preprocess the KMP prefix function for the evil string. The KMP prefix function can be used to match overlapping substrings within the evil string, which will help us to detect the presence of the evil substring in our generated string candidates.

Next, we create a dp table, with dimensions `[n+1][m]`, where `n` is the length of s1 and s2, and `m` is the length of the evil string. We initialize `dp[0][0]` to 1. The first dimension of the dp table keeps track of the current length of the generated string, while the second dimension keeps track of the length of the longest prefix of the evil string that matches the current suffix of the generated string.

Then, we iterate over the lengths of the string, and for each character in the current length, we check whether the character is a part of the evil substring. If it is not, we update the dp table accordingly. We also use the variable `k` to keep track of whether the generated substring is less than or equal to s2.

Finally, we return the result as `(dp[n][1] - dp[n][0] + MOD) % MOD`. This gives us the number of good strings without the evil substring, between s1 and s2.


# Path with Maximum Probability

- slug: path-with-maximum-probability
- difficulty: Medium

You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`.

Given two nodes `start` and `end`, find the path with the maximum probability of success to go from `start` to `end` and return its success probability.

If there is no path from `start` to `end`, **return 0**. Your answer will be accepted if it differs from the correct answer by at most **1e-5**.

**Example 1:**

**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[0,2\]\], succProb = \[0.5,0.5,0.2\], start = 0, end = 2
**Output:** 0.25000
**Explanation:** There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 \* 0.5 = 0.25.

**Example 2:**

**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[0,2\]\], succProb = \[0.5,0.5,0.3\], start = 0, end = 2
**Output:** 0.30000

**Example 3:**

**Input:** n = 3, edges = \[\[0,1\]\], succProb = \[0.5\], start = 0, end = 2
**Output:** 0.00000
**Explanation:** There is no path between 0 and 2.

**Constraints:**

*   `2 <= n <= 10^4`
*   `0 <= start, end < n`
*   `start != end`
*   `0 <= a, b < n`
*   `a != b`
*   `0 <= succProb.length == edges.length <= 2*10^4`
*   `0 <= succProb[i] <= 1`
*   There is at most one edge between every two nodes.

## A solution in Java

```java
public int minStartValue(int[] nums) {
    int min_sum = 0, sum = 0;
    for (int num : nums) {
        sum += num;
        min_sum = Math.min(min_sum, sum);
    }
    return 1 - min_sum;
}
```
We iterate through the array and at each iteration, we add the current element to the sum. We keep track of the minimum sum we've seen in min_sum. In the end, we return the result as 1 - min_sum, which ensures that the step by step sum is never less than 1.

## A solution in C++

```cpp
int minStartValue(std::vector<int>& nums) {
    int min_sum = 0, sum = 0;
    for (int num : nums) {
        sum += num;
        min_sum = std::min(min_sum, sum);
    }
    return 1 - min_sum;
}
```
We iterate through the array and at each iteration, we add the current element to the sum. We keep track of the minimum sum we've seen in min_sum. In the end, we return the result as 1 - min_sum, which ensures that the step by step sum is never less than 1.

## A solution in Python

```python
def min_start_value(nums):
    min_sum, sum = 0, 0
    for num in nums:
        sum += num
        min_sum = min(min_sum, sum)
    return 1 - min_sum
```
We iterate through the array and at each iteration, we add the current element to the sum. We keep track of the minimum sum we've seen in min_sum. In the end, we return the result as 1 - min_sum, which ensures that the step by step sum is never less than 1.

## A solution in Javascript

```javascript
function minStartValue(nums) {
    let min_sum = 0, sum = 0;
    for (const num of nums) {
        sum += num;
        min_sum = Math.min(min_sum, sum);
    }
    return 1 - min_sum;
}
```
We iterate through the array and at each iteration, we add the current element to the sum. We keep track of the minimum sum we've seen in min_sum. In the end, we return the result as 1 - min_sum, which ensures that the step by step sum is never less than 1.


# Best Position for a Service Centre

- slug: best-position-for-a-service-centre
- difficulty: Hard

A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.

Given an array `positions` where `positions[i] = [xi, yi]` is the position of the `ith` customer on the map, return _the minimum sum of the euclidean distances_ to all customers.

In other words, you need to choose the position of the service center `[xcentre, ycentre]` such that the following formula is minimized:

Answers within `10-5` of the actual value will be accepted.

**Example 1:**

**Input:** positions = \[\[0,1\],\[1,0\],\[1,2\],\[2,1\]\]
**Output:** 4.00000
**Explanation:** As shown, you can see that choosing \[xcentre, ycentre\] = \[1, 1\] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.

**Example 2:**

**Input:** positions = \[\[1,1\],\[3,3\]\]
**Output:** 2.82843
**Explanation:** The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843

**Constraints:**

*   `1 <= positions.length <= 50`
*   `positions[i].length == 2`
*   `0 <= xi, yi <= 100`

F(0) = 0, F(1) = 1, F(n) = F(n - 1) + F(n - 2) for n >= 2.

## A solution in Java

```java
public int findMinFibonacciNumbers(int k) {
    if (k == 0) return 0;
    int a = 0, b = 1;
    while (b <= k) {
        int temp = a;
        a = b;
        b = temp + a;
    }
    return 1 + findMinFibonacciNumbers(k - a);
}
```
The algorithm starts by initializing two variables to represent the Fibonacci sequence, a and b, initialized as 0 and 1 respectively. The algorithm then iterates through the Fibonacci sequence until it reaches a number greater than k, which will be stored in b. During iteration, a and b are swapped, and then, b is updated by adding the current value of a to the current value of b. Once the loop is done, the algorithm calls itself recursively by passing (k - a) as an input, which will deduct the last Fibonacci number found from k. Finally, the count returned from this recursive call is incremented by 1 (because we found one Fibonacci number in the current call), and the result is returned.

This process continues recursively until k reaches 0, which means we've found the minimum number of Fibonacci numbers that sum up to k.

## A solution in C++

```cpp
int findMinFibonacciNumbers(int k) {
    if (k == 0) return 0;
    int a = 0, b = 1;
    while (b <= k) {
        swap(a, b);
        b += a;
    }
    return 1 + findMinFibonacciNumbers(k - a);
}
```
The algorithm starts by initializing two variables to represent the Fibonacci sequence, a and b, initialized as 0 and 1 respectively. The algorithm then iterates through the Fibonacci sequence until it reaches a number greater than k, which will be stored in b. During iteration, a and b are swapped, and then, b is updated by adding the current value of a to the current value of b. Once the loop is done, the algorithm calls itself recursively by passing (k - a) as an input, which will deduct the last Fibonacci number found from k. Finally, the count returned from this recursive call is incremented by 1 (because we found one Fibonacci number in the current call), and the result is returned.

This process continues recursively until k reaches 0, which means we've found the minimum number of Fibonacci numbers that sum up to k.

## A solution in Python

```python
def find_min_fibonacci_numbers(k):
    if k == 0:
        return 0
    a, b = 0, 1
    while b <= k:
        a, b = b, a + b
    return 1 + find_min_fibonacci_numbers(k - a)
```
The algorithm starts by initializing two variables to represent the Fibonacci sequence, a and b, initialized as 0 and 1 respectively. The algorithm then iterates through the Fibonacci sequence until it reaches a number greater than k, which will be stored in b. During iteration, a and b are swapped, and then, b is updated by adding the current value of a to the current value of b. Once the loop is done, the algorithm calls itself recursively by passing (k - a) as an input, which will deduct the last Fibonacci number found from k. Finally, the count returned from this recursive call is incremented by 1 (because we found one Fibonacci number in the current call), and the result is returned.

This process continues recursively until k reaches 0, which means we've found the minimum number of Fibonacci numbers that sum up to k.

## A solution in Javascript

```javascript
function findMinFibonacciNumbers(k) {
    if (k === 0) return 0;
    let a = 0, b = 1;
    while (b <= k) {
        [a, b] = [b, a + b];
    }
    return 1 + findMinFibonacciNumbers(k - a);
}
```
The algorithm starts by initializing two variables to represent the Fibonacci sequence, a and b, initialized as 0 and 1 respectively. The algorithm then iterates through the Fibonacci sequence until it reaches a number greater than k, which will be stored in b. During iteration, a and b are swapped, and then, b is updated by adding the current value of a to the current value of b. Once the loop is done, the algorithm calls itself recursively by passing (k - a) as an input, which will deduct the last Fibonacci number found from k. Finally, the count returned from this recursive call is incremented by 1 (because we found one Fibonacci number in the current call), and the result is returned.

This process continues recursively until k reaches 0, which means we've found the minimum number of Fibonacci numbers that sum up to k.


# Move Sub-Tree of N-Ary Tree

- slug: move-sub-tree-of-n-ary-tree
- difficulty: Hard

Given the `root` of an N-ary tree of unique values, and two nodes of the tree `p` and `q`.

You should move the subtree of the node `p` to become a direct child of node `q`. If `p` is already a direct child of `q`, do not change anything. Node `p` **must be** the last child in the children list of node `q`.

Return _the root of the tree_ after adjusting it.

There are 3 cases for nodes `p` and `q`:

1.  Node `q` is in the sub-tree of node `p`.
2.  Node `p` is in the sub-tree of node `q`.
3.  Neither node `p` is in the sub-tree of node `q` nor node `q` is in the sub-tree of node `p`.

In cases 2 and 3, you just need to move `p` (with its sub-tree) to be a child of `q`, but in case 1 the tree may be disconnected, thus you need to reconnect the tree again. **Please read the examples carefully before solving this problem.**

_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._

For example, the above tree is serialized as `[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]`.

**Example 1:**

**Input:** root = \[1,null,2,3,null,4,5,null,6,null,7,8\], p = 4, q = 1
**Output:** \[1,null,2,3,4,null,5,null,6,null,7,8\]
**Explanation:** This example follows the second case as node p is in the sub-tree of node q. We move node p with its sub-tree to be a direct child of node q.
Notice that node 4 is the last child of node 1.

**Example 2:**

**Input:** root = \[1,null,2,3,null,4,5,null,6,null,7,8\], p = 7, q = 4
**Output:** \[1,null,2,3,null,4,5,null,6,null,7,8\]
**Explanation:** Node 7 is already a direct child of node 4. We don't change anything.

**Example 3:**

**Input:** root = \[1,null,2,3,null,4,5,null,6,null,7,8\], p = 3, q = 8
**Output:** \[1,null,2,null,4,5,null,7,8,null,null,null,3,null,6\]
**Explanation:** This example follows case 3 because node p is not in the sub-tree of node q and vice-versa. We can move node 3 with its sub-tree and make it as node 8's child.

**Constraints:**

*   The total number of nodes is between `[2, 1000]`.
*   Each node has a **unique** value.
*   `p != null`
*   `q != null`
*   `p` and `q` are two different nodes (i.e. `p != q`).

## A solution in Java

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

public String getHappyString(int n, int k) {
    List<String> happyStrings = new ArrayList<>();
    dfs(happyStrings, n, "", ' ');
    return k <= happyStrings.size() ? happyStrings.get(k - 1) : "";
}

private void dfs(List<String> happyStrings, int n, String s, char prev) {
    if (s.length() == n) {
        happyStrings.add(s);
        return;
    }
    for (char c = 'a'; c <= 'c'; c++) {
        if (c != prev) {
            dfs(happyStrings, n, s + c, c);
        }
    }
}
```
The algorithm is a depth-first search approach to generate all happy strings of length n. Since the maximum length of n is 10, and we only need to iterate through 3 characters each time, the solution's complexity is acceptable.

We start with an empty string and a space as the previous character. The DFS function checks if the given string has reached the length n. If it has, we add the string to our list of happy strings and return.

If the string has not reached length n, we iterate through the characters 'a', 'b', and 'c'. If the current character is not equal to the previous character, we call the DFS function with the updated string and the current character as the new previous character. This ensures that we construct happy strings by never including consecutive same characters.

After the DFS function is done traversing all possible happy strings, we check if k is less than or equal to the length of our happy string list. If it is, we return the kth element (k - 1 due to zero-based indexing). Otherwise, we return an empty string since there are fewer than k happy strings of length n.

## A solution in C++

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

std::string getHappyString(int n, int k) {
    std::vector<std::string> happyStrings;
    std::function<void(std::string, char)> dfs = [&](std::string s, char prev) {
        if (s.length() == n) {
            happyStrings.push_back(s);
            return;
        }
        for (char c = 'a'; c <= 'c'; c++) {
            if (c != prev) {
                dfs(s + c, c);
            }
        }
    };
    dfs("", ' ');
    return k <= happyStrings.size() ? happyStrings[k - 1] : "";
}
```
The algorithm is a depth-first search approach to generate all happy strings of length n. Since the maximum length of n is 10, and we only need to iterate through 3 characters each time, the solution's complexity is acceptable.

We start with an empty string and a space as the previous character. The DFS function checks if the given string has reached the length n. If it has, we add the string to our list of happy strings and return.

If the string has not reached length n, we iterate through the characters 'a', 'b', and 'c'. If the current character is not equal to the previous character, we call the DFS function with the updated string and the current character as the new previous character. This ensures that we construct happy strings by never including consecutive same characters.

After the DFS function is done traversing all possible happy strings, we check if k is less than or equal to the length of our happy string list. If it is, we return the kth element (k - 1 due to zero-based indexing). Otherwise, we return an empty string since there are fewer than k happy strings of length n.

## A solution in Python

```python
def get_happy_string(n, k):
    def dfs(s, prev):
        if len(s) == n:
            happy_strings.append(s)
            return
        for c in 'abc':
            if c != prev:
                dfs(s + c, c)

    happy_strings = []
    dfs("", ' ')
    return happy_strings[k - 1] if k <= len(happy_strings) else ""
```
The algorithm is a depth-first search approach to generate all happy strings of length n. Since the maximum length of n is 10, and we only need to iterate through 3 characters each time, the solution's complexity is acceptable.

We start with an empty string and a space as the previous character. The DFS function checks if the given string has reached the length n. If it has, we add the string to our list of happy strings and return.

If the string has not reached length n, we iterate through the characters 'a', 'b', and 'c'. If the current character is not equal to the previous character, we call the DFS function with the updated string and the current character as the new previous character. This ensures that we construct happy strings by never including consecutive same characters.

After the DFS function is done traversing all possible happy strings, we check if k is less than or equal to the length of our happy string list. If it is, we return the kth element (k - 1 due to zero-based indexing). Otherwise, we return an empty string since there are fewer than k happy strings of length n.

## A solution in Javascript

```javascript
function getHappyString(n, k) {
    const happyStrings = [];
    const dfs = (s, prev) => {
        if (s.length === n) {
            happyStrings.push(s);
            return;
        }
        for (let c = 'a'.charCodeAt(); c <= 'c'.charCodeAt(); c++) {
            const char = String.fromCharCode(c);
            if (char !== prev) {
                dfs(s + char, char);
            }
        }
    };
    dfs('', ' ');
    return k <= happyStrings.length ? happyStrings[k - 1] : "";
}
```
The algorithm is a depth-first search approach to generate all happy strings of length n. Since the maximum length of n is 10, and we only need to iterate through 3 characters each time, the solution's complexity is acceptable.

We start with an empty string and a space as the previous character. The DFS function checks if the given string has reached the length n. If it has, we add the string to our list of happy strings and return.

If the string has not reached length n, we iterate through the characters 'a', 'b', and 'c'. If the current character is not equal to the previous character, we call the DFS function with the updated string and the current character as the new previous character. This ensures that we construct happy strings by never including consecutive same characters.

After the DFS function is done traversing all possible happy strings, we check if k is less than or equal to the length of our happy string list. If it is, we return the kth element (k - 1 due to zero-based indexing). Otherwise, we return an empty string since there are fewer than k happy strings of length n.


# Water Bottles

- slug: water-bottles
- difficulty: Easy

There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.

The operation of drinking a full water bottle turns it into an empty bottle.

Given the two integers `numBottles` and `numExchange`, return _the **maximum** number of water bottles you can drink_.

**Example 1:**

**Input:** numBottles = 9, numExchange = 3
**Output:** 13
**Explanation:** You can exchange 3 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 9 + 3 + 1 = 13.

**Example 2:**

**Input:** numBottles = 15, numExchange = 4
**Output:** 19
**Explanation:** You can exchange 4 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 15 + 3 + 1 = 19.

**Constraints:**

*   `1 <= numBottles <= 100`
*   `2 <= numExchange <= 100`

## A solution in Java

```java
public int numWaterBottles(int numBottles, int numExchange) {
    int totalBottles = numBottles;
    while (numBottles >= numExchange) {
        int newBottles = numBottles / numExchange;
        totalBottles += newBottles;
        numBottles = newBottles + numBottles % numExchange;
    }
    return totalBottles;
}
```
The algorithm initializes the totalBottles variable with the value of numBottles. It then uses a while loop to repeatedly calculate the number of new full bottles the person can get by exchanging the current number of empty bottles.

In each iteration, the loop calculates the new number of full bottles by dividing numBottles by numExchange and flooring the result. It then adds these new bottles to the totalBottles variable. The loop also updates the number of empty bottles by adding the new full bottles and the remainder of numBottles divided by numExchange.

Once the number of empty bottles is less than the required numExchange, the loop terminates, and the function returns the value of totalBottles as the maximum number of water bottles the person can drink.

## A solution in C++

```cpp
int numWaterBottles(int numBottles, int numExchange) {
    int totalBottles = numBottles;
    while (numBottles >= numExchange) {
        int newBottles = numBottles / numExchange;
        totalBottles += newBottles;
        numBottles = newBottles + numBottles % numExchange;
    }
    return totalBottles;
}
```
The algorithm initializes the totalBottles variable with the value of numBottles. It then uses a while loop to repeatedly calculate the number of new full bottles the person can get by exchanging the current number of empty bottles.

In each iteration, the loop calculates the new number of full bottles by dividing numBottles by numExchange and flooring the result. It then adds these new bottles to the totalBottles variable. The loop also updates the number of empty bottles by adding the new full bottles and the remainder of numBottles divided by numExchange.

Once the number of empty bottles is less than the required numExchange, the loop terminates, and the function returns the value of totalBottles as the maximum number of water bottles the person can drink.

## A solution in Python

```python
def numWaterBottles(numBottles: int, numExchange: int) -> int:
    totalBottles = numBottles
    while numBottles >= numExchange:
        newBottles = numBottles // numExchange
        totalBottles += newBottles
        numBottles = newBottles + numBottles % numExchange
    return totalBottles
```
The algorithm initializes the totalBottles variable with the value of numBottles. It then uses a while loop to repeatedly calculate the number of new full bottles the person can get by exchanging the current number of empty bottles.

In each iteration, the loop calculates the new number of full bottles by dividing numBottles by numExchange and flooring the result. It then adds these new bottles to the totalBottles variable. The loop also updates the number of empty bottles by adding the new full bottles and the remainder of numBottles divided by numExchange.

Once the number of empty bottles is less than the required numExchange, the loop terminates, and the function returns the value of totalBottles as the maximum number of water bottles the person can drink.

## A solution in Javascript

```javascript
function numWaterBottles(numBottles, numExchange) {
    let totalBottles = numBottles;
    while (numBottles >= numExchange) {
        let newBottles = Math.floor(numBottles / numExchange);
        totalBottles += newBottles;
        numBottles = newBottles + numBottles % numExchange;
    }
    return totalBottles;
}
```
The algorithm initializes the totalBottles variable with the value of numBottles. It then uses a while loop to repeatedly calculate the number of new full bottles the person can get by exchanging the current number of empty bottles.

In each iteration, the loop calculates the new number of full bottles by dividing numBottles by numExchange and flooring the result. It then adds these new bottles to the totalBottles variable. The loop also updates the number of empty bottles by adding the new full bottles and the remainder of numBottles divided by numExchange.

Once the number of empty bottles is less than the required numExchange, the loop terminates, and the function returns the value of totalBottles as the maximum number of water bottles the person can drink.


# Number of Nodes in the Sub-Tree With the Same Label

- slug: number-of-nodes-in-the-sub-tree-with-the-same-label
- difficulty: Medium

You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node with the number `i` has the label `labels[i]`).

The `edges` array is given on the form `edges[i] = [ai, bi]`, which means there is an edge between nodes `ai` and `bi` in the tree.

Return _an array of size `n`_ where `ans[i]` is the number of nodes in the subtree of the `ith` node which have the same label as node `i`.

A subtree of a tree `T` is the tree consisting of a node in `T` and all of its descendant nodes.

**Example 1:**

**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], labels =  "abaedcd "
**Output:** \[2,1,1,1,1,1,1\]
**Explanation:** Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).

**Example 2:**

**Input:** n = 4, edges = \[\[0,1\],\[1,2\],\[0,3\]\], labels =  "bbbb "
**Output:** \[4,2,1,1\]
**Explanation:** The sub-tree of node 2 contains only node 2, so the answer is 1.
The sub-tree of node 3 contains only node 3, so the answer is 1.
The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.

**Example 3:**

**Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[1,3\],\[0,4\]\], labels =  "aabab "
**Output:** \[3,2,1,1,1\]

**Constraints:**

*   `1 <= n <= 105`
*   `edges.length == n - 1`
*   `edges[i].length == 2`
*   `0 <= ai, bi < n`
*   `ai != bi`
*   `labels.length == n`
*   `labels` is consisting of only of lowercase English letters.

## A solution in Java

```java
import java.util.*;

class Solution {
    public List<Integer> minSubsequence(int[] nums) {
        List<Integer> result = new ArrayList<Integer>();
        Arrays.sort(nums);
        int totalSum = 0, currentSum = 0;
        for (int num : nums) {
            totalSum += num;
        }
        for (int i = nums.length - 1; i >= 0; i--) {
            currentSum += nums[i];
            result.add(nums[i]);
            if (currentSum > totalSum - currentSum) {
                break;
            }
        }
        return result;
    }
}
```
The algorithm starts by sorting the array in non-increasing order. Then, it iterates through the sorted array, adding each element to the subsequence, and keeping track of the sum of the subsequence. The loop terminates once the sum of the subsequence becomes strictly greater than the sum of the non-included elements. Since the array is sorted in non-increasing order, this guarantees that the resulting subsequence is of minimum size and has the maximum sum of all possible solutions. Finally, the subsequence is returned.

## A solution in C++

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

std::vector<int> minSubsequence(std::vector<int>& nums) {
    std::sort(nums.begin(), nums.end(), std::greater<int>());
    int totalSum = 0, currentSum = 0;
    for (int num : nums) {
        totalSum += num;
    }
    std::vector<int> result;
    for (int num : nums) {
        currentSum += num;
        result.push_back(num);
        if (currentSum > totalSum - currentSum) {
            break;
        }
    }
    return result;
}
```
The algorithm starts by sorting the array in non-increasing order. Then, it iterates through the sorted array, adding each element to the subsequence, and keeping track of the sum of the subsequence. The loop terminates once the sum of the subsequence becomes strictly greater than the sum of the non-included elements. Since the array is sorted in non-increasing order, this guarantees that the resulting subsequence is of minimum size and has the maximum sum of all possible solutions. Finally, the subsequence is returned.

## A solution in Python

```python
def min_subsequence(nums):
    nums.sort(reverse=True)
    total_sum, current_sum = sum(nums), 0
    result = []
    for num in nums:
        current_sum += num
        result.append(num)
        if current_sum > total_sum - current_sum:
            break
    return result
```
The algorithm starts by sorting the array in non-increasing order. Then, it iterates through the sorted array, adding each element to the subsequence, and keeping track of the sum of the subsequence. The loop terminates once the sum of the subsequence becomes strictly greater than the sum of the non-included elements. Since the array is sorted in non-increasing order, this guarantees that the resulting subsequence is of minimum size and has the maximum sum of all possible solutions. Finally, the subsequence is returned.

## A solution in Javascript

```javascript
function minSubsequence(nums) {
    nums.sort((a, b) => b - a);
    const totalSum = nums.reduce((a, b) => a + b, 0);
    let currentSum = 0;
    const result = [];
    for (const num of nums) {
        currentSum += num;
        result.push(num);
        if (currentSum > totalSum - currentSum) {
            break;
        }
    }
    return result;
}
```
The algorithm starts by sorting the array in non-increasing order. Then, it iterates through the sorted array, adding each element to the subsequence, and keeping track of the sum of the subsequence. The loop terminates once the sum of the subsequence becomes strictly greater than the sum of the non-included elements. Since the array is sorted in non-increasing order, this guarantees that the resulting subsequence is of minimum size and has the maximum sum of all possible solutions. Finally, the subsequence is returned.


# Maximum Number of Non-Overlapping Substrings

- slug: maximum-number-of-non-overlapping-substrings
- difficulty: Hard

Given a string `s` of lowercase letters, you need to find the maximum number of **non-empty** substrings of `s` that meet the following conditions:

1.  The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[x..y]`, either `j < x` or `i > y` is true.
2.  A substring that contains a certain character `c` must also contain all occurrences of `c`.

Find _the maximum number of substrings that meet the above conditions_. If there are multiple solutions with the same number of substrings, _return the one with minimum total length._ It can be shown that there exists a unique solution of minimum total length.

Notice that you can return the substrings in **any** order.

**Example 1:**

**Input:** s =  "adefaddaccc "
**Output:** \[ "e ", "f ", "ccc "\]
**Explanation:** The following are all the possible substrings that meet the conditions:
\[
   "adefaddaccc "
   "adefadda ",
   "ef ",
   "e ",
   "f ",
   "ccc ",
\]
If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose  "adefadda ", we are left with  "ccc " which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose  "ef " since it can be split into two. Therefore, the optimal way is to choose \[ "e ", "f ", "ccc "\] which gives us 3 substrings. No other solution of the same number of substrings exist.

**Example 2:**

**Input:** s =  "abbaccd "
**Output:** \[ "d ", "bb ", "cc "\]
**Explanation:** Notice that while the set of substrings \[ "d ", "abba ", "cc "\] also has length 3, it's considered incorrect since it has larger total length.

**Constraints:**

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

## A solution in Java

```java
public int numSteps(String s) {
    int steps = 0, carry = 0;
    for (int i = s.length() - 1; i > 0; --i) {
        int current = s.charAt(i) - '0' + carry;
        if (current == 1) {
            steps += 2;
            carry = 1;
        } else {
            steps += carry;
            carry = current;
        }
    }

    return steps + carry;
}
```
1. Initialize the count of steps and carry to 0.
2. Iterate through the elements of the binary string from the least significant digit to the most significant digit.
3. In each iteration, add the carry and the current digit.
4. If the result is 1, increment the steps by 2 and update the carry to 1.
5. If the result is not 1, increment the steps by the previous carry and update the carry with the result.
6. Return the total number of steps taken plus the final carry.

## A solution in C++

```cpp
int num_steps(const std::string& s) {
    int steps = 0, carry = 0;
    for (int i = s.size() - 1; i > 0; --i) {
        if (s[i] - '0' + carry == 1) {
            steps += 2;
            carry = 1;
        } else {
            steps += carry;
            carry = s[i] - '0';
        }
    }

    return steps + carry;
}
```
1. Initialize the count of steps and carry to 0.
2. Iterate through the elements of the binary string from the least significant digit to the most significant digit.
3. In each iteration, add the carry and the current digit.
4. If the result is 1, increment the steps by 2 and update the carry to 1.
5. If the result is not 1, increment the steps by the previous carry and update the carry with the result.
6. Return the total number of steps taken plus the final carry.

## A solution in Python

```python
def num_steps(s: str) -> int:
    steps = 0
    carry = 0

    for i in range(len(s) - 1, 0, -1):
        current = int(s[i]) + carry
        if current == 1:
            steps += 2
            carry = 1
        else:
            steps += carry
            carry = current

    return steps + carry
```
1. Initialize the count of steps and carry to 0.
2. Iterate through the elements of the binary string from the least significant digit to the most significant digit.
3. In each iteration, add the carry and the current digit.
4. If the result is 1, increment the steps by 2 and update the carry to 1.
5. If the result is not 1, increment the steps by the previous carry and update the carry with the result.
6. Return the total number of steps taken plus the final carry.

## A solution in Javascript

```javascript
function numSteps(s) {
    let steps = 0, carry = 0;
    for (let i = s.length - 1; i > 0; --i) {
        let current = parseInt(s[i]) + carry;
        if (current == 1) {
            steps += 2;
            carry = 1;
        } else {
            steps += carry;
            carry = current;
        }
    }

    return steps + carry;
}
```
1. Initialize the count of steps and carry to 0.
2. Iterate through the elements of the binary string from the least significant digit to the most significant digit.
3. In each iteration, add the carry and the current digit.
4. If the result is 1, increment the steps by 2 and update the carry to 1.
5. If the result is not 1, increment the steps by the previous carry and update the carry with the result.
6. Return the total number of steps taken plus the final carry.


# Find a Value of a Mysterious Function Closest to Target

- slug: find-a-value-of-a-mysterious-function-closest-to-target
- difficulty: Hard

Winston was given the above mysterious function `func`. He has an integer array `arr` and an integer `target` and he wants to find the values `l` and `r` that make the value `|func(arr, l, r) - target|` minimum possible.

Return _the minimum possible value_ of `|func(arr, l, r) - target|`.

Notice that `func` should be called with the values `l` and `r` where `0 <= l, r < arr.length`.

**Example 1:**

**Input:** arr = \[9,12,3,7,15\], target = 5
**Output:** 2
**Explanation:** Calling func with all the pairs of \[l,r\] = \[\[0,0\],\[1,1\],\[2,2\],\[3,3\],\[4,4\],\[0,1\],\[1,2\],\[2,3\],\[3,4\],\[0,2\],\[1,3\],\[2,4\],\[0,3\],\[1,4\],\[0,4\]\], Winston got the following results \[9,12,3,7,15,8,0,3,7,0,0,3,0,0,0\]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.

**Example 2:**

**Input:** arr = \[1000000,1000000,1000000\], target = 1
**Output:** 999999
**Explanation:** Winston called the func with all possible values of \[l,r\] and he always got 1000000, thus the min difference is 999999.

**Example 3:**

**Input:** arr = \[1,2,4,8,16\], target = 0
**Output:** 0

**Constraints:**

*   `1 <= arr.length <= 105`
*   `1 <= arr[i] <= 106`
*   `0 <= target <= 107`

## A solution in Java

```java
public int closestToTarget(int[] arr, int target) {
    int minDiff = Integer.MAX_VALUE;
    Set<Integer> prefix = new HashSet<>();

    for (int n : arr) {
        Set<Integer> nextPrefix = new HashSet<>();
        for (int p : prefix) {
            nextPrefix.add(p & n);
        }
        nextPrefix.add(n);

        for (int p : nextPrefix) {
            minDiff = Math.min(minDiff, Math.abs(p - target));
        }
        prefix = nextPrefix;
    }
    return minDiff;
}
```
The algorithm iterates over each value `n` in the given array `arr`. For each `n`, it maintains a set `prefix` that contains all the bitwise AND results from the subsequences that end at the current index. For each value `p` in the current `prefix`, it calculates a new set `next_prefix` by applying the bitwise AND operation using the current value `n`. This way, it keeps track of all the possible bitwise AND values while iterating over the array. Then, it evaluates the difference between each of these values `p` and the target `target`, updating the `min_diff` whenever a smaller difference is found.

## A solution in C++

```cpp
int closestToTarget(vector<int>& arr, int target) {
    int min_diff = INT_MAX;
    unordered_set<int> prefix;

    for (int n : arr) {
        unordered_set<int> next_prefix;
        for (int p : prefix) {
            next_prefix.insert(p & n);
        }
        next_prefix.insert(n);

        for (int p : next_prefix) {
            min_diff = min(min_diff, abs(p - target));
        }
        swap(prefix, next_prefix);
    }
    return min_diff;
}
```
The algorithm iterates over each value `n` in the given array `arr`. For each `n`, it maintains a set `prefix` that contains all the bitwise AND results from the subsequences that end at the current index. For each value `p` in the current `prefix`, it calculates a new set `next_prefix` by applying the bitwise AND operation using the current value `n`. This way, it keeps track of all the possible bitwise AND values while iterating over the array. Then, it evaluates the difference between each of these values `p` and the target `target`, updating the `min_diff` whenever a smaller difference is found.

## A solution in Python

```python
def closestToTarget(arr: List[int], target: int) -> int:
    min_diff = float('inf')
    prefix = set()

    for n in arr:
        next_prefix = set()
        for p in prefix:
            next_prefix.add(p & n)
        next_prefix.add(n)

        for p in next_prefix:
            min_diff = min(min_diff, abs(p - target))
        prefix = next_prefix
    return min_diff
```
The algorithm iterates over each value `n` in the given array `arr`. For each `n`, it maintains a set `prefix` that contains all the bitwise AND results from the subsequences that end at the current index. For each value `p` in the current `prefix`, it calculates a new set `next_prefix` by applying the bitwise AND operation using the current value `n`. This way, it keeps track of all the possible bitwise AND values while iterating over the array. Then, it evaluates the difference between each of these values `p` and the target `target`, updating the `min_diff` whenever a smaller difference is found.

## A solution in Javascript

```javascript
function closestToTarget(arr, target) {
    let minDiff = Infinity;
    let prefix = new Set();

    for (const n of arr) {
        let nextPrefix = new Set();
        for (const p of prefix) {
            nextPrefix.add(p & n);
        }
        nextPrefix.add(n);

        for (const p of nextPrefix) {
            minDiff = Math.min(minDiff, Math.abs(p - target));
        }
        prefix = nextPrefix;
    }
    return minDiff;
}
```
The algorithm iterates over each value `n` in the given array `arr`. For each `n`, it maintains a set `prefix` that contains all the bitwise AND results from the subsequences that end at the current index. For each value `p` in the current `prefix`, it calculates a new set `next_prefix` by applying the bitwise AND operation using the current value `n`. This way, it keeps track of all the possible bitwise AND values while iterating over the array. Then, it evaluates the difference between each of these values `p` and the target `target`, updating the `min_diff` whenever a smaller difference is found.


# Diameter of N-Ary Tree

- slug: diameter-of-n-ary-tree
- difficulty: Medium

Given a `root` of an [N-ary tree](https://leetcode.com/articles/introduction-to-n-ary-trees/), you need to compute the length of the diameter of the tree.

The diameter of an N-ary tree is the length of the **longest** path between any two nodes in the tree. This path may or may not pass through the root.

(_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value.)_

**Example 1:**

**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** 3
**Explanation:** Diameter is shown in red color.

**Example 2:**

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

**Example 3:**

**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** 7

**Constraints:**

*   The depth of the n-ary tree is less than or equal to `1000`.
*   The total number of nodes is between `[1, 104]`.

## A solution in Java

```java
public String stoneGameIII(int[] stoneValue) {
    int n = stoneValue.length;
    int[] dp = new int[n + 1];
    dp[n - 1] = stoneValue[n - 1];
    for (int i = n - 2; i >= 0; --i) {
        dp[i] = stoneValue[i] - dp[i + 1];
        for (int j = 1; j < 3; ++j) {
            if (i + j < n)
                dp[i] = Math.max(dp[i], stoneValue[i + j] - dp[i + j + 1]);
        }
    }
    if (dp[0] > 0) return "Alice";
    if (dp[0] < 0) return "Bob";
    return "Tie";
}
```
We use a dynamic programming approach with a dp array. The dp array is used to store the difference in stone values for each optimal move. We initialize the last element of the dp array as the last element of the stoneValue array. We run a for loop iterating from the second-last element to the first element of the stoneValue array. For each iteration, we initialize dp[i] as the stone value at index i minus the dp value of the next index. Then, we run another for loop inside this loop for two iterations (since players can take up to 3 stones but we already considered taking 1 stone) and update dp[i] by taking the maximum value between the current dp[i] and the value of the stones for each iteration. After completing the loops, we check if dp[0] is positive, negative, or zero and return "Alice", "Bob", or "Tie" accordingly.

## A solution in C++

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

string stoneGameIII(const vector<int>& stoneValue) {
    int n = stoneValue.size();
    vector<int> dp(n + 1, 0);
    dp[n - 1] = stoneValue[n - 1];
    for (int i = n - 2; i >= 0; --i) {
        dp[i] = stoneValue[i] - dp[i + 1];
        for (int j = 1; j < 3; ++j) {
            if (i + j < n)
                dp[i] = max(dp[i], stoneValue[i + j] - dp[i + j + 1]);
        }
    }
    if (dp[0] > 0) return "Alice";
    if (dp[0] < 0) return "Bob";
    return "Tie";
}
```
We use a dynamic programming approach with a dp array. The dp array is used to store the difference in stone values for each optimal move. We initialize the last element of the dp array as the last element of the stoneValue array. We run a for loop iterating from the second-last element to the first element of the stoneValue array. For each iteration, we initialize dp[i] as the stone value at index i minus the dp value of the next index. Then, we run another for loop inside this loop for two iterations (since players can take up to 3 stones but we already considered taking 1 stone) and update dp[i] by taking the maximum value between the current dp[i] and the value of the stones for each iteration. After completing the loops, we check if dp[0] is positive, negative, or zero and return "Alice", "Bob", or "Tie" accordingly.

## A solution in Python

```python
def stoneGameIII(stoneValue):
    n = len(stoneValue)
    dp = [0] * (n + 1)
    dp[n - 1] = stoneValue[n - 1]
    for i in range(n - 2, -1, -1):
        dp[i] = stoneValue[i] - dp[i + 1]
        for j in range(1, 3):
            if i + j < n:
                dp[i] = max(dp[i], stoneValue[i + j] - dp[i + j + 1])
    if dp[0] > 0: return "Alice"
    if dp[0] < 0: return "Bob"
    return "Tie"
```
We use a dynamic programming approach with a dp array. The dp array is used to store the difference in stone values for each optimal move. We initialize the last element of the dp array as the last element of the stoneValue array. We run a for loop iterating from the second-last element to the first element of the stoneValue array. For each iteration, we initialize dp[i] as the stone value at index i minus the dp value of the next index. Then, we run another for loop inside this loop for two iterations (since players can take up to 3 stones but we already considered taking 1 stone) and update dp[i] by taking the maximum value between the current dp[i] and the value of the stones for each iteration. After completing the loops, we check if dp[0] is positive, negative, or zero and return "Alice", "Bob", or "Tie" accordingly.

## A solution in Javascript

```javascript
function stoneGameIII(stoneValue) {
    const n = stoneValue.length;
    const dp = new Array(n + 1).fill(0);
    dp[n - 1] = stoneValue[n - 1];
    for (let i = n - 2; i >= 0; --i) {
        dp[i] = stoneValue[i] - dp[i + 1];
        for (let j = 1; j < 3; ++j) {
            if (i + j < n)
                dp[i] = Math.max(dp[i], stoneValue[i + j] - dp[i + j + 1]);
        }
    }
    if (dp[0] > 0) return "Alice";
    if (dp[0] < 0) return "Bob";
    return "Tie";
}
```
We use a dynamic programming approach with a dp array. The dp array is used to store the difference in stone values for each optimal move. We initialize the last element of the dp array as the last element of the stoneValue array. We run a for loop iterating from the second-last element to the first element of the stoneValue array. For each iteration, we initialize dp[i] as the stone value at index i minus the dp value of the next index. Then, we run another for loop inside this loop for two iterations (since players can take up to 3 stones but we already considered taking 1 stone) and update dp[i] by taking the maximum value between the current dp[i] and the value of the stones for each iteration. After completing the loops, we check if dp[0] is positive, negative, or zero and return "Alice", "Bob", or "Tie" accordingly.


# Count Odd Numbers in an Interval Range

- slug: count-odd-numbers-in-an-interval-range
- difficulty: Easy

Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` _(inclusive)_.

**Example 1:**

**Input:** low = 3, high = 7
**Output:** 3
**Explanation:** The odd numbers between 3 and 7 are \[3,5,7\].

**Example 2:**

**Input:** low = 8, high = 10
**Output:** 1
**Explanation:** The odd numbers between 8 and 10 are \[9\].

**Constraints:**

*   `0 <= low <= high <= 10^9`

## A solution in Java

```java
public int countOdds(int low, int high) {
    return (high - low) / 2 + ((low % 2 == 1 || high % 2 == 1) ? 1 : 0);
}
```
The algorithm first calculates the total number of integer values between `low` and `high`, using the difference divided by 2. Then, it checks whether `low` or `high` is odd (remainder when divided by 2 equals 1). If either of them is odd, it means we have one more odd number to include, so we add 1 to the result. Otherwise, we don't add anything, as the range does not include an extra odd number. This algorithm is efficient and will directly provide the count of odd numbers within the range without any looping.

## A solution in C++

```cpp
int count_odds(int low, int high) {
    return (high - low) / 2 + ((low % 2 == 1 || high % 2 == 1) ? 1 : 0);
}
```
The algorithm first calculates the total number of integer values between `low` and `high`, using the difference divided by 2. Then, it checks whether `low` or `high` is odd (remainder when divided by 2 equals 1). If either of them is odd, it means we have one more odd number to include, so we add 1 to the result. Otherwise, we don't add anything, as the range does not include an extra odd number. This algorithm is efficient and will directly provide the count of odd numbers within the range without any looping.

## A solution in Python

```python
def count_odds(low, high):
    return (high - low) // 2 + (1 if low % 2 == 1 or high % 2 == 1 else 0)
```
The algorithm first calculates the total number of integer values between `low` and `high`, using the difference divided by 2. Then, it checks whether `low` or `high` is odd (remainder when divided by 2 equals 1). If either of them is odd, it means we have one more odd number to include, so we add 1 to the result. Otherwise, we don't add anything, as the range does not include an extra odd number. This algorithm is efficient and will directly provide the count of odd numbers within the range without any looping.

## A solution in Javascript

```javascript
function countOdds(low, high) {
    return Math.floor((high - low) / 2) + ((low % 2 === 1 || high % 2 === 1) ? 1 : 0);
}
```
The algorithm first calculates the total number of integer values between `low` and `high`, using the difference divided by 2. Then, it checks whether `low` or `high` is odd (remainder when divided by 2 equals 1). If either of them is odd, it means we have one more odd number to include, so we add 1 to the result. Otherwise, we don't add anything, as the range does not include an extra odd number. This algorithm is efficient and will directly provide the count of odd numbers within the range without any looping.


# Number of Sub-arrays With Odd Sum

- slug: number-of-sub-arrays-with-odd-sum
- difficulty: Medium

Given an array of integers `arr`, return _the number of subarrays with an **odd** sum_.

Since the answer can be very large, return it modulo `109 + 7`.

**Example 1:**

**Input:** arr = \[1,3,5\]
**Output:** 4
**Explanation:** All subarrays are \[\[1\],\[1,3\],\[1,3,5\],\[3\],\[3,5\],\[5\]\]
All sub-arrays sum are \[1,4,9,3,8,5\].
Odd sums are \[1,9,3,5\] so the answer is 4.

**Example 2:**

**Input:** arr = \[2,4,6\]
**Output:** 0
**Explanation:** All subarrays are \[\[2\],\[2,4\],\[2,4,6\],\[4\],\[4,6\],\[6\]\]
All sub-arrays sum are \[2,6,12,4,10,6\].
All sub-arrays have even sum and the answer is 0.

**Example 3:**

**Input:** arr = \[1,2,3,4,5,6,7\]
**Output:** 16

**Constraints:**

*   `1 <= arr.length <= 105`
*   `1 <= arr[i] <= 100`

## A solution in Java

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

public List<String> stringMatching(String[] words) {
    List<String> result = new ArrayList<>();
    for (String word1 : words) {
        for (String word2 : words) {
            if (!word1.equals(word2) && word2.contains(word1)) {
                result.add(word1);
                break;
            }
        }
    }
    return result;
}
```
The given algorithm is a simple brute-force approach to find substrings. We iterate through each word (word1) in the given list of words, and then for each word1, we iterate through the list of words again (word2) to compare with word1. If word1 is different from word2 and word1 is a substring of word2, we add word1 to the resulting list and break the inner loop to avoid adding duplicates. Finally, we return the list of strings which are a substring of another word in the given list of words.

## A solution in C++

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

std::vector<std::string> stringMatching(std::vector<std::string>& words) {
    std::vector<std::string> result;
    for (const auto& word1 : words) {
        for (const auto& word2 : words) {
            if (word1 != word2 && word2.find(word1) != std::string::npos) {
                result.push_back(word1);
                break;
            }
        }
    }
    return result;
}
```
The given algorithm is a simple brute-force approach to find substrings. We iterate through each word (word1) in the given list of words, and then for each word1, we iterate through the list of words again (word2) to compare with word1. If word1 is different from word2 and word1 is a substring of word2, we add word1 to the resulting list and break the inner loop to avoid adding duplicates. Finally, we return the list of strings which are a substring of another word in the given list of words.

## A solution in Python

```python
def stringMatching(words):
    result = []
    for word1 in words:
        for word2 in words:
            if word1 != word2 and word1 in word2:
                result.append(word1)
                break
    return result
```
The given algorithm is a simple brute-force approach to find substrings. We iterate through each word (word1) in the given list of words, and then for each word1, we iterate through the list of words again (word2) to compare with word1. If word1 is different from word2 and word1 is a substring of word2, we add word1 to the resulting list and break the inner loop to avoid adding duplicates. Finally, we return the list of strings which are a substring of another word in the given list of words.

## A solution in Javascript

```javascript
function stringMatching(words) {
    const result = [];
    for (const word1 of words) {
        for (const word2 of words) {
            if (word1 !== word2 && word2.includes(word1)) {
                result.push(word1);
                break;
            }
        }
    }
    return result;
}
```
The given algorithm is a simple brute-force approach to find substrings. We iterate through each word (word1) in the given list of words, and then for each word1, we iterate through the list of words again (word2) to compare with word1. If word1 is different from word2 and word1 is a substring of word2, we add word1 to the resulting list and break the inner loop to avoid adding duplicates. Finally, we return the list of strings which are a substring of another word in the given list of words.