# Using a Robot to Print the Lexicographically Smallest String

- slug: using-a-robot-to-print-the-lexicographically-smallest-string
- difficulty: Medium

You are given a string `s` and a robot that currently holds an empty string `t`. Apply one of the following operations until `s` and `t` **are both empty**:

*   Remove the **first** character of a string `s` and give it to the robot. The robot will append this character to the string `t`.
*   Remove the **last** character of a string `t` and give it to the robot. The robot will write this character on paper.

Return _the lexicographically smallest string that can be written on the paper._

**Example 1:**

**Input:** s =  "zza "
**Output:**  "azz "
**Explanation:** Let p denote the written string.
Initially p= " ", s= "zza ", t= " ".
Perform first operation three times p= " ", s= " ", t= "zza ".
Perform second operation three times p= "azz ", s= " ", t= " ".

**Example 2:**

**Input:** s =  "bac "
**Output:**  "abc "
**Explanation:** Let p denote the written string.
Perform first operation twice p= " ", s= "c ", t= "ba ".
Perform second operation twice p= "ab ", s= "c ", t= " ".
Perform first operation p= "ab ", s= " ", t= "c ".
Perform second operation p= "abc ", s= " ", t= " ".

**Example 3:**

**Input:** s =  "bdda "
**Output:**  "addb "
**Explanation:** Let p denote the written string.
Initially p= " ", s= "bdda ", t= " ".
Perform first operation four times p= " ", s= " ", t= "bdda ".
Perform second operation four times p= "addb ", s= " ", t= " ".

**Constraints:**

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

## A solution in Java

```java
public String robotSort(String s) {
    StringBuilder sb = new StringBuilder();
    for (char c : s.toCharArray()) {
        while (sb.length() > 0 && sb.charAt(sb.length() - 1) <= c) {
            sb.setLength(sb.length() - 1);
        }
        sb.append(c);
    }
    return sb.toString();
}
```
The algorithm is a simple greedy one. It iterates over the string, and at each step, tries to add the character to the string that the robot is holding (`t`), if and only if it can remove at least one character from the end of `t` that is less than or equal to the current character from the given string. If it's possible to remove a character and keep the string lexicographically smaller, we do so, otherwise, we simply add the current character. This ensures the lexicographically smallest output at each step.

## A solution in C++

```cpp
std::string robotSort(std::string s) {
    std::string t;
    for (char c : s) {
        while (!t.empty() && t.back() <= c) {
            t.pop_back();
        }
        t.push_back(c);
    }
    return t;
}
```
The algorithm is a simple greedy one. It iterates over the string, and at each step, tries to add the character to the string that the robot is holding (`t`), if and only if it can remove at least one character from the end of `t` that is less than or equal to the current character from the given string. If it's possible to remove a character and keep the string lexicographically smaller, we do so, otherwise, we simply add the current character. This ensures the lexicographically smallest output at each step.

## A solution in Python

```python
def robot_sort(s):
    t = []
    for c in s:
        while t and t[-1] <= c:
            t.pop()
        t.append(c)
    return ''.join(t)
```
The algorithm is a simple greedy one. It iterates over the string, and at each step, tries to add the character to the string that the robot is holding (`t`), if and only if it can remove at least one character from the end of `t` that is less than or equal to the current character from the given string. If it's possible to remove a character and keep the string lexicographically smaller, we do so, otherwise, we simply add the current character. This ensures the lexicographically smallest output at each step.

## A solution in Javascript

```javascript
function robotSort(s) {
    let t = "";
    for (const c of s) {
        while (t.length > 0 && t[t.length - 1] <= c) {
            t = t.slice(0, -1);
        }
        t += c;
    }
    return t;
}
```
The algorithm is a simple greedy one. It iterates over the string, and at each step, tries to add the character to the string that the robot is holding (`t`), if and only if it can remove at least one character from the end of `t` that is less than or equal to the current character from the given string. If it's possible to remove a character and keep the string lexicographically smaller, we do so, otherwise, we simply add the current character. This ensures the lexicographically smallest output at each step.


# Paths in Matrix Whose Sum Is Divisible by K

- slug: paths-in-matrix-whose-sum-is-divisible-by-k
- difficulty: Hard

You are given a **0-indexed** `m x n` integer matrix `grid` and an integer `k`. You are currently at position `(0, 0)` and you want to reach position `(m - 1, n - 1)` moving only **down** or **right**.

Return _the number of paths where the sum of the elements on the path is divisible by_ `k`. Since the answer may be very large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** grid = \[\[5,2,4\],\[3,0,5\],\[0,7,2\]\], k = 3
**Output:** 2
**Explanation:** There are two paths where the sum of the elements on the path is divisible by k.
The first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3.
The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3.

**Example 2:**

**Input:** grid = \[\[0,0\]\], k = 5
**Output:** 1
**Explanation:** The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5.

**Example 3:**

**Input:** grid = \[\[7,3,4,9\],\[2,3,6,2\],\[2,3,7,0\]\], k = 1
**Output:** 10
**Explanation:** Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 5 * 104`
*   `1 <= m * n <= 5 * 104`
*   `0 <= grid[i][j] <= 100`
*   `1 <= k <= 50`

## A solution in Java

```java
public int ways(int[][] grid, int m, int n, int i, int j, int k, int sum, int[][][] dp) {
    if (i == m - 1 && j == n - 1) {
        return (sum + grid[i][j]) % k == 0 ? 1 : 0;
    }
    if (dp[i][j][sum] == -1) {
        int ans = 0;
        if (i + 1 < m) ans = (ans + ways(grid, m, n, i + 1, j, k, (sum + grid[i][j]) % k, dp)) % 1000000007;
        if (j + 1 < n) ans = (ans + ways(grid, m, n, i, j + 1, k, (sum + grid[i][j]) % k, dp)) % 1000000007;
        dp[i][j][sum] = ans;
    }
    return dp[i][j][sum];
}

public int waysToReachDivisibleSum(int[][] grid, int k) {
    int m = grid.length, n = grid[0].length;
    int[][][] dp = new int[m][n][k];
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            Arrays.fill(dp[i][j], -1);
        }
    }
    return ways(grid, m, n, 0, 0, k, 0, dp);
}
```
The algorithm uses a depth first search (DFS) approach to find all the possible paths to reach the end of the grid. We use a 3-dimensional memoization array `dp` to store the number of ways to reach the end, where `dp[i][j][sum]` represents the number of paths from the current cell `(i, j)` to the end with a remainder `sum % k` for the elements of the path so far.

The base case is when we have reached the end at cell `(m - 1, n - 1)`. In this case, we check if the sum of the elements on the path is divisible by `k` and return 1 if it is or 0 otherwise.

For each cell, if there is a possible move down, we call the `ways` function recursively for the next row (i + 1) and keep the same column (j), adding the value in the current cell (grid[i][j]) to the sum. Similarly, if there is a possible move right, we call the `ways` function recursively for the next column (j + 1) and keep the same row (i), also adding the value in the current cell to the sum. We then take the sum of the returned values mod 1000000007 to calculate the total number of ways.

The initial call to the ways function starts at cell `(0, 0)` with a sum of 0 and the memoization `dp` initialized with -1.

## A solution in C++

```cpp
int ways(vector<vector<int>>& grid, int m, int n, int i, int j, int k, int sum, vector<vector<vector<int>>>& dp) {
    if (i == m - 1 && j == n - 1) {
        return (sum + grid[i][j]) % k == 0;
    }
    if (dp[i][j][sum] == -1) {
        int ans = 0;
        if (i + 1 < m) ans = (ans + ways(grid, m, n, i + 1, j, k, (sum + grid[i][j]) % k, dp)) % 1000000007;
        if (j + 1 < n) ans = (ans + ways(grid, m, n, i, j + 1, k, (sum + grid[i][j]) % k, dp)) % 1000000007;
        dp[i][j][sum] = ans;
    }
    return dp[i][j][sum];
}

int waysToReachDivisibleSum(vector<vector<int>>& grid, int k) {
    int m = grid.size(), n = grid[0].size();
    vector<vector<vector<int>>> dp(m, vector<vector<int>>(n, vector<int>(k, -1)));
    return ways(grid, m, n, 0, 0, k, 0, dp);
}
```
The algorithm uses a depth first search (DFS) approach to find all the possible paths to reach the end of the grid. We use a 3-dimensional memoization array `dp` to store the number of ways to reach the end, where `dp[i][j][sum]` represents the number of paths from the current cell `(i, j)` to the end with a remainder `sum % k` for the elements of the path so far.

The base case is when we have reached the end at cell `(m - 1, n - 1)`. In this case, we check if the sum of the elements on the path is divisible by `k` and return 1 if it is or 0 otherwise.

For each cell, if there is a possible move down, we call the `ways` function recursively for the next row (i + 1) and keep the same column (j), adding the value in the current cell (grid[i][j]) to the sum. Similarly, if there is a possible move right, we call the `ways` function recursively for the next column (j + 1) and keep the same row (i), also adding the value in the current cell to the sum. We then take the sum of the returned values mod 1000000007 to calculate the total number of ways.

The initial call to the ways function starts at cell `(0, 0)` with a sum of 0 and the memoization `dp` initialized with -1.

## A solution in Python

```python
def ways(grid, m, n, i, j, k, sum, dp):
    if i == m - 1 and j == n - 1:
        return 1 if (sum + grid[i][j]) % k == 0 else 0
    if dp[i][j][sum] == -1:
        ans = 0
        if i + 1 < m:
            ans = (ans + ways(grid, m, n, i + 1, j, k, (sum + grid[i][j]) % k, dp)) % 1000000007
        if j + 1 < n:
            ans = (ans + ways(grid, m, n, i, j + 1, k, (sum + grid[i][j]) % k, dp)) % 1000000007
        dp[i][j][sum] = ans
    return dp[i][j][sum]

def waysToReachDivisibleSum(grid, k):
    m, n = len(grid), len(grid[0])
    dp = [[[-1] * k for _ in range(n)] for _ in range(m)]
    return ways(grid, m, n, 0, 0, k, 0, dp)
```
The algorithm uses a depth first search (DFS) approach to find all the possible paths to reach the end of the grid. We use a 3-dimensional memoization array `dp` to store the number of ways to reach the end, where `dp[i][j][sum]` represents the number of paths from the current cell `(i, j)` to the end with a remainder `sum % k` for the elements of the path so far.

The base case is when we have reached the end at cell `(m - 1, n - 1)`. In this case, we check if the sum of the elements on the path is divisible by `k` and return 1 if it is or 0 otherwise.

For each cell, if there is a possible move down, we call the `ways` function recursively for the next row (i + 1) and keep the same column (j), adding the value in the current cell (grid[i][j]) to the sum. Similarly, if there is a possible move right, we call the `ways` function recursively for the next column (j + 1) and keep the same row (i), also adding the value in the current cell to the sum. We then take the sum of the returned values mod 1000000007 to calculate the total number of ways.

The initial call to the ways function starts at cell `(0, 0)` with a sum of 0 and the memoization `dp` initialized with -1.

## A solution in Javascript

```javascript
function ways(grid, m, n, i, j, k, sum, dp) {
    if (i === m - 1 && j === n - 1) {
        return (sum + grid[i][j]) % k === 0 ? 1 : 0;
    }
    if (dp[i][j][sum] === -1) {
        let ans = 0;
        if (i + 1 < m)
            ans = (ans + ways(grid, m, n, i + 1, j, k, (sum + grid[i][j]) % k, dp)) % 1000000007;
        if (j + 1 < n)
            ans = (ans + ways(grid, m, n, i, j + 1, k, (sum + grid[i][j]) % k, dp)) % 1000000007;
        dp[i][j][sum] = ans;
    }
    return dp[i][j][sum];
}

