# Make The String Great

- slug: make-the-string-great
- difficulty: Easy

Given a string `s` of lower and upper case English letters.

A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where:

*   `0 <= i <= s.length - 2`
*   `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**.

To make the string good, you can choose **two adjacent** characters that make the string bad and remove them. You can keep doing this until the string becomes good.

Return _the string_ after making it good. The answer is guaranteed to be unique under the given constraints.

**Notice** that an empty string is also good.

**Example 1:**

**Input:** s =  "leEeetcode "
**Output:**  "leetcode "
**Explanation:** In the first step, either you choose i = 1 or i = 2, both will result  "leEeetcode " to be reduced to  "leetcode ".

**Example 2:**

**Input:** s =  "abBAcC "
**Output:**  " "
**Explanation:** We have many possible scenarios, and all lead to the same answer. For example:
 "abBAcC " -->  "aAcC " -->  "cC " -->  " "
 "abBAcC " -->  "abBA " -->  "aA " -->  " "

**Example 3:**

**Input:** s =  "s "
**Output:**  "s "

**Constraints:**

*   `1 <= s.length <= 100`
*   `s` contains only lower and upper case English letters.

## A solution in Java

```java
public int goodNodes(TreeNode root) {
    return goodNodes(root, Integer.MIN_VALUE);
}

private int goodNodes(TreeNode root, int maxVal) {
    if (root == null) return 0;
    int result = 0;
    if (root.val >= maxVal) {
        result = 1;
        maxVal = root.val;
    }
    return result + goodNodes(root.left, maxVal) + goodNodes(root.right, maxVal);
}
```
The algorithm performs a depth-first search on the given binary tree. In order to traverse the tree and count the good nodes, the recursive `goodNodes` function is called, passing the current node and the maximum value found up to the current node.

1. If the current root is null, return 0 (no good nodes found).
2. Initialize a `result` variable to store the number of good nodes.
3. Check if the current node's value is greater or equal to the maximum value found so far. If it is, increment `result` by 1 and set `maxVal` to the current node's value.
4. Return the `result` plus the sum of the good nodes found in both the left and right child subtrees.

The base case for the recursion is when the root is null, in which case the function returns 0. This ensures that the function eventually terminates.

When all nodes of the binary tree have been visited, the function returns the total number of good nodes.

## A solution in C++

```cpp
int goodNodes(TreeNode* root, int maxVal = INT_MIN) {
    if (!root) return 0;
    int result = 0;
    if (root->val >= maxVal) {
        result = 1;
        maxVal = root->val;
    }
    return result + goodNodes(root->left, maxVal) + goodNodes(root->right, maxVal);
}
```
The algorithm performs a depth-first search on the given binary tree. In order to traverse the tree and count the good nodes, the recursive `goodNodes` function is called, passing the current node and the maximum value found up to the current node.

1. If the current root is null, return 0 (no good nodes found).
2. Initialize a `result` variable to store the number of good nodes.
3. Check if the current node's value is greater or equal to the maximum value found so far. If it is, increment `result` by 1 and set `maxVal` to the current node's value.
4. Return the `result` plus the sum of the good nodes found in both the left and right child subtrees.

The base case for the recursion is when the root is null, in which case the function returns 0. This ensures that the function eventually terminates.

When all nodes of the binary tree have been visited, the function returns the total number of good nodes.

## A solution in Python

```python
def goodNodes(root, maxVal=float('-inf')):
    if not root:
        return 0
    result = 0
    if root.val >= maxVal:
        result = 1
        maxVal = root.val
    return result + goodNodes(root.left, maxVal) + goodNodes(root.right, maxVal)
```
The algorithm performs a depth-first search on the given binary tree. In order to traverse the tree and count the good nodes, the recursive `goodNodes` function is called, passing the current node and the maximum value found up to the current node.

1. If the current root is null, return 0 (no good nodes found).
2. Initialize a `result` variable to store the number of good nodes.
3. Check if the current node's value is greater or equal to the maximum value found so far. If it is, increment `result` by 1 and set `maxVal` to the current node's value.
4. Return the `result` plus the sum of the good nodes found in both the left and right child subtrees.

The base case for the recursion is when the root is null, in which case the function returns 0. This ensures that the function eventually terminates.

When all nodes of the binary tree have been visited, the function returns the total number of good nodes.

## A solution in Javascript

```javascript
function goodNodes(root, maxVal = Number.MIN_SAFE_INTEGER) {
    if (!root) return 0;
    let result = 0;
    if (root.val >= maxVal) {
        result = 1;
        maxVal = root.val;
    }
    return result + goodNodes(root.left, maxVal) + goodNodes(root.right, maxVal);
}
```
The algorithm performs a depth-first search on the given binary tree. In order to traverse the tree and count the good nodes, the recursive `goodNodes` function is called, passing the current node and the maximum value found up to the current node.

1. If the current root is null, return 0 (no good nodes found).
2. Initialize a `result` variable to store the number of good nodes.
3. Check if the current node's value is greater or equal to the maximum value found so far. If it is, increment `result` by 1 and set `maxVal` to the current node's value.
4. Return the `result` plus the sum of the good nodes found in both the left and right child subtrees.

The base case for the recursion is when the root is null, in which case the function returns 0. This ensures that the function eventually terminates.

When all nodes of the binary tree have been visited, the function returns the total number of good nodes.


# Find Kth Bit in Nth Binary String

- slug: find-kth-bit-in-nth-binary-string
- difficulty: Medium

Given two positive integers `n` and `k`, the binary string `Sn` is formed as follows:

*   `S1 = "0 "`
*   `Si = Si - 1 + "1 " + reverse(invert(Si - 1))` for `i > 1`

Where `+` denotes the concatenation operation, `reverse(x)` returns the reversed string `x`, and `invert(x)` inverts all the bits in `x` (`0` changes to `1` and `1` changes to `0`).

For example, the first four strings in the above sequence are:

*   `S1 = "0 "`
*   `S2 = "0**1**1 "`
*   `S3 = "011**1**001 "`
*   `S4 = "0111001**1**0110001 "`

Return _the_ `kth` _bit_ _in_ `Sn`. It is guaranteed that `k` is valid for the given `n`.

**Example 1:**

**Input:** n = 3, k = 1
**Output:**  "0 "
**Explanation:** S3 is  "**0**111001 ".
The 1st bit is  "0 ".

**Example 2:**

**Input:** n = 4, k = 11
**Output:**  "1 "
**Explanation:** S4 is  "0111001101**1**0001 ".
The 11th bit is  "1 ".

**Constraints:**

*   `1 <= n <= 20`
*   `1 <= k <= 2n - 1`

## A solution in Java

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

    for (int t = 1; t <= target; ++t) {
        for (int i = 1; i <= 9; ++i) {
            if (t >= cost[i - 1] && dp[t - cost[i - 1]] != null) {
                String temp = dp[t - cost[i - 1]] + Integer.toString(i);
                if (dp[t] == null || dp[t].length() <= temp.length()) {
                    dp[t] = temp;
                }
            }
        }
    }

    return dp[target] == null ? "0" : dp[target];
}
```
We use dynamic programming with an array `dp` where `dp[i]` will store the largest integer that can be painted using exactly a cost of `i`. Initially, all elements of `dp` are empty strings except `dp[0]` which is an empty string (no digits are used). Loop through all possible prices from 1 to `target`, for each price loop through all digit costs from 1 to 9. If the current price minus the current digit cost has a valid value in the `dp`, add the current digit to the value and store it into `temp`. If the current value has a smaller length than `temp`, replace the current value with `temp`. This way we will find the maximum integer value for each cost. Finally, we return the value of dp[target], if it's empty we return "0" as there is no valid option.

## A solution in C++

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

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

    for (int t = 1; t <= target; ++t) {
        for (int i = 1; i <= 9; ++i) {
            if (t >= cost[i - 1]) {
                std::string temp = dp[t - cost[i - 1]] + char('0' + i);
                if (dp[t].length() <= temp.length()) {
                    dp[t] = temp;
                }
            }
        }
    }

    return dp[target].empty() ? "0" : dp[target];
}
```
We use dynamic programming with an array `dp` where `dp[i]` will store the largest integer that can be painted using exactly a cost of `i`. Initially, all elements of `dp` are empty strings except `dp[0]` which is an empty string (no digits are used). Loop through all possible prices from 1 to `target`, for each price loop through all digit costs from 1 to 9. If the current price minus the current digit cost has a valid value in the `dp`, add the current digit to the value and store it into `temp`. If the current value has a smaller length than `temp`, replace the current value with `temp`. This way we will find the maximum integer value for each cost. Finally, we return the value of dp[target], if it's empty we return "0" as there is no valid option.

## A solution in Python

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

    for t in range(1, target + 1):
        for i in range(1, 10):
            if t >= cost[i - 1] and dp[t - cost[i - 1]]:
                temp = dp[t - cost[i - 1]] + str(i)
                if len(dp[t]) <= len(temp):
                    dp[t] = temp

    return dp[target] if dp[target] else "0"
```
We use dynamic programming with an array `dp` where `dp[i]` will store the largest integer that can be painted using exactly a cost of `i`. Initially, all elements of `dp` are empty strings except `dp[0]` which is an empty string (no digits are used). Loop through all possible prices from 1 to `target`, for each price loop through all digit costs from 1 to 9. If the current price minus the current digit cost has a valid value in the `dp`, add the current digit to the value and store it into `temp`. If the current value has a smaller length than `temp`, replace the current value with `temp`. This way we will find the maximum integer value for each cost. Finally, we return the value of dp[target], if it's empty we return "0" as there is no valid option.

## A solution in Javascript

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

    for (let t = 1; t <= target; ++t) {
        for (let i = 1; i <= 9; ++i) {
            if (t >= cost[i - 1] && dp[t - cost[i - 1]] !== "") {
                const temp = dp[t - cost[i - 1]] + i.toString();
                if (dp[t].length <= temp.length) {
                    dp[t] = temp;
                }
            }
        }
    }

    return dp[target] === "" ? "0" : dp[target];
}
```
We use dynamic programming with an array `dp` where `dp[i]` will store the largest integer that can be painted using exactly a cost of `i`. Initially, all elements of `dp` are empty strings except `dp[0]` which is an empty string (no digits are used). Loop through all possible prices from 1 to `target`, for each price loop through all digit costs from 1 to 9. If the current price minus the current digit cost has a valid value in the `dp`, add the current digit to the value and store it into `temp`. If the current value has a smaller length than `temp`, replace the current value with `temp`. This way we will find the maximum integer value for each cost. Finally, we return the value of dp[target], if it's empty we return "0" as there is no valid option.


# Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

- slug: maximum-number-of-non-overlapping-subarrays-with-sum-equals-target
- difficulty: Medium

Given an array `nums` and an integer `target`, return _the maximum number of **non-empty** **non-overlapping** subarrays such that the sum of values in each subarray is equal to_ `target`.

**Example 1:**

**Input:** nums = \[1,1,1,1,1\], target = 2
**Output:** 2
**Explanation:** There are 2 non-overlapping subarrays \[**1,1**,1,**1,1**\] with sum equals to target(2).

**Example 2:**

**Input:** nums = \[-1,3,5,1,4,2,-9\], target = 6
**Output:** 2
**Explanation:** There are 3 subarrays with sum equal to 6.
(\[5,1\], \[4,2\], \[3,5,1,4,2,-9\]) but only the first 2 are non-overlapping.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `-104 <= nums[i] <= 104`
*   `0 <= target <= 106`

## A solution in Java

```java
public int maxNonOverlapping(int[] nums, int target) {
    Map<Integer, Integer> prefixSum = new HashMap<>();
    int sum = 0, count = 0;
    prefixSum.put(0, 0);
    for (int num : nums) {
        sum += num;
        if (prefixSum.containsKey(sum - target)) {
            count = Math.max(count, 1 + prefixSum.get(sum - target));
        }
        prefixSum.put(sum, count);
    }
    return count;
}
```
We use the prefix sum to cumulatively store the sum of the array until the current position. On each iteration, we calculate the sum of elements and then check if the (current sum - target) exists in the prefix sum hashmap. If it exists, it means we have a subarray that sums to the target, so we update our count. We also make sure to only consider non-overlapping subarrays by storing the current max count in the hashmap.

## A solution in C++

```cpp
int maxNonOverlapping(vector<int>& nums, int target) {
    unordered_map<int, int> prefix_sum;
    int sum = 0, count = 0;
    prefix_sum[0] = 0;
    for (const int& num : nums) {
        sum += num;
        if (prefix_sum.find(sum - target) != prefix_sum.end()) {
            count = max(count, 1 + prefix_sum[sum - target]);
        }
        prefix_sum[sum] = count;
    }
    return count;
}
```
We use the prefix sum to cumulatively store the sum of the array until the current position. On each iteration, we calculate the sum of elements and then check if the (current sum - target) exists in the prefix sum hashmap. If it exists, it means we have a subarray that sums to the target, so we update our count. We also make sure to only consider non-overlapping subarrays by storing the current max count in the hashmap.

## A solution in Python

```python
def maxNonOverlapping(nums, target):
    prefix_sum = {0: 0}
    sum, count = 0, 0
    for num in nums:
        sum += num
        if sum - target in prefix_sum:
            count = max(count, 1 + prefix_sum[sum - target])
        prefix_sum[sum] = count
    return count
```
We use the prefix sum to cumulatively store the sum of the array until the current position. On each iteration, we calculate the sum of elements and then check if the (current sum - target) exists in the prefix sum hashmap. If it exists, it means we have a subarray that sums to the target, so we update our count. We also make sure to only consider non-overlapping subarrays by storing the current max count in the hashmap.

## A solution in Javascript

```javascript
function maxNonOverlapping(nums, target) {
    const prefixSum = new Map();
    let sum = 0, count = 0;
    prefixSum.set(0, 0);
    for (const num of nums) {
        sum += num;
        if (prefixSum.has(sum - target)) {
            count = Math.max(count, 1 + prefixSum.get(sum - target));
        }
        prefixSum.set(sum, count);
    }
    return count;
}
```
We use the prefix sum to cumulatively store the sum of the array until the current position. On each iteration, we calculate the sum of elements and then check if the (current sum - target) exists in the prefix sum hashmap. If it exists, it means we have a subarray that sums to the target, so we update our count. We also make sure to only consider non-overlapping subarrays by storing the current max count in the hashmap.


# Minimum Cost to Cut a Stick

- slug: minimum-cost-to-cut-a-stick
- difficulty: Hard

Given a wooden stick of length `n` units. The stick is labelled from `0` to `n`. For example, a stick of length **6** is labelled as follows:

Given an integer array `cuts` where `cuts[i]` denotes a position you should perform a cut at.

You should perform the cuts in order, you can change the order of the cuts as you wish.

The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.

Return _the minimum total cost_ of the cuts.

**Example 1:**

**Input:** n = 7, cuts = \[1,3,4,5\]
**Output:** 16
**Explanation:** Using cuts order = \[1, 3, 4, 5\] as in the input leads to the following scenario:

The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.
Rearranging the cuts to be \[3, 5, 1, 4\] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).

**Example 2:**

**Input:** n = 9, cuts = \[5,6,1,4,2\]
**Output:** 22
**Explanation:** If you try the given cuts ordering the cost will be 25.
There are much ordering with total cost <= 25, for example, the order \[4, 6, 5, 2, 1\] has total cost = 22 which is the minimum possible.

**Constraints:**

*   `2 <= n <= 106`
*   `1 <= cuts.length <= min(n - 1, 100)`
*   `1 <= cuts[i] <= n - 1`
*   All the integers in `cuts` array are **distinct**.

## A solution in Java

```java
import java.util.*;

public String destCity(List<List<String>> paths) {
    Set<String> startingCities = new HashSet<>();
    for (List<String> path : paths)
        startingCities.add(path.get(0));

    for (List<String> path : paths) {
        if (!startingCities.contains(path.get(1)))
            return path.get(1);
    }

    return "";
}
```
We start by creating a set `starting_cities` that will contain all the cities that have a direct path _outgoing_ from them. Then, for each path, we add the city where the path starts to our set.

Once we have the set, we iterate through the given paths again, checking if the destination city of each path (cityBi) is present in the set `starting_cities`. If a city is not present in the set, that means it doesn't have any outgoing path, and we return that city as the destination city.

The algorithm has a time complexity of O(n), where n is the number of paths, since we iterate through the paths twice.

## A solution in C++

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

std::string destCity(std::vector<std::vector<std::string>>& paths) {
    std::unordered_set<std::string> starting_cities;
    for (const auto& path : paths)
        starting_cities.insert(path[0]);

    for (const auto& path : paths) {
        if (starting_cities.find(path[1]) == starting_cities.end())
            return path[1];
    }

    return "";
}
```
We start by creating a set `starting_cities` that will contain all the cities that have a direct path _outgoing_ from them. Then, for each path, we add the city where the path starts to our set.

Once we have the set, we iterate through the given paths again, checking if the destination city of each path (cityBi) is present in the set `starting_cities`. If a city is not present in the set, that means it doesn't have any outgoing path, and we return that city as the destination city.

The algorithm has a time complexity of O(n), where n is the number of paths, since we iterate through the paths twice.

## A solution in Python

```python
def destCity(paths):
    starting_cities = set()

    for path in paths:
        starting_cities.add(path[0])

    for path in paths:
        if path[1] not in starting_cities:
            return path[1]

    return ""
```
We start by creating a set `starting_cities` that will contain all the cities that have a direct path _outgoing_ from them. Then, for each path, we add the city where the path starts to our set.

Once we have the set, we iterate through the given paths again, checking if the destination city of each path (cityBi) is present in the set `starting_cities`. If a city is not present in the set, that means it doesn't have any outgoing path, and we return that city as the destination city.

The algorithm has a time complexity of O(n), where n is the number of paths, since we iterate through the paths twice.

## A solution in Javascript

```javascript
function destCity(paths) {
    const startingCities = new Set();

    for (const path of paths)
        startingCities.add(path[0]);

    for (const path of paths) {
        if (!startingCities.has(path[1]))
            return path[1];
    }

    return "";
}
```
We start by creating a set `starting_cities` that will contain all the cities that have a direct path _outgoing_ from them. Then, for each path, we add the city where the path starts to our set.

Once we have the set, we iterate through the given paths again, checking if the destination city of each path (cityBi) is present in the set `starting_cities`. If a city is not present in the set, that means it doesn't have any outgoing path, and we return that city as the destination city.

The algorithm has a time complexity of O(n), where n is the number of paths, since we iterate through the paths twice.


# The Most Similar Path in a Graph

- slug: the-most-similar-path-in-a-graph
- difficulty: Hard

We have `n` cities and `m` bi-directional `roads` where `roads[i] = [ai, bi]` connects city `ai` with city `bi`. Each city has a name consisting of exactly three upper-case English letters given in the string array `names`. Starting at any city `x`, you can reach any city `y` where `y != x` (i.e., the cities and the roads are forming an undirected connected graph).

You will be given a string array `targetPath`. You should find a path in the graph of the **same length** and with the **minimum edit distance** to `targetPath`.

You need to return _the order of the nodes in the path with the minimum edit distance_. The path should be of the same length of `targetPath` and should be valid (i.e., there should be a direct road between `ans[i]` and `ans[i + 1]`). If there are multiple answers return any one of them.

The **edit distance** is defined as follows:

**Example 1:**

**Input:** n = 5, roads = \[\[0,2\],\[0,3\],\[1,2\],\[1,3\],\[1,4\],\[2,4\]\], names = \[ "ATL ", "PEK ", "LAX ", "DXB ", "HND "\], targetPath = \[ "ATL ", "DXB ", "HND ", "LAX "\]
**Output:** \[0,2,4,2\]
**Explanation:** \[0,2,4,2\], \[0,3,0,2\] and \[0,3,1,2\] are accepted answers.
\[0,2,4,2\] is equivalent to \[ "ATL ", "LAX ", "HND ", "LAX "\] which has edit distance = 1 with targetPath.
\[0,3,0,2\] is equivalent to \[ "ATL ", "DXB ", "ATL ", "LAX "\] which has edit distance = 1 with targetPath.
\[0,3,1,2\] is equivalent to \[ "ATL ", "DXB ", "PEK ", "LAX "\] which has edit distance = 1 with targetPath.