function waysToReachDivisibleSum(grid, k) {
    const m = grid.length, n = grid[0].length;
    const dp = Array.from({ length: m }, () => Array.from({ length: n }, () => Array(k).fill(-1)));
    return ways(grid, m, n, 0, 0, k, 0, dp);
}
```
The algorithm uses a depth first search (DFS) approach to find all the possible paths to reach the end of the grid. We use a 3-dimensional memoization array `dp` to store the number of ways to reach the end, where `dp[i][j][sum]` represents the number of paths from the current cell `(i, j)` to the end with a remainder `sum % k` for the elements of the path so far.

The base case is when we have reached the end at cell `(m - 1, n - 1)`. In this case, we check if the sum of the elements on the path is divisible by `k` and return 1 if it is or 0 otherwise.

For each cell, if there is a possible move down, we call the `ways` function recursively for the next row (i + 1) and keep the same column (j), adding the value in the current cell (grid[i][j]) to the sum. Similarly, if there is a possible move right, we call the `ways` function recursively for the next column (j + 1) and keep the same row (i), also adding the value in the current cell to the sum. We then take the sum of the returned values mod 1000000007 to calculate the total number of ways.

The initial call to the ways function starts at cell `(0, 0)` with a sum of 0 and the memoization `dp` initialized with -1.


# Minimum Split Into Subarrays With GCD Greater Than One

- slug: minimum-split-into-subarrays-with-gcd-greater-than-one
- difficulty: Medium

You are given an array `nums` consisting of positive integers.

Split the array into **one or more** disjoint subarrays such that:

*   Each element of the array belongs to **exactly one** subarray, and
*   The **GCD** of the elements of each subarray is strictly greater than `1`.

Return _the minimum number of subarrays that can be obtained after the split_.

**Note** that:

*   The **GCD** of a subarray is the largest positive integer that evenly divides all the elements of the subarray.
*   A **subarray** is a contiguous part of the array.

**Example 1:**

**Input:** nums = \[12,6,3,14,8\]
**Output:** 2
**Explanation:** We can split the array into the subarrays: \[12,6,3\] and \[14,8\].
- The GCD of 12, 6 and 3 is 3, which is strictly greater than 1.
- The GCD of 14 and 8 is 2, which is strictly greater than 1.
It can be shown that splitting the array into one subarray will make the GCD = 1.

**Example 2:**

**Input:** nums = \[4,12,6,14\]
**Output:** 1
**Explanation:** We can split the array into only one subarray, which is the whole array.

**Constraints:**

*   `1 <= nums.length <= 2000`
*   `2 <= nums[i] <= 109`

## A solution in Java

```java
public int minArrays(int[] nums) {
    int n = nums.length;
    int totalGcd = nums[0];
    for (int i = 1; i < n; ++i) {
        totalGcd = gcd(totalGcd, nums[i]);
    }
    return (totalGcd == 1) ? 2 : 1;
}

public int gcd(int a, int b) {
    return (b == 0) ? a : gcd(b, a % b);
}
```
The algorithm first finds the total GCD (greatest common divisor) of all the elements in the array. If the total GCD is 1, that means the array can't be split into a single subarray and satisfy the condition of having a GCD greater than 1. In this case, the minimum number of subarrays required is 2. Otherwise, if the total GCD is greater than 1, the entire array can be considered as a single subarray meeting the condition, so the answer is 1. The gcd function is a helper function that computes the GCD of two integers using the Euclidean algorithm.

## A solution in C++

```cpp
#include <vector>

int gcd(int a, int b) {
    return (b == 0) ? a : gcd (b, a % b);
}

int minArrays(std::vector<int>& nums) {
    int n = nums.size();
    int total_gcd = nums[0];
    for (int i = 1; i < n; ++i) {
        total_gcd = gcd(total_gcd, nums[i]);
    }
    return (total_gcd == 1) ? 2 : 1;
}
```
The algorithm first finds the total GCD (greatest common divisor) of all the elements in the array. If the total GCD is 1, that means the array can't be split into a single subarray and satisfy the condition of having a GCD greater than 1. In this case, the minimum number of subarrays required is 2. Otherwise, if the total GCD is greater than 1, the entire array can be considered as a single subarray meeting the condition, so the answer is 1. The gcd function is a helper function that computes the GCD of two integers using the Euclidean algorithm.

## A solution in Python

```python
def min_arrays(nums):
    def gcd(a, b):
        return a if b == 0 else gcd(b, a % b)

    total_gcd = nums[0]
    for num in nums[1:]:
        total_gcd = gcd(total_gcd, num)

    return 2 if total_gcd == 1 else 1
```
The algorithm first finds the total GCD (greatest common divisor) of all the elements in the array. If the total GCD is 1, that means the array can't be split into a single subarray and satisfy the condition of having a GCD greater than 1. In this case, the minimum number of subarrays required is 2. Otherwise, if the total GCD is greater than 1, the entire array can be considered as a single subarray meeting the condition, so the answer is 1. The gcd function is a helper function that computes the GCD of two integers using the Euclidean algorithm.

## A solution in Javascript

```javascript
function gcd(a, b) {
    return (b === 0) ? a : gcd(b, a % b);
}

function minArrays(nums) {
    let n = nums.length;
    let totalGcd = nums[0];
    for (let i = 1; i < n; ++i) {
        totalGcd = gcd(totalGcd, nums[i]);
    }
    return (totalGcd === 1) ? 2 : 1;
}
```
The algorithm first finds the total GCD (greatest common divisor) of all the elements in the array. If the total GCD is 1, that means the array can't be split into a single subarray and satisfy the condition of having a GCD greater than 1. In this case, the minimum number of subarrays required is 2. Otherwise, if the total GCD is greater than 1, the entire array can be considered as a single subarray meeting the condition, so the answer is 1. The gcd function is a helper function that computes the GCD of two integers using the Euclidean algorithm.


# Number of Valid Clock Times

- slug: number-of-valid-clock-times
- difficulty: Easy

You are given a string of length `5` called `time`, representing the current time on a digital clock in the format `"hh:mm "`. The **earliest** possible time is `"00:00 "` and the **latest** possible time is `"23:59 "`.

In the string `time`, the digits represented by the `?` symbol are **unknown**, and must be **replaced** with a digit from `0` to `9`.

Return _an integer_ `answer`_, the number of valid clock times that can be created by replacing every_ `?` _with a digit from_ `0` _to_ `9`.

**Example 1:**

**Input:** time =  "?5:00 "
**Output:** 2
**Explanation:** We can replace the ? with either a 0 or 1, producing  "05:00 " or  "15:00 ". Note that we cannot replace it with a 2, since the time  "25:00 " is invalid. In total, we have two choices.

**Example 2:**

**Input:** time =  "0?:0? "
**Output:** 100
**Explanation:** Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices.

**Example 3:**

**Input:** time =  "??:?? "
**Output:** 1440
**Explanation:** There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 \* 60 = 1440 choices.

**Constraints:**

*   `time` is a valid string of length `5` in the format `"hh:mm "`.
*   `"00 " <= hh <= "23 "`
*   `"00 " <= mm <= "59 "`
*   Some of the digits might be replaced with `'?'` and need to be replaced with digits from `0` to `9`.

## A solution in Java

```java
public int countValidTimes(String time) {
    int count = 1;
    if(time.charAt(0) == '?') {
        count *= (time.charAt(1) == '?' || time.charAt(1) < '4') ? 3 : 2;
    }
    if(time.charAt(1) == '?') {
        count *= (time.charAt(0) == '2') ? 4 : 10;
    }
    if(time.charAt(3) == '?') {
        count *= 6;
    }
    if(time.charAt(4) == '?') {
        count *= 10;
    }
    return count;
}
```
1. If the first character is '?', check if the second character is also '?' or less than '4', in that case the valid possibilities for the first character are '0', '1' or '2', so we multiply our count by 3. If the second character is greater than or equal to '4', then the valid possibilities for the first character are only '0' or '1', so we multiply our count by 2.
2. If the second character is '?', check if the first character is '2', in that case, the valid possibilities for the second character are '0', '1', '2' and '3', so we multiply our count by 4. If the first character is not '2', then the valid possibilities for the second character are 0 to 9, so we multiply our count by 10.
3. If the third character is '?', the valid possibilities are '0' to '5', so we multiply our count by 6.
4. If the fourth character is '?', the valid possibilities are 0 to 9, so we multiply our count by 10.

At the end, return the `count` value which represents the number of valid clock times that can be created by replacing '?' with a digit from 0 to 9.

## A solution in C++

```cpp
int countValidTimes(std::string time) {
    int count = 1;
    if(time[0] == '?') {
        count *= (time[1] == '?' || time[1] < '4') ? 3 : 2;
    }
    if(time[1] == '?') {
        count *= (time[0] == '2') ? 4 : 10;
    }
    if(time[3] == '?') {
        count *= 6;
    }
    if(time[4] == '?') {
        count *= 10;
    }
    return count;
}
```
1. If the first character is '?', check if the second character is also '?' or less than '4', in that case the valid possibilities for the first character are '0', '1' or '2', so we multiply our count by 3. If the second character is greater than or equal to '4', then the valid possibilities for the first character are only '0' or '1', so we multiply our count by 2.
2. If the second character is '?', check if the first character is '2', in that case, the valid possibilities for the second character are '0', '1', '2' and '3', so we multiply our count by 4. If the first character is not '2', then the valid possibilities for the second character are 0 to 9, so we multiply our count by 10.
3. If the third character is '?', the valid possibilities are '0' to '5', so we multiply our count by 6.
4. If the fourth character is '?', the valid possibilities are 0 to 9, so we multiply our count by 10.

At the end, return the `count` value which represents the number of valid clock times that can be created by replacing '?' with a digit from 0 to 9.

## A solution in Python

```python
def count_valid_times(time: str) -> int:
    count = 1
    if time[0] == '?':
        count *= 3 if time[1] == '?' or time[1] < '4' else 2
    if time[1] == '?':
        count *= 4 if time[0] == '2' else 10
    if time[3] == '?':
        count *= 6
    if time[4] == '?':
        count *= 10
    return count