**Example 2:**

**Input:** n = 4, roads = \[\[1,0\],\[2,0\],\[3,0\],\[2,1\],\[3,1\],\[3,2\]\], names = \[ "ATL ", "PEK ", "LAX ", "DXB "\], targetPath = \[ "ABC ", "DEF ", "GHI ", "JKL ", "MNO ", "PQR ", "STU ", "VWX "\]
**Output:** \[0,1,0,1,0,1,0,1\]
**Explanation:** Any path in this graph has edit distance = 8 with targetPath.

**Example 3:**

**Input:** n = 6, roads = \[\[0,1\],\[1,2\],\[2,3\],\[3,4\],\[4,5\]\], names = \[ "ATL ", "PEK ", "LAX ", "ATL ", "DXB ", "HND "\], targetPath = \[ "ATL ", "DXB ", "HND ", "DXB ", "ATL ", "LAX ", "PEK "\]
**Output:** \[3,4,5,4,3,2,1\]
**Explanation:** \[3,4,5,4,3,2,1\] is the only path with edit distance = 0 with targetPath.
It's equivalent to \[ "ATL ", "DXB ", "HND ", "DXB ", "ATL ", "LAX ", "PEK "\]

**Constraints:**

*   `2 <= n <= 100`
*   `m == roads.length`
*   `n - 1 <= m <= (n * (n - 1) / 2)`
*   `0 <= ai, bi <= n - 1`
*   `ai != bi`
*   The graph is guaranteed to be **connected** and each pair of nodes may have **at most one** direct road.
*   `names.length == n`
*   `names[i].length == 3`
*   `names[i]` consists of upper-case English letters.
*   There can be two cities with **the same** name.
*   `1 <= targetPath.length <= 100`
*   `targetPath[i].length == 3`
*   `targetPath[i]` consists of upper-case English letters.

**Follow up:** If each node can be visited only once in the path, What should you change in your solution?

## A solution in Java

```java
public boolean kLengthApart(int[] nums, int k) {
    int last_one = -1;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 1) {
            if (last_one != -1 && i - last_one <= k) {
                return false;
            }
            last_one = i;
        }
    }
    return true;
}
```
The algorithm iterates through the binary array `nums`. As it iterates, it keeps track of the position of the last 1 it encountered in the array, which is initially set to -1. When it finds a 1 in the array, it checks if the distance between this 1 and the previous 1 is greater than or equal to `k` (i.e., the distance should be more than `k`). If yes, it updates the last 1's position. If not, the function returns false. If the loop completes without finding any two 1s closer than `k` places from each other, the function returns true.

## A solution in C++

```cpp
bool kLengthApart(vector<int>& nums, int k) {
    int last_one = -1;
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] == 1) {
            if (last_one != -1 && i - last_one <= k) {
                return false;
            }
            last_one = i;
        }
    }
    return true;
}
```
The algorithm iterates through the binary array `nums`. As it iterates, it keeps track of the position of the last 1 it encountered in the array, which is initially set to -1. When it finds a 1 in the array, it checks if the distance between this 1 and the previous 1 is greater than or equal to `k` (i.e., the distance should be more than `k`). If yes, it updates the last 1's position. If not, the function returns false. If the loop completes without finding any two 1s closer than `k` places from each other, the function returns true.

## A solution in Python

```python
def kLengthApart(nums, k):
    last_one = -1
    for i, num in enumerate(nums):
        if num == 1:
            if last_one != -1 and i - last_one <= k:
                return False
            last_one = i
    return True
```
The algorithm iterates through the binary array `nums`. As it iterates, it keeps track of the position of the last 1 it encountered in the array, which is initially set to -1. When it finds a 1 in the array, it checks if the distance between this 1 and the previous 1 is greater than or equal to `k` (i.e., the distance should be more than `k`). If yes, it updates the last 1's position. If not, the function returns false. If the loop completes without finding any two 1s closer than `k` places from each other, the function returns true.

## A solution in Javascript

```javascript
function kLengthApart(nums, k) {
    let last_one = -1;
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] === 1) {
            if (last_one !== -1 && i - last_one <= k) {
                return false;
            }
            last_one = i;
        }
    }
    return true;
}
```
The algorithm iterates through the binary array `nums`. As it iterates, it keeps track of the position of the last 1 it encountered in the array, which is initially set to -1. When it finds a 1 in the array, it checks if the distance between this 1 and the previous 1 is greater than or equal to `k` (i.e., the distance should be more than `k`). If yes, it updates the last 1's position. If not, the function returns false. If the loop completes without finding any two 1s closer than `k` places from each other, the function returns true.


# Three Consecutive Odds

- slug: three-consecutive-odds
- difficulty: Easy

Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`.

**Example 1:**

**Input:** arr = \[2,6,4,1\]
**Output:** false
**Explanation:** There are no three consecutive odds.

**Example 2:**

**Input:** arr = \[1,2,34,3,4,5,7,23,12\]
**Output:** true
**Explanation:** \[5,7,23\] are three consecutive odds.

**Constraints:**

*   `1 <= arr.length <= 1000`
*   `1 <= arr[i] <= 1000`

## A solution in Java

```java
import java.util.Comparator;
import java.util.PriorityQueue;

public int kthSmallest(int[][] mat, int k) {
    int m = mat.length, n = mat[0].length;

    PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparing(a -> a[0]));
    minHeap.offer(new int[]{mat[0][0], 0, 0});

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

    int res = 0;
    while (k-- > 0) {
        int[] cur = minHeap.poll();
        res = cur[0];
        int i = cur[1], j = cur[2];

        if (i < m - 1 && !visited[i+1][j]) {
            minHeap.offer(new int[]{res - mat[i][j] + mat[i + 1][j], i + 1, j});
            visited[i+1][j] = true;
        }
        if (j < n - 1 && !visited[i][j+1]) {
            minHeap.offer(new int[]{res - mat[i][j] + mat[i][j + 1], i, j + 1});
            visited[i][j+1] = true;
        }
    }

    return res;
}
```
The algorithm uses a min-heap data structure initialized with the smallest element (top-left corner) of the matrix. We maintain a matrix `visited` of booleans that tells if an element of the matrix is in the heap.

In each iteration, the algorithm pops the smallest element from the min-heap, updates the result, and inserts the elements below and to the right of the matrix, if they have not been visited yet. This process is repeated k times. After the kth iteration, the result holds the sum of the kth smallest array.

The algorithm has a time complexity of O(k * (m + n)), since in the worst case we have to visit all elements of all rows and columns m and n times (when k = m * n).

Note that in JavaScript, we do not use a priority queue implementation. Instead, we add elements to the array and sort the array each time after adding elements. This gives slightly worse performance in practice, but for the given problem size, it should suffice.

## A solution in C++

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

int kthSmallest(const std::vector<std::vector<int>>& mat, int k) {
    int m = mat.size(), n = mat[0].size();

    auto comp = [&](const std::vector<int>& a, const std::vector<int>& b) {
        return a[0] > b[0];
    };

    std::priority_queue<std::vector<int>, std::vector<std::vector<int>>, decltype(comp)> minHeap(comp);
    minHeap.push({mat[0][0], 0, 0});

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

    int res;
    while (k--) {
        auto cur = minHeap.top(); minHeap.pop();
        res = cur[0];
        int i = cur[1], j = cur[2];

        if (i < m - 1 && !visited[i+1][j]) {
            minHeap.push({res - mat[i][j] + mat[i + 1][j], i + 1, j});
            visited[i+1][j] = true;
        }
        if (j < n - 1 && !visited[i][j+1]) {
            minHeap.push({res - mat[i][j] + mat[i][j + 1], i, j + 1});
            visited[i][j+1] = true;
        }
    }

    return res;
}
```
The algorithm uses a min-heap data structure initialized with the smallest element (top-left corner) of the matrix. We maintain a matrix `visited` of booleans that tells if an element of the matrix is in the heap.

In each iteration, the algorithm pops the smallest element from the min-heap, updates the result, and inserts the elements below and to the right of the matrix, if they have not been visited yet. This process is repeated k times. After the kth iteration, the result holds the sum of the kth smallest array.

The algorithm has a time complexity of O(k * (m + n)), since in the worst case we have to visit all elements of all rows and columns m and n times (when k = m * n).

Note that in JavaScript, we do not use a priority queue implementation. Instead, we add elements to the array and sort the array each time after adding elements. This gives slightly worse performance in practice, but for the given problem size, it should suffice.

## A solution in Python

```python
import heapq

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

    minHeap = [(mat[0][0], 0, 0)]
    visited = [[False for _ in range(n)] for _ in range(m)]
    visited[0][0] = True

    for _ in range(k):
        res, i, j = heapq.heappop(minHeap)

        if i < m - 1 and not visited[i+1][j]:
            heapq.heappush(minHeap, (res - mat[i][j] + mat[i + 1][j], i + 1, j))
            visited[i+1][j] = True
        if j < n - 1 and not visited[i][j+1]:
            heapq.heappush(minHeap, (res - mat[i][j] + mat[i][j + 1], i, j + 1))
            visited[i][j+1] = True

    return res
```
The algorithm uses a min-heap data structure initialized with the smallest element (top-left corner) of the matrix. We maintain a matrix `visited` of booleans that tells if an element of the matrix is in the heap.

In each iteration, the algorithm pops the smallest element from the min-heap, updates the result, and inserts the elements below and to the right of the matrix, if they have not been visited yet. This process is repeated k times. After the kth iteration, the result holds the sum of the kth smallest array.

The algorithm has a time complexity of O(k * (m + n)), since in the worst case we have to visit all elements of all rows and columns m and n times (when k = m * n).

Note that in JavaScript, we do not use a priority queue implementation. Instead, we add elements to the array and sort the array each time after adding elements. This gives slightly worse performance in practice, but for the given problem size, it should suffice.

## A solution in Javascript

```javascript
function kthSmallest(mat, k) {
    const m = mat.length, n = mat[0].length;

    const minHeap = [[mat[0][0], 0, 0]].sort((a, b) => a[0] - b[0]);
    const visited = Array(m).fill().map(_ => Array(n).fill(false));
    visited[0][0] = true;

    let res = 0;
    while (k-- > 0) {
        const [val, i, j] = minHeap.shift();
        res = val;

        if (i < m - 1 && !visited[i+1][j]) {
            minHeap.push([res - mat[i][j] + mat[i + 1][j], i + 1, j]);
            visited[i+1][j] = true;
        }
        if (j < n - 1 && !visited[i][j+1]) {
            minHeap.push([res - mat[i][j] + mat[i][j + 1], i, j + 1]);
            visited[i][j+1] = true;
        }

        minHeap.sort((a, b) => a[0] - b[0]);
    }

    return res;
}
```
The algorithm uses a min-heap data structure initialized with the smallest element (top-left corner) of the matrix. We maintain a matrix `visited` of booleans that tells if an element of the matrix is in the heap.

In each iteration, the algorithm pops the smallest element from the min-heap, updates the result, and inserts the elements below and to the right of the matrix, if they have not been visited yet. This process is repeated k times. After the kth iteration, the result holds the sum of the kth smallest array.

The algorithm has a time complexity of O(k * (m + n)), since in the worst case we have to visit all elements of all rows and columns m and n times (when k = m * n).

Note that in JavaScript, we do not use a priority queue implementation. Instead, we add elements to the array and sort the array each time after adding elements. This gives slightly worse performance in practice, but for the given problem size, it should suffice.


# Minimum Operations to Make Array Equal

- slug: minimum-operations-to-make-array-equal
- difficulty: Medium

You have an array `arr` of length `n` where `arr[i] = (2 * i) + 1` for all valid values of `i` (i.e., `0 <= i < n`).

In one operation, you can select two indices `x` and `y` where `0 <= x, y < n` and subtract `1` from `arr[x]` and add `1` to `arr[y]` (i.e., perform `arr[x] -=1` and `arr[y] += 1`). The goal is to make all the elements of the array **equal**. It is **guaranteed** that all the elements of the array can be made equal using some operations.

Given an integer `n`, the length of the array, return _the minimum number of operations_ needed to make all the elements of arr equal.

**Example 1:**

**Input:** n = 3
**Output:** 2
**Explanation:** arr = \[1, 3, 5\]
First operation choose x = 2 and y = 0, this leads arr to be \[2, 3, 4\]
In the second operation choose x = 2 and y = 0 again, thus arr = \[3, 3, 3\].

**Example 2:**

**Input:** n = 6
**Output:** 9

**Constraints:**

*   `1 <= n <= 104`

## A solution in Java

```java
public int minOperations(int n) {
    return n * n / 4;
}
```
This problem can be solved mathematically without iterating through the array. Since the given array is of length `n` and always has the pattern `arr[i] = (2 * i) + 1`, the average value will always be the middle value when `n` is odd, and the average of two middle values when `n` is even.

In both cases, you can calculate the number of operations needed to make all elements equal by using the following formula: `n * n / 4`. The integer division (`//` in Python) and `Math.floor()` in JavaScript are used to get the integer result of the division.

For example, for `n = 3`, the array will be `[1, 3, 5]`. The average value is `3`, and you need 2 operations to turn `1` and `5` into `3`. The formula `n * n / 4` yields `3 * 3 / 4` = `2`. Similarly, for `n = 6`, the array will be `[1, 3, 5, 7, 9, 11]`, and you need 9 operations to make all elements equal. The formula gives `6 * 6 / 4` = `9`.

## A solution in C++

```cpp
int minOperations(int n) {
    return n * n / 4;
}
```
This problem can be solved mathematically without iterating through the array. Since the given array is of length `n` and always has the pattern `arr[i] = (2 * i) + 1`, the average value will always be the middle value when `n` is odd, and the average of two middle values when `n` is even.

In both cases, you can calculate the number of operations needed to make all elements equal by using the following formula: `n * n / 4`. The integer division (`//` in Python) and `Math.floor()` in JavaScript are used to get the integer result of the division.

For example, for `n = 3`, the array will be `[1, 3, 5]`. The average value is `3`, and you need 2 operations to turn `1` and `5` into `3`. The formula `n * n / 4` yields `3 * 3 / 4` = `2`. Similarly, for `n = 6`, the array will be `[1, 3, 5, 7, 9, 11]`, and you need 9 operations to make all elements equal. The formula gives `6 * 6 / 4` = `9`.

## A solution in Python

```python
def min_operations(n):
    return n * n // 4
```
This problem can be solved mathematically without iterating through the array. Since the given array is of length `n` and always has the pattern `arr[i] = (2 * i) + 1`, the average value will always be the middle value when `n` is odd, and the average of two middle values when `n` is even.

In both cases, you can calculate the number of operations needed to make all elements equal by using the following formula: `n * n / 4`. The integer division (`//` in Python) and `Math.floor()` in JavaScript are used to get the integer result of the division.

For example, for `n = 3`, the array will be `[1, 3, 5]`. The average value is `3`, and you need 2 operations to turn `1` and `5` into `3`. The formula `n * n / 4` yields `3 * 3 / 4` = `2`. Similarly, for `n = 6`, the array will be `[1, 3, 5, 7, 9, 11]`, and you need 9 operations to make all elements equal. The formula gives `6 * 6 / 4` = `9`.

## A solution in Javascript

```javascript
function minOperations(n) {
    return Math.floor(n * n / 4);
}
```
This problem can be solved mathematically without iterating through the array. Since the given array is of length `n` and always has the pattern `arr[i] = (2 * i) + 1`, the average value will always be the middle value when `n` is odd, and the average of two middle values when `n` is even.

In both cases, you can calculate the number of operations needed to make all elements equal by using the following formula: `n * n / 4`. The integer division (`//` in Python) and `Math.floor()` in JavaScript are used to get the integer result of the division.

For example, for `n = 3`, the array will be `[1, 3, 5]`. The average value is `3`, and you need 2 operations to turn `1` and `5` into `3`. The formula `n * n / 4` yields `3 * 3 / 4` = `2`. Similarly, for `n = 6`, the array will be `[1, 3, 5, 7, 9, 11]`, and you need 9 operations to make all elements equal. The formula gives `6 * 6 / 4` = `9`.


# Magnetic Force Between Two Balls

- slug: magnetic-force-between-two-balls
- difficulty: Medium

In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** between any two balls is **maximum**.

Rick stated that magnetic force between two different balls at positions `x` and `y` is `|x - y|`.

Given the integer array `position` and the integer `m`. Return _the required force_.

**Example 1:**

**Input:** position = \[1,2,3,4,7\], m = 3
**Output:** 3
**Explanation:** Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs \[3, 3, 6\]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.

**Example 2:**

**Input:** position = \[5,4,3,2,1,1000000000\], m = 2
**Output:** 999999999
**Explanation:** We can use baskets 1 and 1000000000.

**Constraints:**

*   `n == position.length`
*   `2 <= n <= 105`
*   `1 <= position[i] <= 109`
*   All integers in `position` are **distinct**.
*   `2 <= m <= position.length`

## A solution in Java

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

public List<String> buildArray(int[] target, int n) {
    List<String> result = new ArrayList<>();
    int current = 1;
    for (int num : target) {
        while (current < num) {
            result.add("Push");
            result.add("Pop");
            current++;
        }
        result.add("Push");
        current++;
    }
    return result;
}
```
The algorithm iterates through the `target` array. For each number, it checks if the `current` value (starting from 1) is smaller. If it is, the algorithm adds the "Push" and "Pop" operations to the result list, because these numbers in `list` are not part of the `target` array. The `current` value is then incremented. Once the `current` value reaches the `num` in the target array, the algorithm adds a "Push" operation to the result list and increments the `current` value again. This process continues until the entire target array has been built using the operations listed in the result list.

## A solution in C++

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

std::vector<std::string> buildArray(std::vector<int>& target, int n) {
    std::vector<std::string> result;
    int current = 1;
    for (int num : target) {
        while (current < num) {
            result.push_back("Push");
            result.push_back("Pop");
            current++;
        }
        result.push_back("Push");
        current++;
    }
    return result;
}
```
The algorithm iterates through the `target` array. For each number, it checks if the `current` value (starting from 1) is smaller. If it is, the algorithm adds the "Push" and "Pop" operations to the result list, because these numbers in `list` are not part of the `target` array. The `current` value is then incremented. Once the `current` value reaches the `num` in the target array, the algorithm adds a "Push" operation to the result list and increments the `current` value again. This process continues until the entire target array has been built using the operations listed in the result list.

## A solution in Python

```python
def build_array(target, n):
    result = []
    current = 1
    for num in target:
        while current < num:
            result.append("Push")
            result.append("Pop")
            current += 1
        result.append("Push")
        current += 1
    return result
```
The algorithm iterates through the `target` array. For each number, it checks if the `current` value (starting from 1) is smaller. If it is, the algorithm adds the "Push" and "Pop" operations to the result list, because these numbers in `list` are not part of the `target` array. The `current` value is then incremented. Once the `current` value reaches the `num` in the target array, the algorithm adds a "Push" operation to the result list and increments the `current` value again. This process continues until the entire target array has been built using the operations listed in the result list.

## A solution in Javascript

```javascript
function buildArray(target, n) {
    const result = [];
    let current = 1;
    for (const num of target) {
        while (current < num) {
            result.push("Push");
            result.push("Pop");
            current++;
        }
        result.push("Push");
        current++;
    }
    return result;
}
```
The algorithm iterates through the `target` array. For each number, it checks if the `current` value (starting from 1) is smaller. If it is, the algorithm adds the "Push" and "Pop" operations to the result list, because these numbers in `list` are not part of the `target` array. The `current` value is then incremented. Once the `current` value reaches the `num` in the target array, the algorithm adds a "Push" operation to the result list and increments the `current` value again. This process continues until the entire target array has been built using the operations listed in the result list.


# Minimum Number of Days to Eat N Oranges

- slug: minimum-number-of-days-to-eat-n-oranges
- difficulty: Hard

There are `n` oranges in the kitchen and you decided to eat some of these oranges every day as follows:

*   Eat one orange.
*   If the number of remaining oranges `n` is divisible by `2` then you can eat `n / 2` oranges.
*   If the number of remaining oranges `n` is divisible by `3` then you can eat `2 * (n / 3)` oranges.