```
1. If the first character is '?', check if the second character is also '?' or less than '4', in that case the valid possibilities for the first character are '0', '1' or '2', so we multiply our count by 3. If the second character is greater than or equal to '4', then the valid possibilities for the first character are only '0' or '1', so we multiply our count by 2.
2. If the second character is '?', check if the first character is '2', in that case, the valid possibilities for the second character are '0', '1', '2' and '3', so we multiply our count by 4. If the first character is not '2', then the valid possibilities for the second character are 0 to 9, so we multiply our count by 10.
3. If the third character is '?', the valid possibilities are '0' to '5', so we multiply our count by 6.
4. If the fourth character is '?', the valid possibilities are 0 to 9, so we multiply our count by 10.

At the end, return the `count` value which represents the number of valid clock times that can be created by replacing '?' with a digit from 0 to 9.

## A solution in Javascript

```javascript
function countValidTimes(time) {
    let count = 1;
    if(time[0] === '?') {
        count *= (time[1] === '?' || time[1] < '4') ? 3 : 2;
    }
    if(time[1] === '?') {
        count *= (time[0] === '2') ? 4 : 10;
    }
    if(time[3] === '?') {
        count *= 6;
    }
    if(time[4] === '?') {
        count *= 10;
    }
    return count;
}
```
1. If the first character is '?', check if the second character is also '?' or less than '4', in that case the valid possibilities for the first character are '0', '1' or '2', so we multiply our count by 3. If the second character is greater than or equal to '4', then the valid possibilities for the first character are only '0' or '1', so we multiply our count by 2.
2. If the second character is '?', check if the first character is '2', in that case, the valid possibilities for the second character are '0', '1', '2' and '3', so we multiply our count by 4. If the first character is not '2', then the valid possibilities for the second character are 0 to 9, so we multiply our count by 10.
3. If the third character is '?', the valid possibilities are '0' to '5', so we multiply our count by 6.
4. If the fourth character is '?', the valid possibilities are 0 to 9, so we multiply our count by 10.

At the end, return the `count` value which represents the number of valid clock times that can be created by replacing '?' with a digit from 0 to 9.


# Range Product Queries of Powers

- slug: range-product-queries-of-powers
- difficulty: Medium

Given a positive integer `n`, there exists a **0-indexed** array called `powers`, composed of the **minimum** number of powers of `2` that sum to `n`. The array is sorted in **non-decreasing** order, and there is **only one** way to form the array.

You are also given a **0-indexed** 2D integer array `queries`, where `queries[i] = [lefti, righti]`. Each `queries[i]` represents a query where you have to find the product of all `powers[j]` with `lefti <= j <= righti`.

Return _an array_ `answers`_, equal in length to_ `queries`_, where_ `answers[i]` _is the answer to the_ `ith` _query_. Since the answer to the `ith` query may be too large, each `answers[i]` should be returned **modulo** `109 + 7`.

**Example 1:**

**Input:** n = 15, queries = \[\[0,1\],\[2,2\],\[0,3\]\]
**Output:** \[2,4,64\]
**Explanation:**
For n = 15, powers = \[1,2,4,8\]. It can be shown that powers cannot be a smaller size.
Answer to 1st query: powers\[0\] \* powers\[1\] = 1 \* 2 = 2.
Answer to 2nd query: powers\[2\] = 4.
Answer to 3rd query: powers\[0\] \* powers\[1\] \* powers\[2\] \* powers\[3\] = 1 \* 2 \* 4 \* 8 = 64.
Each answer modulo 109 + 7 yields the same answer, so \[2,4,64\] is returned.

**Example 2:**

**Input:** n = 2, queries = \[\[0,0\]\]
**Output:** \[2\]
**Explanation:**
For n = 2, powers = \[2\].
The answer to the only query is powers\[0\] = 2. The answer modulo 109 + 7 is the same, so \[2\] is returned.

**Constraints:**

*   `1 <= n <= 109`
*   `1 <= queries.length <= 105`
*   `0 <= starti <= endi < powers.length`

## A solution in Java

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

public class Main {
    public static final int mod = 1000000007;

    public static List<Integer> getPowers(int n) {
        List<Integer> powers = new ArrayList<>();
        while (n > 0) {
            powers.add(n & (-n));
            n -= n & (-n);
        }
        return powers;
    }

    public static List<Integer> productOfPowers(int n, int[][] queries) {
        List<Integer> powers = getPowers(n);
        List<Integer> answers = new ArrayList<>();

        for(int[] query : queries) {
            long product = 1;
            for(int i = query[0]; i <= query[1]; i++) {
                product = (product * powers.get(i)) % mod;
            }
            answers.add((int) product);
        }

        return answers;
    }
}
```
1. Create the `getPowers` function, which takes a positive integer `n` as input and returns an array that contains the minimum number of powers of `2` that sum to `n`.
    - Loop while `n` is greater than 0
      - Calculate the least significant bit of `n` by performing bitwise AND operation `n & (-n)`, then push this bit into powers array.
      - Update `n` as `n - n & (-n)`.
2. Create `productOfPowers` function, which takes an integer `n` and a 2D array `queries` as input and returns the array of answers as per the problem.
    - Calculate the powers array using getPowers function.
    - Loop through each query in the `queries` array.
      - Initialize a `product` variable to store the aggregate product of the powers in the range of query.
      - Loop through the start and end index (inclusive) of the query, multiply the corresponding powers to the `product` variable and take modulo 10^9 + 7.
      - Push the `product` variable into the answers array.
3. Return the answers array.

## A solution in C++

```cpp
#include <vector>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;

vector<int> getPowers(int n) {
    vector<int> powers;
    while (n > 0) {
        powers.push_back(n & (-n));
        n -= n & (-n);
    }
    return powers;
}

vector<int> productOfPowers(int n, vector<vector<int>>& queries) {
    vector<int> powers = getPowers(n);
    vector<int> answers;

    for(auto query : queries) {
        ll product = 1;
        for(int i = query[0]; i <= query[1]; i++) {
            product = (product * powers[i]) % mod;
        }
        answers.push_back(product);
    }

    return answers;
}
```
1. Create the `getPowers` function, which takes a positive integer `n` as input and returns an array that contains the minimum number of powers of `2` that sum to `n`.
    - Loop while `n` is greater than 0
      - Calculate the least significant bit of `n` by performing bitwise AND operation `n & (-n)`, then push this bit into powers array.
      - Update `n` as `n - n & (-n)`.
2. Create `productOfPowers` function, which takes an integer `n` and a 2D array `queries` as input and returns the array of answers as per the problem.
    - Calculate the powers array using getPowers function.
    - Loop through each query in the `queries` array.
      - Initialize a `product` variable to store the aggregate product of the powers in the range of query.
      - Loop through the start and end index (inclusive) of the query, multiply the corresponding powers to the `product` variable and take modulo 10^9 + 7.
      - Push the `product` variable into the answers array.
3. Return the answers array.

## A solution in Python

```python
def getPowers(n):
    powers = []
    while n > 0:
        powers.append(n & (-n))
        n -= n & (-n)
    return powers

def productOfPowers(n, queries):
    powers = getPowers(n)
    answers = []

    mod = 10**9 + 7

    for query in queries:
        product = 1
        for i in range(query[0], query[1] + 1):
            product = (product * powers[i]) % mod
        answers.append(product)

    return answers
```
1. Create the `getPowers` function, which takes a positive integer `n` as input and returns an array that contains the minimum number of powers of `2` that sum to `n`.
    - Loop while `n` is greater than 0
      - Calculate the least significant bit of `n` by performing bitwise AND operation `n & (-n)`, then push this bit into powers array.
      - Update `n` as `n - n & (-n)`.
2. Create `productOfPowers` function, which takes an integer `n` and a 2D array `queries` as input and returns the array of answers as per the problem.
    - Calculate the powers array using getPowers function.
    - Loop through each query in the `queries` array.
      - Initialize a `product` variable to store the aggregate product of the powers in the range of query.
      - Loop through the start and end index (inclusive) of the query, multiply the corresponding powers to the `product` variable and take modulo 10^9 + 7.
      - Push the `product` variable into the answers array.
3. Return the answers array.

## A solution in Javascript

```javascript
function getPowers(n) {
    let powers = [];
    while (n > 0) {
        powers.push(n & (-n));
        n -= n & (-n);
    }
    return powers;
}

function productOfPowers(n, queries) {
    let powers = getPowers(n);
    let answers = [];

    let mod = 1e9 + 7;

    for(let query of queries) {
        let product = 1;
        for(let i = query[0]; i <= query[1]; i++) {
            product = (product * powers[i]) % mod;
        }
        answers.push(product);
    }

    return answers;
}
```
1. Create the `getPowers` function, which takes a positive integer `n` as input and returns an array that contains the minimum number of powers of `2` that sum to `n`.
    - Loop while `n` is greater than 0
      - Calculate the least significant bit of `n` by performing bitwise AND operation `n & (-n)`, then push this bit into powers array.
      - Update `n` as `n - n & (-n)`.
2. Create `productOfPowers` function, which takes an integer `n` and a 2D array `queries` as input and returns the array of answers as per the problem.
    - Calculate the powers array using getPowers function.
    - Loop through each query in the `queries` array.
      - Initialize a `product` variable to store the aggregate product of the powers in the range of query.
      - Loop through the start and end index (inclusive) of the query, multiply the corresponding powers to the `product` variable and take modulo 10^9 + 7.
      - Push the `product` variable into the answers array.
3. Return the answers array.


# Minimize Maximum of Array

- slug: minimize-maximum-of-array
- difficulty: Medium

You are given a **0-indexed** array `nums` comprising of `n` non-negative integers.

In one operation, you must:

*   Choose an integer `i` such that `1 <= i < n` and `nums[i] > 0`.
*   Decrease `nums[i]` by 1.
*   Increase `nums[i - 1]` by 1.

Return _the **minimum** possible value of the **maximum** integer of_ `nums` _after performing **any** number of operations_.

**Example 1:**

**Input:** nums = \[3,7,1,6\]
**Output:** 5
**Explanation:**
One set of optimal operations is as follows:
1. Choose i = 1, and nums becomes \[4,6,1,6\].
2. Choose i = 3, and nums becomes \[4,6,2,5\].
3. Choose i = 1, and nums becomes \[5,5,2,5\].
The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
Therefore, we return 5.

**Example 2:**

**Input:** nums = \[10,1\]
**Output:** 10
**Explanation:**
It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.

**Constraints:**

*   `n == nums.length`
*   `2 <= n <= 105`
*   `0 <= nums[i] <= 109`

## A solution in Java

```java
public int findMinMaximumValue(int[] nums) {
    int result = nums[0], sum = nums[0];
    for (int i = 1; i < nums.length; i++) {
        sum += nums[i];
        result = Math.max(result, (sum + i) / (i + 1));
    }
    return result;
}
```
The algorithm iterates through the array and maintains a running sum of the elements `sum`, and the maximum value found so far `result`. For each `i`, the maximum value for any prefix array ending at `i` is calculated by taking the ceiling of the division of the running sum plus `i` by `i+1`, which represents distributing the sum among the elements up to `i+1`. This maximum value is then compared with the current `result`, and the larger one is kept. The loop ends after iterating through the whole array.