You can only choose one of the actions per day.

Given the integer `n`, return _the minimum number of days to eat_ `n` _oranges_.

**Example 1:**

**Input:** n = 10
**Output:** 4
**Explanation:** You have 10 oranges.
Day 1: Eat 1 orange,  10 - 1 = 9.
Day 2: Eat 6 oranges, 9 - 2\*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
Day 3: Eat 2 oranges, 3 - 2\*(3/3) = 3 - 2 = 1.
Day 4: Eat the last orange  1 - 1  = 0.
You need at least 4 days to eat the 10 oranges.

**Example 2:**

**Input:** n = 6
**Output:** 3
**Explanation:** You have 6 oranges.
Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).
Day 2: Eat 2 oranges, 3 - 2\*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)
Day 3: Eat the last orange  1 - 1  = 0.
You need at least 3 days to eat the 6 oranges.

**Constraints:**

*   `1 <= n <= 2 * 109`

## A solution in Java

```java
public int countTriplets(int[] arr) {
    int n = arr.length;
    int[] XOR = new int[n+1];

    for (int i = 0; i < n; i++) {
        XOR[i+1] = XOR[i] ^ arr[i];
    }

    int count = 0;
    for (int i = 0; i < n; i++) {
        for (int k = i+1; k < n; k++) {
            if(XOR[i] == XOR[k+1]) count += k-i;
        }
    }
    return count;
}
```
1. Calculate the prefix xor array `XOR` by iterating through the array `arr` and performing bitwise-xor operation. Initialize an array `XOR` of size n+1 with the first element as 0. Then for each element i, update XOR[i+1] with XOR[i] ^ arr[i].
2. Initialize a counter variable `count`.
3. Iterate through the array with nested loops. The outer loop iterates from index 0 to n-1, i.e., i = 0 to n-1.
4. In the inner loop, iterate from index i+1 to n-1, i.e., k = i+1 to n-1.
5. Check if XOR[i] is equal to XOR[k+1]. If it is true, increment count by k-i.
6. Return the count.

## A solution in C++

```cpp
int countTriplets(vector<int>& arr) {
    int n = arr.size();
    vector<int> XOR(n+1, 0);

    for (int i = 0; i < n; i++) {
        XOR[i+1] = XOR[i] ^ arr[i];
    }

    int count = 0;
    for (int i = 0; i < n; i++) {
        for (int k = i+1; k < n; k++) {
            if(XOR[i] == XOR[k+1]) count += k-i;
        }
    }
    return count;
}
```
1. Calculate the prefix xor array `XOR` by iterating through the array `arr` and performing bitwise-xor operation. Initialize an array `XOR` of size n+1 with the first element as 0. Then for each element i, update XOR[i+1] with XOR[i] ^ arr[i].
2. Initialize a counter variable `count`.
3. Iterate through the array with nested loops. The outer loop iterates from index 0 to n-1, i.e., i = 0 to n-1.
4. In the inner loop, iterate from index i+1 to n-1, i.e., k = i+1 to n-1.
5. Check if XOR[i] is equal to XOR[k+1]. If it is true, increment count by k-i.
6. Return the count.

## A solution in Python

```python
def countTriplets(arr):
    n = len(arr)
    XOR = [0] * (n + 1)

    for i in range(n):
        XOR[i+1] = XOR[i] ^ arr[i]

    count = 0
    for i in range(n):
        for k in range(i+1, n):
            if XOR[i] == XOR[k+1]:
                count += k-i
    return count
```
1. Calculate the prefix xor array `XOR` by iterating through the array `arr` and performing bitwise-xor operation. Initialize an array `XOR` of size n+1 with the first element as 0. Then for each element i, update XOR[i+1] with XOR[i] ^ arr[i].
2. Initialize a counter variable `count`.
3. Iterate through the array with nested loops. The outer loop iterates from index 0 to n-1, i.e., i = 0 to n-1.
4. In the inner loop, iterate from index i+1 to n-1, i.e., k = i+1 to n-1.
5. Check if XOR[i] is equal to XOR[k+1]. If it is true, increment count by k-i.
6. Return the count.

## A solution in Javascript

```javascript
function countTriplets(arr) {
    let n = arr.length;
    let XOR = new Array(n + 1).fill(0);

    for (let i = 0; i < n; i++) {
        XOR[i+1] = XOR[i] ^ arr[i];
    }

    let count = 0;
    for (let i = 0; i < n; i++) {
        for (let k = i+1; k < n; k++) {
            if (XOR[i] === XOR[k+1]) {
                count += (k-i);
            }
        }
    }
    return count;
}
```
1. Calculate the prefix xor array `XOR` by iterating through the array `arr` and performing bitwise-xor operation. Initialize an array `XOR` of size n+1 with the first element as 0. Then for each element i, update XOR[i+1] with XOR[i] ^ arr[i].
2. Initialize a counter variable `count`.
3. Iterate through the array with nested loops. The outer loop iterates from index 0 to n-1, i.e., i = 0 to n-1.
4. In the inner loop, iterate from index i+1 to n-1, i.e., k = i+1 to n-1.
5. Check if XOR[i] is equal to XOR[k+1]. If it is true, increment count by k-i.
6. Return the count.


# Strings Differ by One Character

- slug: strings-differ-by-one-character
- difficulty: Medium

Given a list of strings `dict` where all the strings are of the same length.

Return `true` if there are 2 strings that only differ by 1 character in the same index, otherwise return `false`.

**Example 1:**

**Input:** dict = \[ "abcd ", "acbd ",  "aacd "\]
**Output:** true
**Explanation:** Strings  "a**b**cd " and  "a**a**cd " differ only by one character in the index 1.

**Example 2:**

**Input:** dict = \[ "ab ", "cd ", "yz "\]
**Output:** false

**Example 3:**

**Input:** dict = \[ "abcd ", "cccc ", "abyd ", "abab "\]
**Output:** true

**Constraints:**

*   The number of characters in `dict <= 105`
*   `dict[i].length == dict[j].length`
*   `dict[i]` should be unique.
*   `dict[i]` contains only lowercase English letters.

**Follow up:** Could you solve this problem in `O(n * m)` where n is the length of `dict` and `m` is the length of each string.

## A solution in Java

```java
import java.util.*;

public int minTime(int n, int[][] edges, boolean[] hasApple) {
    Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();

    for (int[] edge : edges) {
        graph.computeIfAbsent(edge[0], k -> new HashMap<>()).put(edge[1], 0);
        graph.computeIfAbsent(edge[1], k -> new HashMap<>()).put(edge[0], 0);
    }

    return dfs(n, 0, -1, hasApple, graph);
}

private int dfs(int n, int v, int parent, boolean[] hasApple, Map<Integer, Map<Integer, Integer>> graph) {
    int ans = 0;
    for (int u : graph.get(v).keySet()) {
        if (u == parent) continue;
        ans += dfs(n, u, v, hasApple, graph) * 2;
    }

    return ans + ((hasApple[v] || ans > 0) ? 1 : 0);
}
```
The algorithm works as follows:
1. Build a graph representation using a hashmap with the given edges.
2. Implement a depth-first search (dfs) function to traverse the tree.
   - The input parameters are the vertex, and it's parent.
   - The output is the minimum time required to collect apples from the sub-tree rooted at the given vertex.
3. During the dfs traversal, visit each neighbor of the current vertex (ignoring the parent).
   - For each neighbor, accumulator (ans) is incremented by (dfs(neighbor) * 2). The reason it's multiplied by 2 is because you have to spend time going to and coming back from the neighbor.
4. Finally, include the time spent at the current vertex if it has an apple or if some time was spent in its sub-tree.
5. Call the dfs function with the root vertex (0) and parent (-1).
6. Return the result obtained from the dfs function.

The time complexity is O(n) as each vertex is visited once.

## A solution in C++

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

int minTime(int n, std::vector<std::vector<int>>& edges, std::vector<bool>& hasApple) {
    std::unordered_map<int, std::unordered_map<int, int>> graph;

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

    std::function<int(int, int)> dfs = [&](int v, int parent) {
        int ans = 0;
        for (auto& [u, _] : graph[v]) {
            if (u == parent) continue;
            ans += dfs(u, v) * 2;
        }
        return ans + (hasApple[v] || ans);
    };

    return dfs(0, -1);
}
```
The algorithm works as follows:
1. Build a graph representation using a hashmap with the given edges.
2. Implement a depth-first search (dfs) function to traverse the tree.
   - The input parameters are the vertex, and it's parent.
   - The output is the minimum time required to collect apples from the sub-tree rooted at the given vertex.
3. During the dfs traversal, visit each neighbor of the current vertex (ignoring the parent).
   - For each neighbor, accumulator (ans) is incremented by (dfs(neighbor) * 2). The reason it's multiplied by 2 is because you have to spend time going to and coming back from the neighbor.
4. Finally, include the time spent at the current vertex if it has an apple or if some time was spent in its sub-tree.
5. Call the dfs function with the root vertex (0) and parent (-1).
6. Return the result obtained from the dfs function.

The time complexity is O(n) as each vertex is visited once.

## A solution in Python

```python
def minTime(n, edges, hasApple):
    graph = {i: {} for i in range(n)}

    for a, b in edges:
        graph[a][b] = 0
        graph[b][a] = 0

    def dfs(v, parent):
        ans = 0
        for u in graph[v]:
            if u == parent:
                continue
            ans += dfs(u, v) * 2
        return ans + int(hasApple[v] or ans > 0)

    return dfs(0, -1)