Finally, the algorithm returns the calculated minimum possible maximum value `result`.

## A solution in C++

```cpp
int findMinMaximumValue(vector<int>& nums) {
    int result = nums[0], sum = nums[0];
    for (int i = 1; i < nums.size(); i++) {
        sum += nums[i];
        result = max(result, (sum + i) / (i + 1));
    }
    return result;
}
```
The algorithm iterates through the array and maintains a running sum of the elements `sum`, and the maximum value found so far `result`. For each `i`, the maximum value for any prefix array ending at `i` is calculated by taking the ceiling of the division of the running sum plus `i` by `i+1`, which represents distributing the sum among the elements up to `i+1`. This maximum value is then compared with the current `result`, and the larger one is kept. The loop ends after iterating through the whole array.

Finally, the algorithm returns the calculated minimum possible maximum value `result`.

## A solution in Python

```python
def find_min_maximum_value(nums):
    result = nums[0]
    total_sum = nums[0]
    for i in range(1, len(nums)):
        total_sum += nums[i]
        result = max(result, (total_sum + i) // (i + 1))
    return result
```
The algorithm iterates through the array and maintains a running sum of the elements `sum`, and the maximum value found so far `result`. For each `i`, the maximum value for any prefix array ending at `i` is calculated by taking the ceiling of the division of the running sum plus `i` by `i+1`, which represents distributing the sum among the elements up to `i+1`. This maximum value is then compared with the current `result`, and the larger one is kept. The loop ends after iterating through the whole array.

Finally, the algorithm returns the calculated minimum possible maximum value `result`.

## A solution in Javascript

```javascript
function findMinMaximumValue(nums) {
    let result = nums[0], sum = nums[0];
    for (let i = 1; i < nums.length; i++) {
        sum += nums[i];
        result = Math.max(result, Math.floor((sum + i) / (i + 1)));
    }
    return result;
}
```
The algorithm iterates through the array and maintains a running sum of the elements `sum`, and the maximum value found so far `result`. For each `i`, the maximum value for any prefix array ending at `i` is calculated by taking the ceiling of the division of the running sum plus `i` by `i+1`, which represents distributing the sum among the elements up to `i+1`. This maximum value is then compared with the current `result`, and the larger one is kept. The loop ends after iterating through the whole array.

Finally, the algorithm returns the calculated minimum possible maximum value `result`.


# Create Components With Same Value

- slug: create-components-with-same-value
- difficulty: Hard

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

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

You are allowed to **delete** some edges, splitting the tree into multiple connected components. Let the **value** of a component be the sum of **all** `nums[i]` for which node `i` is in the component.

Return _the **maximum** number of edges you can delete, such that every connected component in the tree has the same value._

**Example 1:**

**Input:** nums = \[6,2,2,2,6\], edges = \[\[0,1\],\[1,2\],\[1,3\],\[3,4\]\]
**Output:** 2
**Explanation:** The above figure shows how we can delete the edges \[0,1\] and \[3,4\]. The created components are nodes \[0\], \[1,2,3\] and \[4\]. The sum of the values in each component equals 6. It can be proven that no better deletion exists, so the answer is 2.

**Example 2:**

**Input:** nums = \[2\], edges = \[\]
**Output:** 0
**Explanation:** There are no edges to be deleted.

**Constraints:**

*   `1 <= n <= 2 * 104`
*   `nums.length == n`
*   `1 <= nums[i] <= 50`
*   `edges.length == n - 1`
*   `edges[i].length == 2`
*   `0 <= edges[i][0], edges[i][1] <= n - 1`
*   `edges` represents a valid tree.

## A solution in Java

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

public int dfs(int node, int parent, int[] nums, List<List<Integer>> graph, int total, int[] result) {
    int sum = nums[node];
    for (int neighbor : graph.get(node)) {
        if (neighbor != parent) {
            sum += dfs(neighbor, node, nums, graph, total, result);
        }
    }
    if (sum == total / 2) {
        result[0]++;
        return 0;
    }
    return sum;
}

public int delete_edges_to_balance_tree(int[] nums, int[][] edges) {
    int n = nums.length;
    List<List<Integer>> graph = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        graph.add(new ArrayList<>());
    }
    for (int[] e : edges) {
        graph.get(e[0]).add(e[1]);
        graph.get(e[1]).add(e[0]);
    }

    int total = 0;
    for (int num : nums) {
        total += num;
    }
    if (total % 2 != 0) {
        return 0;  // It is impossible to split the tree fairly.
    }

    int[] result = {0};
    dfs(0, -1, nums, graph, total, result);
    return result[0] - 1;
}
```
The algorithm includes the following steps:

1. Build a graph representing the tree, where each node has an array of its adjacent nodes.
2. Calculate the total sum of the values in `nums`.
3. If the total sum is not divisible by 2, return 0 since it is impossible to divide the tree into components with the same value.
4. Perform a Depth-First Search (DFS) from node 0, traversing through the tree and calculating the subtree sums while keeping track of how many subtree sums we have seen that are half of the total sum.
5. Return the number of subtree sums that are half of the total sum minus 1, since we have to remove one additional component (the whole tree).

The time complexity of the algorithm is O(n), as we traverse each node in the tree once during the DFS.

## A solution in C++

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

int dfs(int node, int parent, vector<int>& nums, vector<vector<int>>& graph, int total, int& result) {
    int sum = nums[node];
    for (int neighbor : graph[node]) {
        if (neighbor != parent) {
            sum += dfs(neighbor, node, nums, graph, total, result);
        }
    }
    if (sum == total / 2) {
        result++;
        return 0;
    }
    return sum;
}

int delete_edges_to_balance_tree(vector<int>& nums, vector<vector<int>>& edges) {
    int n = nums.size();
    vector<vector<int>> graph(n);
    for (auto& e : edges) {
        graph[e[0]].push_back(e[1]);
        graph[e[1]].push_back(e[0]);
    }

    int total = 0;
    for (int num : nums) {
        total += num;
    }
    if (total % 2 != 0) {
        return 0;  // It is impossible to split the tree fairly.
    }

    int result = 0;
    dfs(0, -1, nums, graph, total, result);
    return result - 1;
}
```
The algorithm includes the following steps:

1. Build a graph representing the tree, where each node has an array of its adjacent nodes.
2. Calculate the total sum of the values in `nums`.
3. If the total sum is not divisible by 2, return 0 since it is impossible to divide the tree into components with the same value.
4. Perform a Depth-First Search (DFS) from node 0, traversing through the tree and calculating the subtree sums while keeping track of how many subtree sums we have seen that are half of the total sum.
5. Return the number of subtree sums that are half of the total sum minus 1, since we have to remove one additional component (the whole tree).

The time complexity of the algorithm is O(n), as we traverse each node in the tree once during the DFS.

## A solution in Python

```python
from collections import defaultdict

def dfs(node, parent, nums, graph, total, result):
    total_sum = nums[node]
    for neighbor in graph[node]:
        if neighbor != parent:
            total_sum += dfs(neighbor, node, nums, graph, total, result)
    if total_sum == total // 2:
        result.append(1)
        return 0
    return total_sum

def delete_edges_to_balance_tree(nums, edges):
    n = len(nums)
    graph = defaultdict(list)
    for e in edges:
        graph[e[0]].append(e[1])
        graph[e[1]].append(e[0])

    total = sum(nums)
    if total % 2 != 0:
        return 0  # It is impossible to split the tree fairly.

    result = []
    dfs(0, -1, nums, graph, total, result)
    return len(result) - 1
```
The algorithm includes the following steps:

1. Build a graph representing the tree, where each node has an array of its adjacent nodes.
2. Calculate the total sum of the values in `nums`.
3. If the total sum is not divisible by 2, return 0 since it is impossible to divide the tree into components with the same value.
4. Perform a Depth-First Search (DFS) from node 0, traversing through the tree and calculating the subtree sums while keeping track of how many subtree sums we have seen that are half of the total sum.
5. Return the number of subtree sums that are half of the total sum minus 1, since we have to remove one additional component (the whole tree).

The time complexity of the algorithm is O(n), as we traverse each node in the tree once during the DFS.

## A solution in Javascript

```javascript
function dfs(node, parent, nums, graph, total, result) {
    let sum = nums[node];
    for (let neighbor of graph[node]) {
        if (neighbor !== parent) {
            sum += dfs(neighbor, node, nums, graph, total, result);
        }
    }
    if (sum === Math.floor(total / 2)) {
        result.push(1);
        return 0;
    }
    return sum;
}

function delete_edges_to_balance_tree(nums, edges) {
    const n = nums.length;
    const graph = Array.from({ length: n }, () => []);
    for (const [a, b] of edges) {
        graph[a].push(b);
        graph[b].push(a);
    }

    const total = nums.reduce((a, b) => a + b, 0);
    if (total % 2 !== 0)
        return 0; // It is impossible to split the tree fairly.

    const result = [];
    dfs(0, -1, nums, graph, total, result);
    return result.length - 1;
}
```
The algorithm includes the following steps:

1. Build a graph representing the tree, where each node has an array of its adjacent nodes.
2. Calculate the total sum of the values in `nums`.
3. If the total sum is not divisible by 2, return 0 since it is impossible to divide the tree into components with the same value.
4. Perform a Depth-First Search (DFS) from node 0, traversing through the tree and calculating the subtree sums while keeping track of how many subtree sums we have seen that are half of the total sum.
5. Return the number of subtree sums that are half of the total sum minus 1, since we have to remove one additional component (the whole tree).

The time complexity of the algorithm is O(n), as we traverse each node in the tree once during the DFS.


# Largest Positive Integer That Exists With Its Negative

- slug: largest-positive-integer-that-exists-with-its-negative
- difficulty: Easy

Given an integer array `nums` that **does not contain** any zeros, find **the largest positive** integer `k` such that `-k` also exists in the array.

Return _the positive integer_ `k`. If there is no such integer, return `-1`.

**Example 1:**

**Input:** nums = \[-1,2,-3,3\]
**Output:** 3
**Explanation:** 3 is the only valid k we can find in the array.

**Example 2:**

**Input:** nums = \[-1,10,6,7,-7,1\]
**Output:** 7
**Explanation:** Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.

**Example 3:**

**Input:** nums = \[-10,8,6,7,-2,-3\]
**Output:** -1
**Explanation:** There is no a single valid k, we return -1.

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `-1000 <= nums[i] <= 1000`
*   `nums[i] != 0`

## A solution in Java

```java
public int findK(int[] nums) {
    Set<Integer> set = new HashSet<>();
    for (int num : nums) {
        set.add(num);
    }
    int k = -1;
    for (int num : nums) {
        if (set.contains(-num)) {
            k = Math.max(k, Math.abs(num));
        }
    }
    return k;
}
```
The algorithm puts all numbers in `nums` into a set `s` and then iterates through the numbers in the array. For each of the numbers, it checks whether `-k` is present in the set. If it is, it updates `k` to be the maximum of the absolute values of `k` and the current element (`num`). The maximum positive integer `k` is returned if it exists, otherwise `-1` is returned. This way, it finds the largest positive `k` such that both `k` and `-k` exist in the input array `nums`.

## A solution in C++

```cpp
int findK(vector<int>& nums) {
    set<int> s(nums.begin(), nums.end());
    int k = -1;
    for (const int& num : nums) {
        if (s.find(-num) != s.end()) {
            k = max(k, abs(num));
        }
    }
    return k;
}
```
The algorithm puts all numbers in `nums` into a set `s` and then iterates through the numbers in the array. For each of the numbers, it checks whether `-k` is present in the set. If it is, it updates `k` to be the maximum of the absolute values of `k` and the current element (`num`). The maximum positive integer `k` is returned if it exists, otherwise `-1` is returned. This way, it finds the largest positive `k` such that both `k` and `-k` exist in the input array `nums`.

## A solution in Python

```python
def find_K(nums):
    s = set(nums)
    k = -1
    for num in nums:
        if -num in s:
            k = max(k, abs(num))
    return k
```
The algorithm puts all numbers in `nums` into a set `s` and then iterates through the numbers in the array. For each of the numbers, it checks whether `-k` is present in the set. If it is, it updates `k` to be the maximum of the absolute values of `k` and the current element (`num`). The maximum positive integer `k` is returned if it exists, otherwise `-1` is returned. This way, it finds the largest positive `k` such that both `k` and `-k` exist in the input array `nums`.

## A solution in Javascript

```javascript
function findK(nums) {
    const s = new Set(nums);
    let k = -1;
    for (const num of nums) {
        if (s.has(-num)) {
            k = Math.max(k, Math.abs(num));
        }
    }
    return k;
}
```
The algorithm puts all numbers in `nums` into a set `s` and then iterates through the numbers in the array. For each of the numbers, it checks whether `-k` is present in the set. If it is, it updates `k` to be the maximum of the absolute values of `k` and the current element (`num`). The maximum positive integer `k` is returned if it exists, otherwise `-1` is returned. This way, it finds the largest positive `k` such that both `k` and `-k` exist in the input array `nums`.


# Count Number of Distinct Integers After Reverse Operations

- slug: count-number-of-distinct-integers-after-reverse-operations
- difficulty: Medium

You are given an array `nums` consisting of **positive** integers.

You have to take each integer in the array, **reverse its digits**, and add it to the end of the array. You should apply this operation to the original integers in `nums`.

Return _the number of **distinct** integers in the final array_.

**Example 1:**

**Input:** nums = \[1,13,10,12,31\]
**Output:** 6
**Explanation:** After including the reverse of each number, the resulting array is \[1,13,10,12,31,1,31,1,21,13\].
The reversed integers that were added to the end of the array are underlined. Note that for the integer 10, after reversing it, it becomes 01 which is just 1.
The number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31).

**Example 2:**

**Input:** nums = \[2,2,2\]
**Output:** 1
**Explanation:** After including the reverse of each number, the resulting array is \[2,2,2,2,2,2\].
The number of distinct integers in this array is 1 (The number 2).

**Constraints:**

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

## A solution in Java

```java
import java.util.HashSet;
import java.util.Set;

public int distinctIntegersAfterReversingAndAdding(int[] nums) {
    Set<Integer> distinct = new HashSet<>();
    for (int num : nums) {
        distinct.add(num);
        int reversed = 0;
        while (num > 0) {
            reversed = reversed * 10 + num % 10;
            num /= 10;
        }
        distinct.add(reversed);
    }
    return distinct.size();
}
```
The algorithm first initializes a set `distinct` to keep track of distinct integers in the final array. It then iterates through each integer `num` in the `nums` array, adds the integer `num` to the `distinct` set, and calculates the reversed integer by reversing the digits of `num`. The reversed integer is also added to the `distinct` set. Finally, the algorithm returns the size of the `distinct` set, which represents the number of distinct integers in the final array. The time complexity is O(n) where n is the size of the `nums` array.

## A solution in C++

```cpp
#include <set>
#include <vector>

int distinctIntegersAfterReversingAndAdding(const std::vector<int>& nums) {
    std::set<int> distinct;
    for (int num : nums) {
        distinct.insert(num);
        int reversed = 0;
        while (num > 0) {
            reversed = reversed * 10 + num % 10;
            num /= 10;
        }
        distinct.insert(reversed);
    }
    return distinct.size();
}
```
The algorithm first initializes a set `distinct` to keep track of distinct integers in the final array. It then iterates through each integer `num` in the `nums` array, adds the integer `num` to the `distinct` set, and calculates the reversed integer by reversing the digits of `num`. The reversed integer is also added to the `distinct` set. Finally, the algorithm returns the size of the `distinct` set, which represents the number of distinct integers in the final array. The time complexity is O(n) where n is the size of the `nums` array.

## A solution in Python

```python
def distinct_integers_after_reversing_and_adding(nums):
    distinct = set(nums)
    for num in nums:
        reversed_num = int(str(num)[::-1])
        distinct.add(reversed_num)
    return len(distinct)
```
The algorithm first initializes a set `distinct` to keep track of distinct integers in the final array. It then iterates through each integer `num` in the `nums` array, adds the integer `num` to the `distinct` set, and calculates the reversed integer by reversing the digits of `num`. The reversed integer is also added to the `distinct` set. Finally, the algorithm returns the size of the `distinct` set, which represents the number of distinct integers in the final array. The time complexity is O(n) where n is the size of the `nums` array.

## A solution in Javascript

```javascript
function distinctIntegersAfterReversingAndAdding(nums) {
    let distinct = new Set(nums);
    nums.forEach(num => {
        let reversed = parseInt(num.toString().split('').reverse().join(''));
        distinct.add(reversed);
    });
    return distinct.size;
}
```
The algorithm first initializes a set `distinct` to keep track of distinct integers in the final array. It then iterates through each integer `num` in the `nums` array, adds the integer `num` to the `distinct` set, and calculates the reversed integer by reversing the digits of `num`. The reversed integer is also added to the `distinct` set. Finally, the algorithm returns the size of the `distinct` set, which represents the number of distinct integers in the final array. The time complexity is O(n) where n is the size of the `nums` array.


# Sum of Number and Its Reverse

- slug: sum-of-number-and-its-reverse
- difficulty: Medium

Given a **non-negative** integer `num`, return `true` _if_ `num` _can be expressed as the sum of any **non-negative** integer and its reverse, or_ `false` _otherwise._

**Example 1:**

**Input:** num = 443
**Output:** true
**Explanation:** 172 + 271 = 443 so we return true.

**Example 2:**

**Input:** num = 63
**Output:** false
**Explanation:** 63 cannot be expressed as the sum of a non-negative integer and its reverse so we return false.

**Example 3:**

**Input:** num = 181
**Output:** true
**Explanation:** 140 + 041 = 181 so we return true. Note that when a number is reversed, there may be leading zeros.

**Constraints:**

*   `0 <= num <= 105`

## A solution in Java

```java
public boolean sumWithReverse(int num) {
    for (int i = 0; i <= num; i++) {
        int reverse = 0, temp = i;
        while (temp != 0) {
            reverse = reverse * 10 + temp % 10;
            temp /= 10;
        }
        if (i + reverse == num) {
            return true;
        }
    }
    return false;
}
```
The algorithm iterates through all non-negative integers from 0 to the input number. For each of these integers, it calculates the reverse by converting the integer to a string, reversing the string, and converting back to an integer. If the sum of the integer and its reverse is equal to the input number, the algorithm returns true. If no such pair is found after the iteration, the algorithm returns false.

## A solution in C++

```cpp
bool sum_with_reverse(int num) {
    for (int i = 0; i <= num; ++i) {
        int reverse = 0, temp = i;
        while (temp != 0) {
            reverse = reverse * 10 + temp % 10;
            temp /= 10;
        }
        if (i + reverse == num) {
            return true;
        }
    }
    return false;
}
```
The algorithm iterates through all non-negative integers from 0 to the input number. For each of these integers, it calculates the reverse by converting the integer to a string, reversing the string, and converting back to an integer. If the sum of the integer and its reverse is equal to the input number, the algorithm returns true. If no such pair is found after the iteration, the algorithm returns false.

## A solution in Python

```python
def sum_with_reverse(num: int) -> bool:
    for i in range(num + 1):
        reverse = int(str(i)[::-1])
        if i + reverse == num:
            return True
    return False
```
The algorithm iterates through all non-negative integers from 0 to the input number. For each of these integers, it calculates the reverse by converting the integer to a string, reversing the string, and converting back to an integer. If the sum of the integer and its reverse is equal to the input number, the algorithm returns true. If no such pair is found after the iteration, the algorithm returns false.

## A solution in Javascript

```javascript
function sumWithReverse(num) {
    for (let i = 0; i <= num; i++) {
        const reverse = parseInt(i.toString().split('').reverse().join(''), 10);
        if (i + reverse === num) {
            return true;
        }
    }
    return false;
}
```
The algorithm iterates through all non-negative integers from 0 to the input number. For each of these integers, it calculates the reverse by converting the integer to a string, reversing the string, and converting back to an integer. If the sum of the integer and its reverse is equal to the input number, the algorithm returns true. If no such pair is found after the iteration, the algorithm returns false.


# Count Subarrays With Fixed Bounds

- slug: count-subarrays-with-fixed-bounds
- difficulty: Hard

You are given an integer array `nums` and two integers `minK` and `maxK`.

A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions:

*   The **minimum** value in the subarray is equal to `minK`.
*   The **maximum** value in the subarray is equal to `maxK`.

Return _the **number** of fixed-bound subarrays_.

A **subarray** is a **contiguous** part of an array.

**Example 1:**

**Input:** nums = \[1,3,5,2,7,5\], minK = 1, maxK = 5
**Output:** 2
**Explanation:** The fixed-bound subarrays are \[1,3,5\] and \[1,3,5,2\].

**Example 2:**

**Input:** nums = \[1,1,1,1\], minK = 1, maxK = 1
**Output:** 10
**Explanation:** Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.

**Constraints:**

*   `2 <= nums.length <= 105`
*   `1 <= nums[i], minK, maxK <= 106`

## A solution in Java

```java
public int fixedBoundSubarrays(int[] nums, int minK, int maxK) {
    int count = 0, min_index = -1, max_index = -1;
    for (int i = 0; i < nums.length; i++) {
        if(nums[i]==minK) min_index=i;
        else if(nums[i]==maxK) max_index=i;
        count += Math.min(min_index, max_index)+1;
    }
    return count;
}
```
We initialize counter, min_index, and max_index variables. Iterate through the given nums array. Inside the loop, we check if the current element of nums equals minK or maxK, and we update min_index or max_index accordingly.