```
The algorithm works as follows:
1. Build a graph representation using a hashmap with the given edges.
2. Implement a depth-first search (dfs) function to traverse the tree.
   - The input parameters are the vertex, and it's parent.
   - The output is the minimum time required to collect apples from the sub-tree rooted at the given vertex.
3. During the dfs traversal, visit each neighbor of the current vertex (ignoring the parent).
   - For each neighbor, accumulator (ans) is incremented by (dfs(neighbor) * 2). The reason it's multiplied by 2 is because you have to spend time going to and coming back from the neighbor.
4. Finally, include the time spent at the current vertex if it has an apple or if some time was spent in its sub-tree.
5. Call the dfs function with the root vertex (0) and parent (-1).
6. Return the result obtained from the dfs function.

The time complexity is O(n) as each vertex is visited once.

## A solution in Javascript

```javascript
function minTime(n, edges, hasApple) {
  const graph = Array.from({ length: n }, () => new Map());

  for (const [a, b] of edges) {
    graph[a].set(b, 0);
    graph[b].set(a, 0);
  }

  function dfs(v, parent) {
    let ans = 0;
    for (const [u, _] of graph[v]) {
      if (u === parent) continue;
      ans += dfs(u, v) * 2;
    }

    return ans + (hasApple[v] || ans > 0 ? 1 : 0);
  }

  return dfs(0, -1);
}
```
The algorithm works as follows:
1. Build a graph representation using a hashmap with the given edges.
2. Implement a depth-first search (dfs) function to traverse the tree.
   - The input parameters are the vertex, and it's parent.
   - The output is the minimum time required to collect apples from the sub-tree rooted at the given vertex.
3. During the dfs traversal, visit each neighbor of the current vertex (ignoring the parent).
   - For each neighbor, accumulator (ans) is incremented by (dfs(neighbor) * 2). The reason it's multiplied by 2 is because you have to spend time going to and coming back from the neighbor.
4. Finally, include the time spent at the current vertex if it has an apple or if some time was spent in its sub-tree.
5. Call the dfs function with the root vertex (0) and parent (-1).
6. Return the result obtained from the dfs function.

The time complexity is O(n) as each vertex is visited once.


# Thousand Separator

- slug: thousand-separator
- difficulty: Easy

Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.

**Example 1:**

**Input:** n = 987
**Output:**  "987 "

**Example 2:**

**Input:** n = 1234
**Output:**  "1.234 "

**Constraints:**

*   `0 <= n <= 231 - 1`

## A solution in Java

```java
import java.util.Arrays;

public boolean canBeEqual(int[] target, int[] arr) {
    Arrays.sort(target);
    Arrays.sort(arr);
    return Arrays.equals(target, arr);
}
```
The basic idea behind the solution is to compare the sorted versions of the input arrays `target` and `arr`. If they are equal after sorting, it means that we can obtain `target` from `arr` by reversing any number of sub-arrays, since we can sort `arr` by reversing sub-arrays of length 2.

1. Sort the input arrays `target` and `arr`.
2. Compare the sorted arrays for equality.
3. If the sorted arrays are equal, return `true`; otherwise, return `false`.

The time complexity is O(n log n) as the solution involves sorting the arrays, and the space complexity is O(log n) for the sorting operations.

## A solution in C++

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

bool canBeEqual(std::vector<int>& target, std::vector<int>& arr) {
    std::sort(target.begin(), target.end());
    std::sort(arr.begin(), arr.end());
    return target == arr;
}
```
The basic idea behind the solution is to compare the sorted versions of the input arrays `target` and `arr`. If they are equal after sorting, it means that we can obtain `target` from `arr` by reversing any number of sub-arrays, since we can sort `arr` by reversing sub-arrays of length 2.

1. Sort the input arrays `target` and `arr`.
2. Compare the sorted arrays for equality.
3. If the sorted arrays are equal, return `true`; otherwise, return `false`.

The time complexity is O(n log n) as the solution involves sorting the arrays, and the space complexity is O(log n) for the sorting operations.

## A solution in Python

```python
def can_be_equal(target, arr):
    target.sort()
    arr.sort()
    return target == arr
```
The basic idea behind the solution is to compare the sorted versions of the input arrays `target` and `arr`. If they are equal after sorting, it means that we can obtain `target` from `arr` by reversing any number of sub-arrays, since we can sort `arr` by reversing sub-arrays of length 2.

1. Sort the input arrays `target` and `arr`.
2. Compare the sorted arrays for equality.
3. If the sorted arrays are equal, return `true`; otherwise, return `false`.

The time complexity is O(n log n) as the solution involves sorting the arrays, and the space complexity is O(log n) for the sorting operations.

## A solution in Javascript

```javascript
function canBeEqual(target, arr) {
    target.sort((a, b) => a - b);
    arr.sort((a, b) => a - b);
    return JSON.stringify(target) === JSON.stringify(arr);
}
```
The basic idea behind the solution is to compare the sorted versions of the input arrays `target` and `arr`. If they are equal after sorting, it means that we can obtain `target` from `arr` by reversing any number of sub-arrays, since we can sort `arr` by reversing sub-arrays of length 2.

1. Sort the input arrays `target` and `arr`.
2. Compare the sorted arrays for equality.
3. If the sorted arrays are equal, return `true`; otherwise, return `false`.

The time complexity is O(n log n) as the solution involves sorting the arrays, and the space complexity is O(log n) for the sorting operations.


# Minimum Number of Vertices to Reach All Nodes

- slug: minimum-number-of-vertices-to-reach-all-nodes
- difficulty: Medium

Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.

Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists.

Notice that you can return the vertices in any order.

**Example 1:**

**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\]
**Output:** \[0,3\]
**Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\].

**Example 2:**

**Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\]
**Output:** \[0,2,3\]
**Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.

**Constraints:**

*   `2 <= n <= 10^5`
*   `1 <= edges.length <= min(10^5, n * (n - 1) / 2)`
*   `edges[i].length == 2`
*   `0 <= fromi, toi < n`
*   All pairs `(fromi, toi)` are distinct.

## A solution in Java

```java
public boolean hasAllCodes(String s, int k) {
    int need = 1 << k;
    Set<String> got = new HashSet<>();

    for (int i = 0; i <= s.length() - k; i++) {
        got.add(s.substring(i, i + k));
    }

    return got.size() == need;
}
```
We need to find all binary codes with a length of `k`. The total number of binary codes with length `k` can be obtained by `1 << k`, which is basically 2^k.

We then create a set `got` to store unique substrings of length `k` found in the input string `s`. We iterate through the string `s` with an index `i` ranging between `0` and `s.length - k`, and add the substring of length k to the set `got`.

After iterating for all substrings, we compare the size of the `got` set with the `need`. If they match, it means that all binary codes of length `k` have been found in the input string, so we return `true`. Otherwise, we return `false`.

## A solution in C++

```cpp
bool hasAllCodes(std::string s, int k) {
    int need = 1 << k;
    std::unordered_set<std::string> got;

    for (int i = 0; i <= s.size() - k; i++) {
        got.insert(s.substr(i, k));
    }

    return got.size() == need;
}
```
We need to find all binary codes with a length of `k`. The total number of binary codes with length `k` can be obtained by `1 << k`, which is basically 2^k.

We then create a set `got` to store unique substrings of length `k` found in the input string `s`. We iterate through the string `s` with an index `i` ranging between `0` and `s.length - k`, and add the substring of length k to the set `got`.

After iterating for all substrings, we compare the size of the `got` set with the `need`. If they match, it means that all binary codes of length `k` have been found in the input string, so we return `true`. Otherwise, we return `false`.

## A solution in Python

```python
def has_all_codes(s, k):
    need = 1 << k
    got = set()

    for i in range(len(s) - k + 1):
        got.add(s[i:i + k])

    return len(got) == need
```
We need to find all binary codes with a length of `k`. The total number of binary codes with length `k` can be obtained by `1 << k`, which is basically 2^k.

We then create a set `got` to store unique substrings of length `k` found in the input string `s`. We iterate through the string `s` with an index `i` ranging between `0` and `s.length - k`, and add the substring of length k to the set `got`.

After iterating for all substrings, we compare the size of the `got` set with the `need`. If they match, it means that all binary codes of length `k` have been found in the input string, so we return `true`. Otherwise, we return `false`.

## A solution in Javascript

```javascript
function hasAllCodes(s, k) {
    const need = 1 << k;
    const got = new Set();

    for (let i = 0; i <= s.length - k; i++) {
        got.add(s.slice(i, i + k));
    }

    return got.size === need;
}
```
We need to find all binary codes with a length of `k`. The total number of binary codes with length `k` can be obtained by `1 << k`, which is basically 2^k.

We then create a set `got` to store unique substrings of length `k` found in the input string `s`. We iterate through the string `s` with an index `i` ranging between `0` and `s.length - k`, and add the substring of length k to the set `got`.

After iterating for all substrings, we compare the size of the `got` set with the `need`. If they match, it means that all binary codes of length `k` have been found in the input string, so we return `true`. Otherwise, we return `false`.


# Minimum Numbers of Function Calls to Make Target Array

- slug: minimum-numbers-of-function-calls-to-make-target-array
- difficulty: Medium

You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:

You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.

Return _the minimum number of function calls to make_ `nums` _from_ `arr`.

The test cases are generated so that the answer fits in a **32-bit** signed integer.

**Example 1:**

**Input:** nums = \[1,5\]
**Output:** 5
**Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation).
Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations).
Increment by 1 (both elements)  \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations).
Total of operations: 1 + 2 + 2 = 5.

**Example 2:**

**Input:** nums = \[2,2\]
**Output:** 3
**Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations).
Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation).
Total of operations: 2 + 1 = 3.

**Example 3:**

**Input:** nums = \[4,2,5\]
**Output:** 6
**Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums).

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

public class Solution {
    public void DFS(int src, Map<Integer, List<Integer>> graph, boolean[] visited, boolean[] transitiveClosure, int dest) {
        if (src == dest) {
            transitiveClosure[dest] = true;
            return;
        }
        if (visited[src]) return;
        visited[src] = true;
        for (int neighbor : graph.get(src)) {
            DFS(neighbor, graph, visited, transitiveClosure, dest);
            if (transitiveClosure[dest]) return;
        }
    }

    public boolean[] checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
        Map<Integer, List<Integer>> graph = new HashMap<>();

        for (int[] pre : prerequisites) {
            graph.computeIfAbsent(pre[0], k -> new ArrayList<>()).add(pre[1]);
        }

        boolean[] result = new boolean[queries.length];

        for (int i = 0; i < queries.length; ++i) {
            boolean[] visited = new boolean[numCourses];
            boolean[] transitiveClosure = new boolean[numCourses];
            DFS(queries[i][0], graph, visited, transitiveClosure, queries[i][1]);
            result[i] = transitiveClosure[queries[i][1]];
        }