After updating min_index and/or max_index, we calculate the minimum of min_index and max_index, and add it to the counter. We also add 1 to this result, since we need to account for the fixed-bound subarray itself.

At the end of the loop, return the counter representing the number of fixed-bound subarrays.

## A solution in C++

```cpp
int fixedBoundSubarrays(vector<int>& nums, int minK, int maxK) {
    int count = 0, min_index = -1, max_index = -1;
    for (int i = 0; i < nums.size(); i++) {
        if(nums[i]==minK) min_index=i;
        else if(nums[i]==maxK) max_index=i;
        count += min(min_index, max_index)+1;
    }
    return count;
}
```
We initialize counter, min_index, and max_index variables. Iterate through the given nums array. Inside the loop, we check if the current element of nums equals minK or maxK, and we update min_index or max_index accordingly.

After updating min_index and/or max_index, we calculate the minimum of min_index and max_index, and add it to the counter. We also add 1 to this result, since we need to account for the fixed-bound subarray itself.

At the end of the loop, return the counter representing the number of fixed-bound subarrays.

## A solution in Python

```python
def fixed_bound_subarrays(nums, minK, maxK):
    count, min_index, max_index = 0, -1, -1
    for i, num in enumerate(nums):
        if num==minK:
            min_index=i
        elif num==maxK:
            max_index=i

        count += min(min_index, max_index) + 1
    return count
```
We initialize counter, min_index, and max_index variables. Iterate through the given nums array. Inside the loop, we check if the current element of nums equals minK or maxK, and we update min_index or max_index accordingly.

After updating min_index and/or max_index, we calculate the minimum of min_index and max_index, and add it to the counter. We also add 1 to this result, since we need to account for the fixed-bound subarray itself.

At the end of the loop, return the counter representing the number of fixed-bound subarrays.

## A solution in Javascript

```javascript
function fixedBoundSubarrays(nums, minK, maxK) {
    let count = 0, min_index = -1, max_index = -1;
    for (let i = 0; i < nums.length; i++) {
        if(nums[i]===minK) min_index=i;
        else if(nums[i]===maxK) max_index=i;
        count += Math.min(min_index, max_index)+1;
    }
    return count;
}
```
We initialize counter, min_index, and max_index variables. Iterate through the given nums array. Inside the loop, we check if the current element of nums equals minK or maxK, and we update min_index or max_index accordingly.

After updating min_index and/or max_index, we calculate the minimum of min_index and max_index, and add it to the counter. We also add 1 to this result, since we need to account for the fixed-bound subarray itself.

At the end of the loop, return the counter representing the number of fixed-bound subarrays.


# Number of Nodes With Value One

- slug: number-of-nodes-with-value-one
- difficulty: Medium

There is an **undirected** connected tree with `n` nodes labeled from `1` to `n` and `n - 1` edges. You are given the integer `n`. The parent node of a node with a label `v` is the node with the label `floor (v / 2)`. The root of the tree is the node with the label `1`.

*   For example, if `n = 7`, then the node with the label `3` has the node with the label `floor(3 / 2) = 1` as its parent, and the node with the label `7` has the node with the label `floor(7 / 2) = 3` as its parent.

You are also given an integer array `queries`. Initially, every node has a value `0` on it. For each query `queries[i]`, you should flip all values in the subtree of the node with the label `queries[i]`.

Return _the total number of nodes with the value_ `1` _**after processing all the queries**_.

**Note** that:

*   Flipping the value of a node means that the node with the value `0` becomes `1` and vice versa.
*   `floor(x)` is equivalent to rounding `x` down to the nearest integer.

**Example 1:**

**Input:** n = 5 , queries = \[1,2,5\]
**Output:** 3
**Explanation:** The diagram above shows the tree structure and its status after performing the queries. The blue node represents the value 0, and the red node represents the value 1.
After processing the queries, there are three red nodes (nodes with value 1): 1, 3, and 5.

**Example 2:**

**Input:** n = 3, queries = \[2,3,3\]
**Output:** 1
**Explanation:** The diagram above shows the tree structure and its status after performing the queries. The blue node represents the value 0, and the red node represents the value 1.
After processing the queries, there are one red node (node with value 1): 2.

**Constraints:**

*   `1 <= n <= 105`
*   `1 <= queries.length <= 105`
*   `1 <= queries[i] <= n`

## A solution in Java

```java
import java.util.HashMap;
import java.util.Map;
import java.util.List;

public int flipTrees(int n, List<Integer> queries) {
    Map<Integer, Boolean> flippedNodes = new HashMap<>();
    for (int query : queries) {
        flippedNodes.put(query, !flippedNodes.getOrDefault(query, false));
        while (query > 1) {
            query /= 2;
            flippedNodes.put(query, !flippedNodes.getOrDefault(query, false));
        }
    }

    int count = 0;
    for (Map.Entry<Integer, Boolean> node : flippedNodes.entrySet()) {
        if (node.getValue()) {
            count++;
        }
    }
    return count;
}
```
This algorithm uses a hash map to store the nodes that have been flipped. For each query, it toggles the flipped state of the current node and all its parent nodes up to the root (node `1`). After going through all the queries, it counts the number of nodes which are flipped (have a value of `1`) in the hash map.

Since we only store the flipped nodes in the hash map, and not all the nodes, this algorithm has a space complexity lower than O(n). The time complexity is O(queries.length * log(n)), as each query corresponds to a path of length at most log(n) in the tree.

## A solution in C++

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

int flipTrees(int n, std::vector<int>& queries) {
    std::unordered_map<int, bool> flipped_nodes;
    for (int query : queries) {
        flipped_nodes[query] = !flipped_nodes[query];
        while (query > 1) {
            query /= 2;
            flipped_nodes[query] = !flipped_nodes[query];
        }
    }

    int count = 0;
    for (const auto& node : flipped_nodes) {
        if (node.second) {
            count++;
        }
    }
    return count;
}
```
This algorithm uses a hash map to store the nodes that have been flipped. For each query, it toggles the flipped state of the current node and all its parent nodes up to the root (node `1`). After going through all the queries, it counts the number of nodes which are flipped (have a value of `1`) in the hash map.

Since we only store the flipped nodes in the hash map, and not all the nodes, this algorithm has a space complexity lower than O(n). The time complexity is O(queries.length * log(n)), as each query corresponds to a path of length at most log(n) in the tree.

## A solution in Python

```python
def flip_trees(n, queries):
    flipped_nodes = {}
    for query in queries:
        flipped_nodes[query] = not flipped_nodes.get(query, False)
        while query > 1:
            query //= 2
            flipped_nodes[query] = not flipped_nodes.get(query, False)

    count = 0
    for value in flipped_nodes.values():
        if value:
            count += 1

    return count
```
This algorithm uses a hash map to store the nodes that have been flipped. For each query, it toggles the flipped state of the current node and all its parent nodes up to the root (node `1`). After going through all the queries, it counts the number of nodes which are flipped (have a value of `1`) in the hash map.

Since we only store the flipped nodes in the hash map, and not all the nodes, this algorithm has a space complexity lower than O(n). The time complexity is O(queries.length * log(n)), as each query corresponds to a path of length at most log(n) in the tree.

## A solution in Javascript

```javascript
function flipTrees(n, queries) {
    const flippedNodes = new Map();

    queries.forEach(query => {
        flippedNodes.set(query, !flippedNodes.get(query));
        while (query > 1) {
            query = Math.floor(query / 2);
            flippedNodes.set(query, !flippedNodes.get(query));
        }
    });

    let count = 0;
    flippedNodes.forEach(value => {
        if (value) {
            count++;
        }
    });

    return count;
}
```
This algorithm uses a hash map to store the nodes that have been flipped. For each query, it toggles the flipped state of the current node and all its parent nodes up to the root (node `1`). After going through all the queries, it counts the number of nodes which are flipped (have a value of `1`) in the hash map.

Since we only store the flipped nodes in the hash map, and not all the nodes, this algorithm has a space complexity lower than O(n). The time complexity is O(queries.length * log(n)), as each query corresponds to a path of length at most log(n) in the tree.


# Determine if Two Events Have Conflict

- slug: determine-if-two-events-have-conflict
- difficulty: Easy

You are given two arrays of strings that represent two inclusive events that happened **on the same day**, `event1` and `event2`, where:

*   `event1 = [startTime1, endTime1]` and
*   `event2 = [startTime2, endTime2]`.

Event times are valid 24 hours format in the form of `HH:MM`.

A **conflict** happens when two events have some non-empty intersection (i.e., some moment is common to both events).

Return `true` _if there is a conflict between two events. Otherwise, return_ `false`.

**Example 1:**

**Input:** event1 = \[ "01:15 ", "02:00 "\], event2 = \[ "02:00 ", "03:00 "\]
**Output:** true
**Explanation:** The two events intersect at time 2:00.

**Example 2:**

**Input:** event1 = \[ "01:00 ", "02:00 "\], event2 = \[ "01:20 ", "03:00 "\]
**Output:** true
**Explanation:** The two events intersect starting from 01:20 to 02:00.

**Example 3:**

**Input:** event1 = \[ "10:00 ", "11:00 "\], event2 = \[ "14:00 ", "15:00 "\]
**Output:** false
**Explanation:** The two events do not intersect.

**Constraints:**

*   `evnet1.length == event2.length == 2.`
*   `event1[i].length == event2[i].length == 5`
*   `startTime1 <= endTime1`
*   `startTime2 <= endTime2`
*   All the event times follow the `HH:MM` format.

## A solution in Java

```java
public boolean hasEventConflict(String start1, String end1, String start2, String end2) {
    int startHour1 = Integer.parseInt(start1.substring(0, 2));
    int startMin1 = Integer.parseInt(start1.substring(3, 5));
    int startHour2 = Integer.parseInt(start2.substring(0, 2));
    int startMin2 = Integer.parseInt(start2.substring(3, 5));

    int endHour1 = Integer.parseInt(end1.substring(0, 2));
    int endMin1 = Integer.parseInt(end1.substring(3, 5));
    int endHour2 = Integer.parseInt(end2.substring(0, 2));
    int endMin2 = Integer.parseInt(end2.substring(3, 5));

    int totalMin1Start = startHour1 * 60 + startMin1;
    int totalMin1End = endHour1 * 60 + endMin1;
    int totalMin2Start = startHour2 * 60 + startMin2;
    int totalMin2End = endHour2 * 60 + endMin2;

    return !(totalMin1End <= totalMin2Start || totalMin1Start >= totalMin2End);
}
```
The algorithm first parses the input strings and separates the hour and minute parts of each event. Then, it converts the event times to the total minutes from 00:00 to account for easier comparisons. Finally, it checks if the two events have any intersection by comparing the start and end time of each event in minutes. If there's a conflict, return true; otherwise, return false.

## A solution in C++

```cpp
#include <string>