        return result;
    }
}
```
The algorithm starts by creating a graph representation from the given prerequisites, with the courses represented as nodes and directed edges from the prerequisites to the dependent courses. Then, for each query, we perform a Depth-First Search (DFS) from the source course to check if we can reach the destination course. During the DFS traversal, we maintain a visited array and a transitive closure array to prevent cycles and to mark prerequisite courses. If we reach the destination course during DFS, we set the corresponding position in the transitive closure array to true, indicating that the prerequisite is satisfied. Finally, results are collected in an array and returned.

## A solution in C++

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

using namespace std;

void DFS(int src, unordered_map<int, vector<int>> &graph, vector<bool> &visited, vector<bool> &transitiveClosure, int dest) {
    if (src == dest) {
        transitiveClosure[dest] = true;
        return;
    }
    if (visited[src]) return;
    visited[src] = true;
    for (int neighbor : graph[src]) {
        DFS(neighbor, graph, visited, transitiveClosure, dest);
        if (transitiveClosure[dest]) return;
    }
}

vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
    unordered_map<int, vector<int>> graph;

    for (auto &pre : prerequisites) {
        graph[pre[0]].push_back(pre[1]);
    }

    vector<bool> result(queries.size());

    for (int i = 0; i < queries.size(); ++i) {
        vector<bool> visited(numCourses, false);
        vector<bool> transitiveClosure(numCourses, false);
        DFS(queries[i][0], graph, visited, transitiveClosure, queries[i][1]);
        result[i] = transitiveClosure[queries[i][1]];
    }

    return result;
}
```
The algorithm starts by creating a graph representation from the given prerequisites, with the courses represented as nodes and directed edges from the prerequisites to the dependent courses. Then, for each query, we perform a Depth-First Search (DFS) from the source course to check if we can reach the destination course. During the DFS traversal, we maintain a visited array and a transitive closure array to prevent cycles and to mark prerequisite courses. If we reach the destination course during DFS, we set the corresponding position in the transitive closure array to true, indicating that the prerequisite is satisfied. Finally, results are collected in an array and returned.

## A solution in Python

```python
from collections import defaultdict

def DFS(src, graph, visited, transitive_closure, dest):
    if src == dest:
        transitive_closure[dest] = True
        return
    if visited[src]:
        return
    visited[src] = True
    for neighbor in graph[src]:
        DFS(neighbor, graph, visited, transitive_closure, dest)
        if transitive_closure[dest]:
            return

def checkIfPrerequisite(numCourses, prerequisites, queries):
    graph = defaultdict(list)

    for pre in prerequisites:
        graph[pre[0]].append(pre[1])

    result = []

    for i in range(len(queries)):
        visited = [False] * numCourses
        transitive_closure = [False] * numCourses
        DFS(queries[i][0], graph, visited, transitive_closure, queries[i][1])
        result.append(transitive_closure[queries[i][1]])

    return result
```
The algorithm starts by creating a graph representation from the given prerequisites, with the courses represented as nodes and directed edges from the prerequisites to the dependent courses. Then, for each query, we perform a Depth-First Search (DFS) from the source course to check if we can reach the destination course. During the DFS traversal, we maintain a visited array and a transitive closure array to prevent cycles and to mark prerequisite courses. If we reach the destination course during DFS, we set the corresponding position in the transitive closure array to true, indicating that the prerequisite is satisfied. Finally, results are collected in an array and returned.

## A solution in Javascript

```javascript
function DFS(src, graph, visited, transitiveClosure, dest) {
    if (src === dest) {
        transitiveClosure[dest] = true;
        return;
    }
    if (visited[src]) return;
    visited[src] = true;
    for (let neighbor of graph[src]) {
        DFS(neighbor, graph, visited, transitiveClosure, dest);
        if (transitiveClosure[dest]) return;
    }
}

function checkIfPrerequisite(numCourses, prerequisites, queries) {
    const graph = new Map();

    for (let pre of prerequisites) {
        if (!graph.has(pre[0])) {
            graph.set(pre[0], []);
        }
        graph.get(pre[0]).push(pre[1]);
    }

    const result = [];

    for (let i = 0; i < queries.length; ++i) {
        const visited = new Array(numCourses).fill(false);
        const transitiveClosure = new Array(numCourses).fill(false);
        DFS(queries[i][0], graph, visited, transitiveClosure, queries[i][1]);
        result.push(transitiveClosure[queries[i][1]]);
    }

    return result;
}
```
The algorithm starts by creating a graph representation from the given prerequisites, with the courses represented as nodes and directed edges from the prerequisites to the dependent courses. Then, for each query, we perform a Depth-First Search (DFS) from the source course to check if we can reach the destination course. During the DFS traversal, we maintain a visited array and a transitive closure array to prevent cycles and to mark prerequisite courses. If we reach the destination course during DFS, we set the corresponding position in the transitive closure array to true, indicating that the prerequisite is satisfied. Finally, results are collected in an array and returned.


# Detect Cycles in 2D Grid

- slug: detect-cycles-in-2d-grid
- difficulty: Medium

Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.

A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the **same value** of the current cell.

Also, you cannot move to the cell that you visited in your last move. For example, the cycle `(1, 1) -> (1, 2) -> (1, 1)` is invalid because from `(1, 2)` we visited `(1, 1)` which was the last visited cell.

Return `true` if any cycle of the same value exists in `grid`, otherwise, return `false`.

**Example 1:**