bool hasEventConflict(const std::string& start1, const std::string& end1,
                      const std::string& start2, const std::string& end2) {
    int startHour1 = stoi(start1.substr(0, 2));
    int startMin1 = stoi(start1.substr(3, 2));
    int startHour2 = stoi(start2.substr(0, 2));
    int startMin2 = stoi(start2.substr(3, 2));

    int endHour1 = stoi(end1.substr(0, 2));
    int endMin1 = stoi(end1.substr(3, 2));
    int endHour2 = stoi(end2.substr(0, 2));
    int endMin2 = stoi(end2.substr(3, 2));

    int totalMin1Start = startHour1*60 + startMin1;
    int totalMin1End = endHour1*60 + endMin1;
    int totalMin2Start = startHour2*60 + startMin2;
    int totalMin2End = endHour2*60 + endMin2;

    return !(totalMin1End <= totalMin2Start || totalMin1Start >= totalMin2End);
}
```
The algorithm first parses the input strings and separates the hour and minute parts of each event. Then, it converts the event times to the total minutes from 00:00 to account for easier comparisons. Finally, it checks if the two events have any intersection by comparing the start and end time of each event in minutes. If there's a conflict, return true; otherwise, return false.

## A solution in Python

```python
def has_event_conflict(start1: str, end1: str, start2: str, end2: str) -> bool:
    start_hour1, start_min1 = map(int, start1.split(":"))
    start_hour2, start_min2 = map(int, start2.split(":"))
    end_hour1, end_min1 = map(int, end1.split(":"))
    end_hour2, end_min2 = map(int, end2.split(":"))

    total_min1_start = start_hour1 * 60 + start_min1
    total_min1_end = end_hour1 * 60 + end_min1
    total_min2_start = start_hour2 * 60 + start_min2
    total_min2_end = end_hour2 * 60 + end_min2

    return not (total_min1_end <= total_min2_start or total_min1_start >= total_min2_end)
```
The algorithm first parses the input strings and separates the hour and minute parts of each event. Then, it converts the event times to the total minutes from 00:00 to account for easier comparisons. Finally, it checks if the two events have any intersection by comparing the start and end time of each event in minutes. If there's a conflict, return true; otherwise, return false.

## A solution in Javascript

```javascript
function hasEventConflict(start1, end1, start2, end2) {
    let startHour1 = parseInt(start1.slice(0, 2));
    let startMin1 = parseInt(start1.slice(3, 5));
    let startHour2 = parseInt(start2.slice(0, 2));
    let startMin2 = parseInt(start2.slice(3, 5));

    let endHour1 = parseInt(end1.slice(0, 2));
    let endMin1 = parseInt(end1.slice(3, 5));
    let endHour2 = parseInt(end2.slice(0, 2));
    let endMin2 = parseInt(end2.slice(3, 5));

    let totalMin1Start = startHour1 * 60 + startMin1;
    let totalMin1End = endHour1 * 60 + endMin1;
    let totalMin2Start = startHour2 * 60 + startMin2;
    let totalMin2End = endHour2 * 60 + endMin2;

    return !(totalMin1End <= totalMin2Start || totalMin1Start >= totalMin2End);
}
```
The algorithm first parses the input strings and separates the hour and minute parts of each event. Then, it converts the event times to the total minutes from 00:00 to account for easier comparisons. Finally, it checks if the two events have any intersection by comparing the start and end time of each event in minutes. If there's a conflict, return true; otherwise, return false.


# Number of Subarrays With GCD Equal to K

- slug: number-of-subarrays-with-gcd-equal-to-k
- difficulty: Medium

Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the greatest common divisor of the subarray's elements is_ `k`.

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

The **greatest common divisor of an array** is the largest integer that evenly divides all the array elements.

**Example 1:**

**Input:** nums = \[9,3,1,2,6,3\], k = 3
**Output:** 4
**Explanation:** The subarrays of nums where 3 is the greatest common divisor of all the subarray's elements are:
- \[9,**3**,1,2,6,3\]
- \[9,3,1,2,6,**3**\]
- \[**9,3**,1,2,6,3\]
- \[9,3,1,2,**6,3**\]

**Example 2:**

**Input:** nums = \[4\], k = 7
**Output:** 0
**Explanation:** There are no subarrays of nums where 7 is the greatest common divisor of all the subarray's elements.

**Constraints:**

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

## A solution in Java

```java
public int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}

public int countGCDSubarrays(int[] nums, int k) {
    int count = 0;

    for (int i = 0; i < nums.length; ++i) {
        int gcdSoFar = 0;
        for (int j = i; j < nums.length; ++j) {
            gcdSoFar = gcd(gcdSoFar, nums[j]);
            if (gcdSoFar == k) ++count;
        }
    }

    return count;
}
```
To find the subarrays with a greatest common divisor (GCD) equal to `k`, we iterate through each element of `nums`. For each element 'i', we find the GCD of the subarrays starting at 'i' and ending at each element 'j' such that i <= j < nums.length.

To calculate the GCD of a subarray, we use the Euclidean algorithm which finds the GCD of two numbers by recursively dividing them and getting the remainder. In this case, we can use the previous GCD (`gcd_so_far`) and the current element (`nums[j]`) to update the GCD. When `gcd_so_far` is equal to `k`, we increment the count.

After traversing all subarrays, we return the count.

## A solution in C++

```cpp
int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}

int countGCDSubarrays(vector<int>& nums, int k) {
    int count = 0;

    for (int i = 0; i < nums.size(); ++i) {
        int gcd_so_far = 0;
        for (int j = i; j < nums.size(); ++j) {
            gcd_so_far = gcd(gcd_so_far, nums[j]);
            if (gcd_so_far == k) ++count;
        }
    }

    return count;
}
```
To find the subarrays with a greatest common divisor (GCD) equal to `k`, we iterate through each element of `nums`. For each element 'i', we find the GCD of the subarrays starting at 'i' and ending at each element 'j' such that i <= j < nums.length.

To calculate the GCD of a subarray, we use the Euclidean algorithm which finds the GCD of two numbers by recursively dividing them and getting the remainder. In this case, we can use the previous GCD (`gcd_so_far`) and the current element (`nums[j]`) to update the GCD. When `gcd_so_far` is equal to `k`, we increment the count.

After traversing all subarrays, we return the count.

## A solution in Python

```python
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def count_GCD_subarrays(nums, k):
    count = 0

    for i in range(len(nums)):
        gcd_so_far = 0
        for j in range(i, len(nums)):
            gcd_so_far = gcd(gcd_so_far, nums[j])
            if gcd_so_far == k:
                count += 1

    return count
```
To find the subarrays with a greatest common divisor (GCD) equal to `k`, we iterate through each element of `nums`. For each element 'i', we find the GCD of the subarrays starting at 'i' and ending at each element 'j' such that i <= j < nums.length.

To calculate the GCD of a subarray, we use the Euclidean algorithm which finds the GCD of two numbers by recursively dividing them and getting the remainder. In this case, we can use the previous GCD (`gcd_so_far`) and the current element (`nums[j]`) to update the GCD. When `gcd_so_far` is equal to `k`, we increment the count.

After traversing all subarrays, we return the count.

## A solution in Javascript

```javascript
function gcd(a, b) {
    if (b === 0) return a;
    return gcd(b, a % b);
}

function countGCDSubarrays(nums, k) {
    let count = 0;

    for (let i = 0; i < nums.length; ++i) {
        let gcdSoFar = 0;
        for (let j = i; j < nums.length; ++j) {
            gcdSoFar = gcd(gcdSoFar, nums[j]);
            if (gcdSoFar === k) ++count;
        }
    }

    return count;
}
```
To find the subarrays with a greatest common divisor (GCD) equal to `k`, we iterate through each element of `nums`. For each element 'i', we find the GCD of the subarrays starting at 'i' and ending at each element 'j' such that i <= j < nums.length.

To calculate the GCD of a subarray, we use the Euclidean algorithm which finds the GCD of two numbers by recursively dividing them and getting the remainder. In this case, we can use the previous GCD (`gcd_so_far`) and the current element (`nums[j]`) to update the GCD. When `gcd_so_far` is equal to `k`, we increment the count.

After traversing all subarrays, we return the count.


# Minimum Cost to Make Array Equal

- slug: minimum-cost-to-make-array-equal
- difficulty: Hard

You are given two **0-indexed** arrays `nums` and `cost` consisting each of `n` **positive** integers.

You can do the following operation **any** number of times:

*   Increase or decrease **any** element of the array `nums` by `1`.

The cost of doing one operation on the `ith` element is `cost[i]`.

Return _the **minimum** total cost such that all the elements of the array_ `nums` _become **equal**_.

**Example 1:**

**Input:** nums = \[1,3,5,2\], cost = \[2,3,1,14\]
**Output:** 8
**Explanation:** We can make all the elements equal to 2 in the following way:
- Increase the 0th element one time. The cost is 2.
- Decrease the 1st element one time. The cost is 3.
- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.
The total cost is 2 + 3 + 3 = 8.
It can be shown that we cannot make the array equal with a smaller cost.

**Example 2:**

**Input:** nums = \[2,2,2,2,2\], cost = \[4,2,8,1,3\]
**Output:** 0
**Explanation:** All the elements are already equal, so no operations are needed.

**Constraints:**

*   `n == nums.length == cost.length`
*   `1 <= n <= 105`
*   `1 <= nums[i], cost[i] <= 106`

## A solution in Java

```java
public long minCost(int[] nums, int[] cost) {
    long ans = Long.MAX_VALUE;
    int minValue = nums[0];

    for (int num : nums) {
        minValue = Math.min(minValue, num);
    }

    for (int target = minValue; target < minValue + 2; target++) {
        long local_res = 0;
        for (int i = 0; i < nums.length; i++) {
            local_res += Math.abs(nums[i] - target) * cost[i];
        }
        ans = Math.min(ans, local_res);
    }

    return ans;
}
```
The algorithm starts by finding the minimum value present in the `nums` array. Then, it iterates through `target` values within the range `[base, base + 1]` because we only need to check the minimum value and potential next minimum value. For each possible `target`, calculate the local result by iterating through the elements in the `nums` array and multiplying the absolute difference between the current element and target by the corresponding cost element. Update the global minimum cost if the local result is smaller than the current global minimum.

## A solution in C++

```cpp
long long minCost(vector<int>& nums, vector<int>& cost) {
    long long ans = LLONG_MAX;
    long long base = *min_element(nums.begin(), nums.end());

    for(int target = base; target < base+2; target++) {
        long long local_res = 0;
        for(int i = 0; i < nums.size(); i++) {
            local_res += abs(nums[i] - target) * cost[i];
        }
        ans = min(ans, local_res);
    }

    return ans;
}
```
The algorithm starts by finding the minimum value present in the `nums` array. Then, it iterates through `target` values within the range `[base, base + 1]` because we only need to check the minimum value and potential next minimum value. For each possible `target`, calculate the local result by iterating through the elements in the `nums` array and multiplying the absolute difference between the current element and target by the corresponding cost element. Update the global minimum cost if the local result is smaller than the current global minimum.

## A solution in Python

```python
def minCost(nums, cost):
    ans = float("inf")
    base = min(nums)

    for target in range(base, base + 2):
        local_res = 0
        for i in range(len(nums)):
            local_res += abs(nums[i] - target) * cost[i]
        ans = min(ans, local_res)

    return ans
```
The algorithm starts by finding the minimum value present in the `nums` array. Then, it iterates through `target` values within the range `[base, base + 1]` because we only need to check the minimum value and potential next minimum value. For each possible `target`, calculate the local result by iterating through the elements in the `nums` array and multiplying the absolute difference between the current element and target by the corresponding cost element. Update the global minimum cost if the local result is smaller than the current global minimum.

## A solution in Javascript

```javascript
function minCost(nums, cost) {
    let ans = Number.MAX_VALUE;
    let base = Math.min(...nums);

    for (let target = base; target < base + 2; target++) {
        let local_res = 0;
        for (let i = 0; i < nums.length; i++) {
            local_res += Math.abs(nums[i] - target) * cost[i];
        }
        ans = Math.min(ans, local_res);
    }

    return ans;
}
```
The algorithm starts by finding the minimum value present in the `nums` array. Then, it iterates through `target` values within the range `[base, base + 1]` because we only need to check the minimum value and potential next minimum value. For each possible `target`, calculate the local result by iterating through the elements in the `nums` array and multiplying the absolute difference between the current element and target by the corresponding cost element. Update the global minimum cost if the local result is smaller than the current global minimum.


# Minimum Number of Operations to Make Arrays Similar

- slug: minimum-number-of-operations-to-make-arrays-similar
- difficulty: Hard

You are given two positive integer arrays `nums` and `target`, of the same length.

In one operation, you can choose any two **distinct** indices `i` and `j` where `0 <= i, j < nums.length` and:

*   set `nums[i] = nums[i] + 2` and
*   set `nums[j] = nums[j] - 2`.

Two arrays are considered to be **similar** if the frequency of each element is the same.

Return _the minimum number of operations required to make_ `nums` _similar to_ `target`. The test cases are generated such that `nums` can always be similar to `target`.

**Example 1:**

**Input:** nums = \[8,12,6\], target = \[2,14,10\]
**Output:** 2
**Explanation:** It is possible to make nums similar to target in two operations:
- Choose i = 0 and j = 2, nums = \[10,12,4\].
- Choose i = 1 and j = 2, nums = \[10,14,2\].
It can be shown that 2 is the minimum number of operations needed.

**Example 2:**

**Input:** nums = \[1,2,5\], target = \[4,1,3\]
**Output:** 1
**Explanation:** We can make nums similar to target in one operation:
- Choose i = 1 and j = 2, nums = \[1,4,3\].

**Example 3:**

**Input:** nums = \[1,1,1,1,1\], target = \[1,1,1,1,1\]
**Output:** 0
**Explanation:** The array nums is already similiar to target.

**Constraints:**

*   `n == nums.length == target.length`
*   `1 <= n <= 105`
*   `1 <= nums[i], target[i] <= 106`
*   It is possible to make `nums` similar to `target`.

## A solution in Java

```java
public int minOperations(int[] nums, int[] target) {
    int n = nums.length;
    int sum_nums = 0;
    int sum_target = 0;
    for (int i = 0; i < n; i++) {
        sum_nums += nums[i];
        sum_target += target[i];
    }
    int diff = (sum_target - sum_nums) / 2;
    int cnt = 0;
    for (int i = 0; i < n; i++) {
        if (nums[i] > target[i]) {
            cnt += (nums[i] - target[i] - diff) / 2;
        }
    }
    return cnt;
}
```
1. Calculate the sum of both nums and target arrays.
2. Calculate the difference in sum (sum_target - sum_nums) and divide by 2.
3. For each element in nums, if it's greater than the corresponding element in target, increment the count cnt by the difference between the elements, minus diff and then divide by 2.
4. Return the cnt as the minimum number of operations required to make nums similar to target.

## A solution in C++

```cpp
int minOperations(vector<int>& nums, vector<int>& target) {
    int n = nums.size();
    int sum_nums = 0;
    int sum_target = 0;
    for (int i = 0; i < n; i++) {
        sum_nums += nums[i];
        sum_target += target[i];
    }
    int diff = (sum_target - sum_nums) / 2;
    int cnt = 0;
    for (int i = 0; i < n; i++) {
        if (nums[i] > target[i]) {
            cnt += (nums[i] - target[i] - diff) / 2;
        }
    }
    return cnt;
}
```
1. Calculate the sum of both nums and target arrays.
2. Calculate the difference in sum (sum_target - sum_nums) and divide by 2.
3. For each element in nums, if it's greater than the corresponding element in target, increment the count cnt by the difference between the elements, minus diff and then divide by 2.
4. Return the cnt as the minimum number of operations required to make nums similar to target.

## A solution in Python

```python
def minOperations(nums, target):
    n = len(nums)
    sum_nums = sum(nums)
    sum_target = sum(target)
    diff = (sum_target - sum_nums) // 2
    cnt = 0
    for i in range(n):
        if nums[i] > target[i]:
            cnt += (nums[i] - target[i] - diff) // 2
    return cnt
```
1. Calculate the sum of both nums and target arrays.
2. Calculate the difference in sum (sum_target - sum_nums) and divide by 2.
3. For each element in nums, if it's greater than the corresponding element in target, increment the count cnt by the difference between the elements, minus diff and then divide by 2.
4. Return the cnt as the minimum number of operations required to make nums similar to target.

## A solution in Javascript

```javascript
function minOperations(nums, target) {
    const n = nums.length;
    const sum_nums = nums.reduce((a, b) => a + b, 0);
    const sum_target = target.reduce((a, b) => a + b, 0);
    const diff = (sum_target - sum_nums) / 2;
    let cnt = 0;
    for (let i = 0; i < n; i++) {
        if (nums[i] > target[i]) {
            cnt += (nums[i] - target[i] - diff) / 2;
        }
    }
    return cnt;
}
```
1. Calculate the sum of both nums and target arrays.
2. Calculate the difference in sum (sum_target - sum_nums) and divide by 2.
3. For each element in nums, if it's greater than the corresponding element in target, increment the count cnt by the difference between the elements, minus diff and then divide by 2.
4. Return the cnt as the minimum number of operations required to make nums similar to target.


# Number of Distinct Binary Strings After Applying Operations

- slug: number-of-distinct-binary-strings-after-applying-operations
- difficulty: Medium

You are given a **binary** string `s` and a positive integer `k`.

You can apply the following operation on the string **any** number of times:

*   Choose any substring of size `k` from `s` and **flip** all its characters, that is, turn all `1`'s into `0`'s, and all `0`'s into `1`'s.

Return _the number of **distinct** strings you can obtain_. Since the answer may be too large, return it **modulo** `109 + 7`.

**Note** that:

*   A binary string is a string that consists **only** of the characters `0` and `1`.
*   A substring is a contiguous part of a string.

**Example 1:**

**Input:** s =  "1001 ", k = 3
**Output:** 4
**Explanation:** We can obtain the following strings:
- Applying no operation on the string gives s =  "1001 ".
- Applying one operation on the substring starting at index 0 gives s =  "**011**1 ".
- Applying one operation on the substring starting at index 1 gives s =  "1**110** ".
- Applying one operation on both the substrings starting at indices 0 and 1 gives s =  "**0000** ".
It can be shown that we cannot obtain any other string, so the answer is 4.

**Example 2:**

**Input:** s =  "10110 ", k = 5
**Output:** 2
**Explanation:** We can obtain the following strings:
- Applying no operation on the string gives s =  "10110 ".
- Applying one operation on the whole string gives s =  "01001 ".
It can be shown that we cannot obtain any other string, so the answer is 2.

**Constraints:**

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

## A solution in Java

```java
import java.util.HashSet;
import java.util.Set;

public int distinctStrings(String s, int k) {
    int n = s.length(), cnt = 0;
    Set<String> st = new HashSet<>();

    for (int i = 0; i <= n - k; ++i) {
        String temp = s.substring(0, i) + s.substring(i + k);
        if (!st.contains(temp)) {
            st.add(temp);
            cnt = (cnt + 1) % 1000000007;
        }
    }
    return cnt + 1; // Add 1 for the original string
}
```
The algorithm used for this problem involves iterating through the string `s` and checking all possible substrings with a length of `k`. We use a set to store the strings we've seen so far, creating a new string by removing the substring of length `k`. After iterating through all the possible substrings, we take the length of the set and add 1 (for the original string), then return the count modulo 1000000007.

## A solution in C++

```cpp
#include<string>
#include<unordered_set>
#define MOD 1000000007
using namespace std;

int distinctStrings(string s, int k) {
    int n = s.length(), cnt = 0;
    unordered_set<string> st;

    for (int i = 0; i <= n - k; ++i) {
        string temp = s.substr(0, i) + s.substr(i + k);
        if (st.count(temp) == 0) {
            st.insert(temp);
            cnt = (cnt + 1) % MOD;
        }
    }
    return cnt + 1; // Add 1 for the original string
}
```
The algorithm used for this problem involves iterating through the string `s` and checking all possible substrings with a length of `k`. We use a set to store the strings we've seen so far, creating a new string by removing the substring of length `k`. After iterating through all the possible substrings, we take the length of the set and add 1 (for the original string), then return the count modulo 1000000007.

## A solution in Python

```python
def distinctStrings(s, k):
    n = len(s)
    cnt = 0
    st = set()

    for i in range(n - k + 1):
        temp = s[:i] + s[i + k:]
        if temp not in st:
            st.add(temp)
            cnt = (cnt + 1) % 1000000007

    return cnt + 1 # Add 1 for the original string
```
The algorithm used for this problem involves iterating through the string `s` and checking all possible substrings with a length of `k`. We use a set to store the strings we've seen so far, creating a new string by removing the substring of length `k`. After iterating through all the possible substrings, we take the length of the set and add 1 (for the original string), then return the count modulo 1000000007.

## A solution in Javascript

```javascript
function distinctStrings(s, k) {
    const n = s.length;
    let cnt = 0;
    const st = new Set();

    for (let i = 0; i <= n - k; ++i) {
        const temp = s.substring(0, i) + s.substring(i + k);
        if (!st.has(temp)) {
            st.add(temp);
            cnt = (cnt + 1) % 1000000007;
        }
    }
    return cnt + 1; // Add 1 for the original string
}
```
The algorithm used for this problem involves iterating through the string `s` and checking all possible substrings with a length of `k`. We use a set to store the strings we've seen so far, creating a new string by removing the substring of length `k`. After iterating through all the possible substrings, we take the length of the set and add 1 (for the original string), then return the count modulo 1000000007.