**Input:** grid = \[\[ "a ", "a ", "a ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "a ", "a ", "a "\]\]
**Output:** true
**Explanation:** There are two valid cycles shown in different colors in the image below:

**Example 2:**

**Input:** grid = \[\[ "c ", "c ", "c ", "a "\],\[ "c ", "d ", "c ", "c "\],\[ "c ", "c ", "e ", "c "\],\[ "f ", "c ", "c ", "c "\]\]
**Output:** true
**Explanation:** There is only one valid cycle highlighted in the image below:

**Example 3:**

**Input:** grid = \[\[ "a ", "b ", "b "\],\[ "b ", "z ", "b "\],\[ "b ", "b ", "a "\]\]
**Output:** false

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 500`
*   `grid` consists only of lowercase English letters.

## A solution in Java

```java
public int cherryPickup(int[][] grid) {
    int rows = grid.length;
    int cols = grid[0].length;
    int[][][] dp = new int[rows][cols][cols];

    for (int row = rows - 1; row >= 0; --row) {
        for (int col1 = 0; col1 < cols; ++col1) {
            for (int col2 = 0; col2 < cols; ++col2) {
                int currentCell = row < rows - 1 ? dp[row + 1][col1][col2] : 0;
                currentCell += grid[row][col1] + (col1 != col2 ? grid[row][col2] : 0);

                int maxVal = 0;
                for (int move1 = -1; move1 <= 1; ++move1) {
                    for (int move2 = -1; move2 <= 1; ++move2) {
                        int newCol1 = col1 + move1;
                        int newCol2 = col2 + move2;
                        if (newCol1 >= 0 && newCol1 < cols && newCol2 >= 0 && newCol2 < cols) {
                            maxVal = Math.max(maxVal, dp[row][newCol1][newCol2]);
                        }
                    }
                }

                dp[row][col1][col2] = currentCell + maxVal;
            }
        }
    }

    return dp[0][0][cols - 1];
}
```
We use a 3D dynamic programming approach where dp[row][col1][col2] - cherries count that can be picked by two robots by the end of row 'row' if the first robot is currently in the cell (row, col1) and the second robot is currently in the cell (row, col2)

1. Iterate through the rows in reverse order, from the bottom to the top.
2. For each row, iterate through the columns col1 and col2 for the first and second robot and calculate the cherries collected in the current cell.
3. Calculate the maximum number of cherries that can be collected for the current cell by accounting for valid moves in the next row.
4. Update dp[row][col1][col2] with the sum of cherries collected at the current cell and maximum cherries that can be collected in the next row.
5. Return dp[0][0][cols-1] which represents the maximum number of cherries that can be collected by both robots after reaching the top row.

## A solution in C++

```cpp
int cherryPickup(vector<vector<int>>& grid) {
    int rows = grid.size();
    int cols = grid[0].size();
    vector<vector<vector<int>>> dp(rows, vector<vector<int>>(cols, vector<int>(cols, 0)));

    for (int row = rows - 1; row >= 0; --row) {
        for (int col1 = 0; col1 < cols; ++col1) {
            for (int col2 = 0; col2 < cols; ++col2) {
                int currentCell = row < rows - 1 ? dp[row + 1][col1][col2] : 0;
                currentCell += grid[row][col1] + (col1 != col2 ? grid[row][col2] : 0);

                int maxVal = 0;
                for (int move1 = -1; move1 <= 1; ++move1) {
                    for (int move2 = -1; move2 <= 1; ++move2) {
                        int newCol1 = col1 + move1;
                        int newCol2 = col2 + move2;
                        if (newCol1 >= 0 && newCol1 < cols && newCol2 >= 0 && newCol2 < cols) {
                            maxVal = max(maxVal, dp[row][newCol1][newCol2]);
                        }
                    }
                }

                dp[row][col1][col2] = currentCell + maxVal;
            }
        }
    }

    return dp[0][0][cols - 1];
}
```
We use a 3D dynamic programming approach where dp[row][col1][col2] - cherries count that can be picked by two robots by the end of row 'row' if the first robot is currently in the cell (row, col1) and the second robot is currently in the cell (row, col2)

1. Iterate through the rows in reverse order, from the bottom to the top.
2. For each row, iterate through the columns col1 and col2 for the first and second robot and calculate the cherries collected in the current cell.
3. Calculate the maximum number of cherries that can be collected for the current cell by accounting for valid moves in the next row.
4. Update dp[row][col1][col2] with the sum of cherries collected at the current cell and maximum cherries that can be collected in the next row.
5. Return dp[0][0][cols-1] which represents the maximum number of cherries that can be collected by both robots after reaching the top row.

## A solution in Python

```python
def cherry_pickup(grid):
    rows, cols = len(grid), len(grid[0])
    dp = [[[0] * cols for _ in range(cols)] for _ in range(rows)]

    for row in reversed(range(rows)):
        for col1 in range(cols):
            for col2 in range(cols):
                current_cell = dp[row + 1][col1][col2] if row < rows - 1 else 0
                current_cell += grid[row][col1] + (grid[row][col2] if col1 != col2 else 0)

                max_val = 0
                for move1 in range(-1, 2):
                    for move2 in range(-1, 2):
                        new_col1, new_col2 = col1 + move1, col2 + move2
                        if 0 <= new_col1 < cols and 0 <= new_col2 < cols:
                            max_val = max(max_val, dp[row][new_col1][new_col2])

                dp[row][col1][col2] = current_cell + max_val

    return dp[0][0][cols - 1]
```
We use a 3D dynamic programming approach where dp[row][col1][col2] - cherries count that can be picked by two robots by the end of row 'row' if the first robot is currently in the cell (row, col1) and the second robot is currently in the cell (row, col2)

1. Iterate through the rows in reverse order, from the bottom to the top.
2. For each row, iterate through the columns col1 and col2 for the first and second robot and calculate the cherries collected in the current cell.
3. Calculate the maximum number of cherries that can be collected for the current cell by accounting for valid moves in the next row.
4. Update dp[row][col1][col2] with the sum of cherries collected at the current cell and maximum cherries that can be collected in the next row.
5. Return dp[0][0][cols-1] which represents the maximum number of cherries that can be collected by both robots after reaching the top row.

## A solution in Javascript

```javascript
function cherryPickup(grid) {
    let rows = grid.length;
    let cols = grid[0].length;
    let dp = new Array(rows).fill(0).map(() => new Array(cols).fill(0).map(() => new Array(cols).fill(0)));

    for (let row = rows - 1; row >= 0; --row) {
        for (let col1 = 0; col1 < cols; ++col1) {
            for (let col2 = 0; col2 < cols; ++col2) {
                let currentCell = row < rows - 1 ? dp[row + 1][col1][col2] : 0;
                currentCell += grid[row][col1] + (col1 !== col2 ? grid[row][col2] : 0);

                let maxVal = 0;
                for (let move1 = -1; move1 <= 1; ++move1) {
                    for (let move2 = -1; move2 <= 1; ++move2) {
                        let newCol1 = col1 + move1;
                        let newCol2 = col2 + move2;
                        if (newCol1 >= 0 && newCol1 < cols && newCol2 >= 0 && newCol2 < cols) {
                            maxVal = Math.max(maxVal, dp[row][newCol1][newCol2]);
                        }
                    }
                }

                dp[row][col1][col2] = currentCell + maxVal;
            }
        }
    }

    return dp[0][0][cols - 1];
}
```
We use a 3D dynamic programming approach where dp[row][col1][col2] - cherries count that can be picked by two robots by the end of row 'row' if the first robot is currently in the cell (row, col1) and the second robot is currently in the cell (row, col2)

1. Iterate through the rows in reverse order, from the bottom to the top.
2. For each row, iterate through the columns col1 and col2 for the first and second robot and calculate the cherries collected in the current cell.
3. Calculate the maximum number of cherries that can be collected for the current cell by accounting for valid moves in the next row.
4. Update dp[row][col1][col2] with the sum of cherries collected at the current cell and maximum cherries that can be collected in the next row.
5. Return dp[0][0][cols-1] which represents the maximum number of cherries that can be collected by both robots after reaching the top row.


# Most Visited Sector in  a Circular Track

- slug: most-visited-sector-in-a-circular-track
- difficulty: Easy

Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at sector `rounds[0]` and ends at sector `rounds[1]`

Return _an array of the most visited sectors_ sorted in **ascending** order.

Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).

**Example 1:**

**Input:** n = 4, rounds = \[1,3,1,2\]
**Output:** \[1,2\]
**Explanation:** The marathon starts at sector 1. The order of the visited sectors is as follows:
1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.

**Example 2:**

**Input:** n = 2, rounds = \[2,1,2,1,2,1,2,1,2\]
**Output:** \[2\]

**Example 3:**

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

**Constraints:**

*   `2 <= n <= 100`
*   `1 <= m <= 100`
*   `rounds.length == m + 1`
*   `1 <= rounds[i] <= n`
*   `rounds[i] != rounds[i + 1]` for `0 <= i < m`

## A solution in Java

```java
public int busyStudent(int[] startTime, int[] endTime, int queryTime) {
    int count = 0;
    for (int i = 0; i < startTime.length; i++) {
        if (startTime[i] <= queryTime && endTime[i] >= queryTime) {
            count++;
        }
    }
    return count;
}
```
The algorithm consists of iterating through the startTime and endTime arrays in parallel, by checking if the queryTime lies within the range of startTime[i] and endTime[i]. If it's within the range, increment the count. Finally, return the count as the result. The code is quite similar across the different languages.

## A solution in C++

```cpp
int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime) {
    int count = 0;
    for (int i = 0; i < startTime.size(); i++) {
        if (startTime[i] <= queryTime && endTime[i] >= queryTime) {
            count++;
        }
    }
    return count;
}
```
The algorithm consists of iterating through the startTime and endTime arrays in parallel, by checking if the queryTime lies within the range of startTime[i] and endTime[i]. If it's within the range, increment the count. Finally, return the count as the result. The code is quite similar across the different languages.

## A solution in Python

```python
def busy_student(start_time, end_time, query_time):
    count = 0
    for i in range(len(start_time)):
        if start_time[i] <= query_time <= end_time[i]:
            count += 1
    return count
```
The algorithm consists of iterating through the startTime and endTime arrays in parallel, by checking if the queryTime lies within the range of startTime[i] and endTime[i]. If it's within the range, increment the count. Finally, return the count as the result. The code is quite similar across the different languages.

## A solution in Javascript

```javascript
function busyStudent(startTime, endTime, queryTime) {
    let count = 0;
    for (let i = 0; i < startTime.length; i++) {
        if (startTime[i] <= queryTime && endTime[i] >= queryTime) {
            count++;
        }
    }
    return count;
}
```
The algorithm consists of iterating through the startTime and endTime arrays in parallel, by checking if the queryTime lies within the range of startTime[i] and endTime[i]. If it's within the range, increment the count. Finally, return the count as the result. The code is quite similar across the different languages.


# Maximum Number of Coins You Can Get

- slug: maximum-number-of-coins-you-can-get
- difficulty: Medium

There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows:

*   In each step, you will choose **any** `3` piles of coins (not necessarily consecutive).
*   Of your choice, Alice will pick the pile with the maximum number of coins.
*   You will pick the next pile with the maximum number of coins.
*   Your friend Bob will pick the last pile.
*   Repeat until there are no more piles of coins.

Given an array of integers `piles` where `piles[i]` is the number of coins in the `ith` pile.

Return the maximum number of coins that you can have.

**Example 1:**

**Input:** piles = \[2,4,1,2,7,8\]
**Output:** 9
**Explanation:** Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with **7** coins and Bob the last one.
Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with **2** coins and Bob the last one.
The maximum number of coins which you can have are: 7 + 2 = 9.
On the other hand if we choose this arrangement (1, **2**, 8), (2, **4**, 7) you only get 2 + 4 = 6 coins which is not optimal.

**Example 2:**

**Input:** piles = \[2,4,5\]
**Output:** 4

**Example 3:**

**Input:** piles = \[9,8,7,6,5,1,2,3,4\]
**Output:** 18

**Constraints:**

*   `3 <= piles.length <= 105`
*   `piles.length % 3 == 0`
*   `1 <= piles[i] <= 104`

## A solution in Java

```java
import java.util.Arrays;

public class Main {
    public static String arrangeWords(String text) {
        String[] words = text.toLowerCase().split(" ");
        Arrays.sort(words, (a, b) -> a.length() - b.length());
        words[0] = Character.toUpperCase(words[0].charAt(0)) + words[0].substring(1);
        return String.join(" ", words);
    }
}
```
1. First, convert the first character of `text` to lowercase.
2. Split the `text` into an array or vector of words based on the space character.
3. Sort the words by their length using the `sort` or `stable_sort` function. The stable sort preservers the relative order of the elements with same length.
4. Change the first character of the first word to uppercase.
5. Join the words with a space separator and return the resulting string.

## A solution in C++

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

std::string arrangeWords(std::string text) {
    text[0] = tolower(text[0]);
    std::istringstream iss(text);
    std::vector<std::pair<std::string, int>> words;
    std::string word;
    int i = 0;
    while (iss >> word) {
        words.emplace_back(word, i++);
    }
    std::stable_sort(words.begin(), words.end(), [](const auto &a, const auto &b) {
        return a.first.length() < b.first.length();
    });
    std::ostringstream oss;
    for (const auto &w : words) {
        if (&w != &words[0]) oss << ' ';
        oss << w.first;
    }
    auto result = oss.str();
    result[0] = toupper(result[0]);
    return result;
}
```
1. First, convert the first character of `text` to lowercase.
2. Split the `text` into an array or vector of words based on the space character.
3. Sort the words by their length using the `sort` or `stable_sort` function. The stable sort preservers the relative order of the elements with same length.
4. Change the first character of the first word to uppercase.
5. Join the words with a space separator and return the resulting string.

## A solution in Python

```python
def arrangeWords(text: str) -> str:
    words = text.split()
    words[0] = words[0].lower()
    words.sort(key=len)
    words[0] = words[0].capitalize()
    return ' '.join(words)
```
1. First, convert the first character of `text` to lowercase.
2. Split the `text` into an array or vector of words based on the space character.
3. Sort the words by their length using the `sort` or `stable_sort` function. The stable sort preservers the relative order of the elements with same length.
4. Change the first character of the first word to uppercase.
5. Join the words with a space separator and return the resulting string.

## A solution in Javascript

```javascript
function arrangeWords(text) {
    const words = text.toLowerCase().split(' ').sort((a, b) => a.length - b.length);
    words[0] = words[0].charAt(0).toUpperCase() + words[0].slice(1);
    return words.join(' ');
}
```
1. First, convert the first character of `text` to lowercase.
2. Split the `text` into an array or vector of words based on the space character.
3. Sort the words by their length using the `sort` or `stable_sort` function. The stable sort preservers the relative order of the elements with same length.
4. Change the first character of the first word to uppercase.
5. Join the words with a space separator and return the resulting string.