# Count Items Matching a Rule

- slug: count-items-matching-a-rule
- difficulty: Easy

You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.

The `ith` item is said to match the rule if **one** of the following is true:

*   `ruleKey == "type "` and `ruleValue == typei`.
*   `ruleKey == "color "` and `ruleValue == colori`.
*   `ruleKey == "name "` and `ruleValue == namei`.

Return _the number of items that match the given rule_.

**Example 1:**

**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "lenovo "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey =  "color ", ruleValue =  "silver "
**Output:** 1
**Explanation:** There is only one item matching the given rule, which is \[ "computer ", "silver ", "lenovo "\].

**Example 2:**

**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "phone "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey =  "type ", ruleValue =  "phone "
**Output:** 2
**Explanation:** There are only two items matching the given rule, which are \[ "phone ", "blue ", "pixel "\] and \[ "phone ", "gold ", "iphone "\]. Note that the item \[ "computer ", "silver ", "phone "\] does not match.

**Constraints:**

*   `1 <= items.length <= 104`
*   `1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10`
*   `ruleKey` is equal to either `"type "`, `"color "`, or `"name "`.
*   All strings consist only of lowercase letters.

## A solution in Java

```java
import java.util.List;

public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
    int count = 0;
    int index = ruleKey.equals("type") ? 0 : (ruleKey.equals("color") ? 1 : 2);
    for (List<String> item : items) {
        if (item.get(index).equals(ruleValue))
            count++;
    }
    return count;
}
```
The algorithm first finds the index of the attribute to be compared based on the `ruleKey`. Then, it iterates over the `items` array and compares the attribute at the calculated index with `ruleValue`. If there is a match, it increments a `count` variable. Finally, it returns the `count` representing the number of items matching the given rule.

## A solution in C++

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

int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
    int count = 0;
    int index = (ruleKey == "type" ? 0 : (ruleKey == "color" ? 1 : 2));
    for (const auto& item : items) {
        if (item[index] == ruleValue)
            count++;
    }
    return count;
}
```
The algorithm first finds the index of the attribute to be compared based on the `ruleKey`. Then, it iterates over the `items` array and compares the attribute at the calculated index with `ruleValue`. If there is a match, it increments a `count` variable. Finally, it returns the `count` representing the number of items matching the given rule.

## A solution in Python

```python
def countMatches(items, ruleKey, ruleValue):
    count = 0
    index = {"type": 0, "color": 1, "name": 2}[ruleKey]
    for item in items:
        if item[index] == ruleValue:
            count += 1
    return count
```
The algorithm first finds the index of the attribute to be compared based on the `ruleKey`. Then, it iterates over the `items` array and compares the attribute at the calculated index with `ruleValue`. If there is a match, it increments a `count` variable. Finally, it returns the `count` representing the number of items matching the given rule.

## A solution in Javascript

```javascript
function countMatches(items, ruleKey, ruleValue) {
    let count = 0;
    let index = ruleKey === "type" ? 0 : (ruleKey === "color" ? 1 : 2);
    for (let item of items) {
        if (item[index] === ruleValue)
            count++;
    }
    return count;
}
```
The algorithm first finds the index of the attribute to be compared based on the `ruleKey`. Then, it iterates over the `items` array and compares the attribute at the calculated index with `ruleValue`. If there is a match, it increments a `count` variable. Finally, it returns the `count` representing the number of items matching the given rule.


# Closest Dessert Cost

- slug: closest-dessert-cost
- difficulty: Medium

You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:

*   There must be **exactly one** ice cream base.
*   You can add **one or more** types of topping or have no toppings at all.
*   There are **at most two** of **each type** of topping.

You are given three inputs:

*   `baseCosts`, an integer array of length `n`, where each `baseCosts[i]` represents the price of the `ith` ice cream base flavor.
*   `toppingCosts`, an integer array of length `m`, where each `toppingCosts[i]` is the price of **one** of the `ith` topping.
*   `target`, an integer representing your target price for dessert.

You want to make a dessert with a total cost as close to `target` as possible.

Return _the closest possible cost of the dessert to_ `target`. If there are multiple, return _the **lower** one._

**Example 1:**

**Input:** baseCosts = \[1,7\], toppingCosts = \[3,4\], target = 10
**Output:** 10
**Explanation:** Consider the following combination (all 0-indexed):
- Choose base 1: cost 7
- Take 1 of topping 0: cost 1 x 3 = 3
- Take 0 of topping 1: cost 0 x 4 = 0
Total: 7 + 3 + 0 = 10.

**Example 2:**

**Input:** baseCosts = \[2,3\], toppingCosts = \[4,5,100\], target = 18
**Output:** 17
**Explanation:** Consider the following combination (all 0-indexed):
- Choose base 1: cost 3
- Take 1 of topping 0: cost 1 x 4 = 4
- Take 2 of topping 1: cost 2 x 5 = 10
- Take 0 of topping 2: cost 0 x 100 = 0
Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.

**Example 3:**

**Input:** baseCosts = \[3,10\], toppingCosts = \[2,5\], target = 9
**Output:** 8
**Explanation:** It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.

**Constraints:**

*   `n == baseCosts.length`
*   `m == toppingCosts.length`
*   `1 <= n, m <= 10`
*   `1 <= baseCosts[i], toppingCosts[i] <= 104`
*   `1 <= target <= 104`

## A solution in Java

```java
import java.util.Arrays;

public int closestCost(int[] baseCosts, int[] toppingCosts, int target) {
    int closest = Integer.MAX_VALUE;
    Arrays.sort(toppingCosts);

    for (int base : baseCosts) {
        int diff = Math.abs(target - base);
        if (diff < closest) {
            closest = diff;
        }
        if (diff == 0) {
            return target;
        }
        for (int t0 = 0; t0 <= 2; t0++) {
            int x1 = base + t0 * toppingCosts[0];
            int diff1 = Math.abs(target - x1);
            if (diff1 < closest) {
                closest = diff1;
            }
            if (diff1 == 0) {
                return target;
            }
            for (int t1 = 0; t1 <= 2; t1++) {
                int x2 = x1 + t1 * toppingCosts[1];
                int diff2 = Math.abs(target - x2);
                if (diff2 < closest) {
                    closest = diff2;
                }
                if (diff2 == 0) {
                    return target;
                }
            }
        }
    }
    return target - closest;
}
```
To solve this problem, we can use depth-first search (DFS) to explore all possible combinations of toppings for each base. The Python solution uses a different approach to generate all possible topping combinations using itertools.product, and then iterates through each combination to find the closest cost.

1. Initialize the `closest` variable as a large number (infinity for Python and JavaScript, the maximum integer value for C++ and Java).
2. If needed, sort the `toppingCosts` array (not necessary in Python and JavaScript since they use a different approach).
3. For each base cost in the `baseCosts` array, calculate the absolute difference (`diff`) between the target and the base cost, update the `closest` variable if the current difference is smaller than the previous minimum difference. If the difference is zero, return the target as the result.
4. Using a nested loop or recursive DFS approach, iterate through all possible topping combinations for the current base cost, updating the closest difference as needed.
5. Return the result as `target - closest`.

Note: The Python solution uses `itertools.product` to generate all possible topping combinations, then iterates through the combinations to calculate their costs and find the closest cost. The JavaScript solution uses a recursive DFS approach which is similar to the C++ and Java solutions.

## A solution in C++

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

int closestCost(std::vector<int>& baseCosts, std::vector<int>& toppingCosts, int target) {
    int closest = std::numeric_limits<int>::max();
    std::sort(toppingCosts.begin(), toppingCosts.end());

    for (const int& base : baseCosts) {
        int diff = abs(target - base);
        if (diff < closest) {
            closest = diff;
        }
        if (diff == 0) {
            return target;
        }
        for (int t0 = 0; t0 <= 2; ++t0) {
            int x1 = base + t0 * toppingCosts[0];
            int diff1 = abs(target - x1);
            if (diff1 < closest) {
                closest = diff1;
            }
            if (diff1 == 0) {
                return target;
            }
            for (int t1 = 0; t1 <= 2; ++t1) {
                int x2 = x1 + t1 * toppingCosts[1];
                int diff2 = abs(target - x2);
                if (diff2 < closest) {
                    closest = diff2;
                }
                if (diff2 == 0) {
                    return target;
                }
            }
        }
    }
    return target - closest;
}
```
To solve this problem, we can use depth-first search (DFS) to explore all possible combinations of toppings for each base. The Python solution uses a different approach to generate all possible topping combinations using itertools.product, and then iterates through each combination to find the closest cost.

1. Initialize the `closest` variable as a large number (infinity for Python and JavaScript, the maximum integer value for C++ and Java).
2. If needed, sort the `toppingCosts` array (not necessary in Python and JavaScript since they use a different approach).
3. For each base cost in the `baseCosts` array, calculate the absolute difference (`diff`) between the target and the base cost, update the `closest` variable if the current difference is smaller than the previous minimum difference. If the difference is zero, return the target as the result.
4. Using a nested loop or recursive DFS approach, iterate through all possible topping combinations for the current base cost, updating the closest difference as needed.
5. Return the result as `target - closest`.

Note: The Python solution uses `itertools.product` to generate all possible topping combinations, then iterates through the combinations to calculate their costs and find the closest cost. The JavaScript solution uses a recursive DFS approach which is similar to the C++ and Java solutions.

## A solution in Python

```python
from itertools import product

def closest_cost(base_costs, topping_costs, target):
    closest = float('inf')
    topping_combinations = list(product([0, 1, 2], repeat=len(topping_costs)))

    for base in base_costs:
        for combination in topping_combinations:
            combination_cost = sum(x * y for x, y in zip(topping_costs, combination))
            diff = abs(target - (base + combination_cost))
            if diff < closest:
                closest = diff
            if diff == 0:
                return target

    return target - closest
```
To solve this problem, we can use depth-first search (DFS) to explore all possible combinations of toppings for each base. The Python solution uses a different approach to generate all possible topping combinations using itertools.product, and then iterates through each combination to find the closest cost.

1. Initialize the `closest` variable as a large number (infinity for Python and JavaScript, the maximum integer value for C++ and Java).
2. If needed, sort the `toppingCosts` array (not necessary in Python and JavaScript since they use a different approach).
3. For each base cost in the `baseCosts` array, calculate the absolute difference (`diff`) between the target and the base cost, update the `closest` variable if the current difference is smaller than the previous minimum difference. If the difference is zero, return the target as the result.
4. Using a nested loop or recursive DFS approach, iterate through all possible topping combinations for the current base cost, updating the closest difference as needed.
5. Return the result as `target - closest`.

Note: The Python solution uses `itertools.product` to generate all possible topping combinations, then iterates through the combinations to calculate their costs and find the closest cost. The JavaScript solution uses a recursive DFS approach which is similar to the C++ and Java solutions.

## A solution in Javascript

```javascript
function closestCost(baseCosts, toppingCosts, target) {
    let closest = Infinity;

    function dfs(index, cost) {
        if (index === toppingCosts.length || cost >= target + closest) {
            closest = Math.min(closest, Math.abs(cost - target));
            return;
        }

        dfs(index + 1, cost);
        dfs(index + 1, cost + toppingCosts[index]);
        dfs(index + 1, cost + 2 * toppingCosts[index]);
    }

    for (const base of baseCosts) {
        dfs(0, base);
    }

    return target - (closest > target ? -closest : closest);
}
```
To solve this problem, we can use depth-first search (DFS) to explore all possible combinations of toppings for each base. The Python solution uses a different approach to generate all possible topping combinations using itertools.product, and then iterates through each combination to find the closest cost.

1. Initialize the `closest` variable as a large number (infinity for Python and JavaScript, the maximum integer value for C++ and Java).
2. If needed, sort the `toppingCosts` array (not necessary in Python and JavaScript since they use a different approach).
3. For each base cost in the `baseCosts` array, calculate the absolute difference (`diff`) between the target and the base cost, update the `closest` variable if the current difference is smaller than the previous minimum difference. If the difference is zero, return the target as the result.
4. Using a nested loop or recursive DFS approach, iterate through all possible topping combinations for the current base cost, updating the closest difference as needed.
5. Return the result as `target - closest`.

Note: The Python solution uses `itertools.product` to generate all possible topping combinations, then iterates through the combinations to calculate their costs and find the closest cost. The JavaScript solution uses a recursive DFS approach which is similar to the C++ and Java solutions.


# Equal Sum Arrays With Minimum Number of Operations

- slug: equal-sum-arrays-with-minimum-number-of-operations
- difficulty: Medium

You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.

In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.

Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1` if it is not possible to make the sum of the two arrays equal.

**Example 1:**

**Input:** nums1 = \[1,2,3,4,5,6\], nums2 = \[1,1,2,2,2,2\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2\[0\] to 6. nums1 = \[1,2,3,4,5,6\], nums2 = \[**6**,1,2,2,2,2\].
- Change nums1\[5\] to 1. nums1 = \[1,2,3,4,5,**1**\], nums2 = \[6,1,2,2,2,2\].
- Change nums1\[2\] to 2. nums1 = \[1,2,**2**,4,5,1\], nums2 = \[6,1,2,2,2,2\].

**Example 2:**

**Input:** nums1 = \[1,1,1,1,1,1,1\], nums2 = \[6\]
**Output:** -1
**Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.

**Example 3:**

**Input:** nums1 = \[6,6\], nums2 = \[1\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1\[0\] to 2. nums1 = \[**2**,6\], nums2 = \[1\].
- Change nums1\[1\] to 2. nums1 = \[2,**2**\], nums2 = \[1\].
- Change nums2\[0\] to 4. nums1 = \[2,2\], nums2 = \[**4**\].

**Constraints:**

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

## A solution in Java

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

public class OrderedStream {
    private int ptr;
    private HashMap<Integer, String> data;

    public OrderedStream(int n) {
        ptr = 1;
        data = new HashMap<>();
    }

    public List<String> insert(int idKey, String value) {
        data.put(idKey, value);
        List<String> result = new ArrayList<>();
        while (data.containsKey(ptr)) {
            result.add(data.get(ptr));
            ptr++;
        }
        return result;
    }
}
```
The algorithm follows the design of a class called `OrderedStream` that creates an object with two instance variables: `ptr` and `data`. The `ptr` variable is initialized to 1 and represents the next ID we expect to process. The `data` variable is a hash map that will store the values for each ID in the data stream.
The `insert` method receives an ID and a value as arguments. When a new (idKey, value) pair arrives, the value is stored in the hash map with the idKey as the key.
Then we initialize an empty list called `result` and start a loop to check if the `ptr` ID exists in the hash map. If it exists, we add its value to the `result` list and increment the ptr by 1, indicating that we have processed that ID. This loop continues until we cannot find the next ID in the data stream. Finally, we return the `result` list.

The concatenation of all the chunks from the returned lists will result in a list of the sorted values as per the required increasing order of their IDs.

## A solution in C++

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

class OrderedStream {
public:
    int ptr;
    unordered_map<int, string> data;

    OrderedStream(int n) {
        ptr = 1;
    }

    vector<string> insert(int id, string value) {
        data[id] = value;
        vector<string> result;
        while (data.find(ptr) != data.end()) {
            result.push_back(data[ptr]);
            ptr++;
        }
        return result;
    }
};
```
The algorithm follows the design of a class called `OrderedStream` that creates an object with two instance variables: `ptr` and `data`. The `ptr` variable is initialized to 1 and represents the next ID we expect to process. The `data` variable is a hash map that will store the values for each ID in the data stream.
The `insert` method receives an ID and a value as arguments. When a new (idKey, value) pair arrives, the value is stored in the hash map with the idKey as the key.
Then we initialize an empty list called `result` and start a loop to check if the `ptr` ID exists in the hash map. If it exists, we add its value to the `result` list and increment the ptr by 1, indicating that we have processed that ID. This loop continues until we cannot find the next ID in the data stream. Finally, we return the `result` list.

The concatenation of all the chunks from the returned lists will result in a list of the sorted values as per the required increasing order of their IDs.

## A solution in Python

```python
class OrderedStream:
    def __init__(self, n: int):
        self.ptr = 1
        self.data = {}

    def insert(self, idKey: int, value: str):
        self.data[idKey] = value
        result = []
        while self.ptr in self.data:
            result.append(self.data[self.ptr])
            self.ptr += 1
        return result
```
The algorithm follows the design of a class called `OrderedStream` that creates an object with two instance variables: `ptr` and `data`. The `ptr` variable is initialized to 1 and represents the next ID we expect to process. The `data` variable is a hash map that will store the values for each ID in the data stream.
The `insert` method receives an ID and a value as arguments. When a new (idKey, value) pair arrives, the value is stored in the hash map with the idKey as the key.
Then we initialize an empty list called `result` and start a loop to check if the `ptr` ID exists in the hash map. If it exists, we add its value to the `result` list and increment the ptr by 1, indicating that we have processed that ID. This loop continues until we cannot find the next ID in the data stream. Finally, we return the `result` list.

The concatenation of all the chunks from the returned lists will result in a list of the sorted values as per the required increasing order of their IDs.

## A solution in Javascript

```javascript
class OrderedStream {
    constructor(n) {
        this.ptr = 1;
        this.data = {};
    }

    insert(idKey, value) {
        this.data[idKey] = value;
        let result = [];
        while (this.data[this.ptr]) {
            result.push(this.data[this.ptr]);
            this.ptr++;
        }
        return result;
    }
}
```
The algorithm follows the design of a class called `OrderedStream` that creates an object with two instance variables: `ptr` and `data`. The `ptr` variable is initialized to 1 and represents the next ID we expect to process. The `data` variable is a hash map that will store the values for each ID in the data stream.
The `insert` method receives an ID and a value as arguments. When a new (idKey, value) pair arrives, the value is stored in the hash map with the idKey as the key.
Then we initialize an empty list called `result` and start a loop to check if the `ptr` ID exists in the hash map. If it exists, we add its value to the `result` list and increment the ptr by 1, indicating that we have processed that ID. This loop continues until we cannot find the next ID in the data stream. Finally, we return the `result` list.

The concatenation of all the chunks from the returned lists will result in a list of the sorted values as per the required increasing order of their IDs.


# Car Fleet II

- slug: car-fleet-ii
- difficulty: Hard

There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:

*   `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < positioni+1`.
*   `speedi` is the initial speed of the `ith` car in meters per second.

For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the **slowest** car in the fleet.

Return an array `answer`, where `answer[i]` is the time, in seconds, at which the `ith` car collides with the next car, or `-1` if the car does not collide with the next car. Answers within `10-5` of the actual answers are accepted.

**Example 1:**

**Input:** cars = \[\[1,2\],\[2,1\],\[4,3\],\[7,2\]\]
**Output:** \[1.00000,-1.00000,3.00000,-1.00000\]
**Explanation:** After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.

**Example 2:**

**Input:** cars = \[\[3,4\],\[5,4\],\[6,3\],\[9,1\]\]
**Output:** \[2.00000,1.00000,1.50000,-1.00000\]

**Constraints:**

*   `1 <= cars.length <= 105`
*   `1 <= positioni, speedi <= 106`
*   `positioni < positioni+1`

## A solution in Java

```java
public int minOperations(int[] nums, int x) {
    int total = 0;
    for (int num : nums) total += num;
    int target = total - x;
    if (target < 0) return -1;

    int maxLength = -1;
    int left = 0, sum = 0;
    for (int right = 0; right < nums.length; ++right) {
        sum += nums[right];

        while (sum > target) {
            sum -= nums[left++];
        }

        if (sum == target) {
            maxLength = Math.max(maxLength, right - left + 1);
        }
    }

    return maxLength == -1 ? -1 : nums.length - maxLength;
}
```
The algorithm works by first calculating the total sum of the array and finding the target sum we need to achieve by subtracting x from the total sum. If the target sum is less than 0, return -1 since it's not possible to reduce x to 0.

Next, initialize two pointers (left and right) to 0 and the sum variable to 0. Iterate through the array nums with the right pointer, updating the sum by adding the current element in the nums array.

Inside the loop, keep updating the left pointer by removing the leftmost element of the subarray and subtracting its value from the sum until the sum is less than or equal to target.

If the sum is equal to the target, update maxLength to the maximum value between maxLength and the difference between right and left pointers.

Once the whole nums array has been processed, return -1 when maxLength remains -1 or the difference between the size of nums and maxLength as a result.

The algorithm has a time complexity of O(n), where n is the size of the nums array.

## A solution in C++

```cpp
int minOperations(vector<int>& nums, int x) {
    int total = accumulate(nums.begin(), nums.end(), 0);
    int target = total - x;
    if (target < 0) return -1;

    int maxLength = -1;
    int left = 0, sum = 0;
    for (int right = 0; right < nums.size(); ++right) {
      sum += nums[right];

      while (sum > target) {
        sum -= nums[left++];
      }

      if (sum == target) {
        maxLength = max(maxLength, right - left + 1);
      }
    }

    return maxLength == -1 ? -1 : nums.size() - maxLength;
}
```
The algorithm works by first calculating the total sum of the array and finding the target sum we need to achieve by subtracting x from the total sum. If the target sum is less than 0, return -1 since it's not possible to reduce x to 0.

Next, initialize two pointers (left and right) to 0 and the sum variable to 0. Iterate through the array nums with the right pointer, updating the sum by adding the current element in the nums array.

Inside the loop, keep updating the left pointer by removing the leftmost element of the subarray and subtracting its value from the sum until the sum is less than or equal to target.

If the sum is equal to the target, update maxLength to the maximum value between maxLength and the difference between right and left pointers.

Once the whole nums array has been processed, return -1 when maxLength remains -1 or the difference between the size of nums and maxLength as a result.

The algorithm has a time complexity of O(n), where n is the size of the nums array.

## A solution in Python

```python
def minOperations(nums, x):
    total = sum(nums)
    target = total - x
    if target < 0:
        return -1

    maxLength = -1
    left = 0
    current_sum = 0

    for right in range(len(nums)):
        current_sum += nums[right]

        while current_sum > target:
            current_sum -= nums[left]
            left += 1

        if current_sum == target:
            maxLength = max(maxLength, right - left + 1)

    return -1 if maxLength == -1 else len(nums) - maxLength
```
The algorithm works by first calculating the total sum of the array and finding the target sum we need to achieve by subtracting x from the total sum. If the target sum is less than 0, return -1 since it's not possible to reduce x to 0.

Next, initialize two pointers (left and right) to 0 and the sum variable to 0. Iterate through the array nums with the right pointer, updating the sum by adding the current element in the nums array.

Inside the loop, keep updating the left pointer by removing the leftmost element of the subarray and subtracting its value from the sum until the sum is less than or equal to target.

If the sum is equal to the target, update maxLength to the maximum value between maxLength and the difference between right and left pointers.

Once the whole nums array has been processed, return -1 when maxLength remains -1 or the difference between the size of nums and maxLength as a result.

The algorithm has a time complexity of O(n), where n is the size of the nums array.

## A solution in Javascript

```javascript
function minOperations(nums, x) {
    const total = nums.reduce((accumulator, currentValue) => accumulator + currentValue);
    const target = total - x;
    if (target < 0) return -1;

    let maxLength = -1;
    let left = 0, sum = 0;

    for (let right = 0; right < nums.length; ++right) {
        sum += nums[right];

        while (sum > target) {
            sum -= nums[left++];
        }

        if (sum == target) {
            maxLength = Math.max(maxLength, right - left + 1);
        }
    }

    return maxLength == -1 ? -1 : nums.length - maxLength;
}
```
The algorithm works by first calculating the total sum of the array and finding the target sum we need to achieve by subtracting x from the total sum. If the target sum is less than 0, return -1 since it's not possible to reduce x to 0.

Next, initialize two pointers (left and right) to 0 and the sum variable to 0. Iterate through the array nums with the right pointer, updating the sum by adding the current element in the nums array.

Inside the loop, keep updating the left pointer by removing the leftmost element of the subarray and subtracting its value from the sum until the sum is less than or equal to target.

If the sum is equal to the target, update maxLength to the maximum value between maxLength and the difference between right and left pointers.

Once the whole nums array has been processed, return -1 when maxLength remains -1 or the difference between the size of nums and maxLength as a result.

The algorithm has a time complexity of O(n), where n is the size of the nums array.


# Shortest Path in a Hidden Grid

- slug: shortest-path-in-a-hidden-grid
- difficulty: Medium

This is an **interactive problem**.

There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size `m x n`, and each cell in the grid is either empty or blocked. It is **guaranteed** that the starting cell and the target cell are different, and neither of them is blocked.

You want to find the minimum distance to the target cell. However, you **do not know** the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the `GridMaster` object.

Thr `GridMaster` class has the following functions:

*   `boolean canMove(char direction)` Returns `true` if the robot can move in that direction. Otherwise, it returns `false`.
*   `void move(char direction)` Moves the robot in that direction. If this move would move the robot to a blocked cell or off the grid, the move will be **ignored**, and the robot will remain in the same position.
*   `boolean isTarget()` Returns `true` if the robot is currently on the target cell. Otherwise, it returns `false`.

Note that `direction` in the above functions should be a character from `{'U','D','L','R'}`, representing the directions up, down, left, and right, respectively.

Return _the **minimum distance** between the robot's initial starting cell and the target cell. If there is no valid path between the cells, return_ `-1`.

**Custom testing:**

The test input is read as a 2D matrix `grid` of size `m x n` where:

*   `grid[i][j] == -1` indicates that the robot is in cell `(i, j)` (the starting cell).
*   `grid[i][j] == 0` indicates that the cell `(i, j)` is blocked.
*   `grid[i][j] == 1` indicates that the cell `(i, j)` is empty.
*   `grid[i][j] == 2` indicates that the cell `(i, j)` is the target cell.

There is exactly one `-1` and `2` in `grid`. Remember that you will **not** have this information in your code.

**Example 1:**

**Input:** grid = \[\[1,2\],\[-1,0\]\]
**Output:** 2
**Explanation:** One possible interaction is described below:
The robot is initially standing on cell (1, 0), denoted by the -1.
- master.canMove('U') returns true.
- master.canMove('D') returns false.
- master.canMove('L') returns false.
- master.canMove('R') returns false.
- master.move('U') moves the robot to the cell (0, 0).
- master.isTarget() returns false.
- master.canMove('U') returns false.
- master.canMove('D') returns true.
- master.canMove('L') returns false.
- master.canMove('R') returns true.
- master.move('R') moves the robot to the cell (0, 1).
- master.isTarget() returns true.
We now know that the target is the cell (0, 1), and the shortest path to the target cell is 2.

**Example 2:**

**Input:** grid = \[\[0,0,-1\],\[1,1,1\],\[2,0,0\]\]
**Output:** 4
**Explanation:** The minimum distance between the robot and the target cell is 4.

**Example 3:**

**Input:** grid = \[\[-1,0\],\[0,2\]\]
**Output:** -1
**Explanation:** There is no path from the robot to the target cell.

**Constraints:**

*   `1 <= n, m <= 500`
*   `m == grid.length`
*   `n == grid[i].length`
*   `grid[i][j]` is either `-1`, `0`, `1`, or `2`.
*   There is **exactly one** `-1` in `grid`.
*   There is **exactly one** `2` in `grid`.

## A solution in Java

```java
int[][][][] dp = new int[6][6][37][64];
boolean[][][][] seen = new boolean[6][6][37][64];

int maxHappy(int m, int n, int introvertsCount, int extrovertsCount, int y, int mask) {
    if (y == n)
        return 0;

    if (seen[m][n][introvertsCount][mask])
        return dp[m][n][introvertsCount][mask];
    seen[m][n][introvertsCount][mask] = true;

    int cur = y * m, ans = 0;
    for (int x = 0; x <= m; ++x) {
        int happiness = 0;
        if ((mask >> x) & 1) {
            happiness -= 30;
            if (x > 0 && (mask & 1))
                happiness -= 30;
            else
                happiness += 20;
        }
        ans = Math.max(ans, happiness + maxHappy(m, n, introvertsCount, extrovertsCount, y + 1, (mask | (1 << x)) >> 1));
    }

    return dp[m][n][introvertsCount][mask] = ans;
}

int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) {
    return maxHappy(m, n, introvertsCount, extrovertsCount, 0, 0);
}
```
We use a dynamic programming approach to solve this problem.
1. First we define the function maxHappy(y, mask) to find the maximum happiness.
2. We loop through all possible "x" values (i.e., we loop through all the cells in the m * n grid).
3. For each "x" value, we calculate the happiness.
4. We decide whether to add an introvert or extrovert in the current cell.
5. We add the happiness of that person and call the function maxHappy() recursively for next row.
6. We cache the result of maxHappy() to avoid redundant calculations.
7. The result will be the maximum happiness of the grid.

The main function getMaxGridHappiness() initializes the required values and calls the maxHappy() function.

## A solution in C++

```cpp
int maxHappy(int m, int n, int introvertsCount, int extrovertsCount, int y = 0, int mask = 0) {
    if (y == n)
        return 0;

    static int dp[6][6][6 * 6][1 << 6];
    static bool seen[6][6][6 * 6][1 << 6] = {};
    if (seen[m][n][introvertsCount][mask])
        return dp[m][n][introvertsCount][mask];
    seen[m][n][introvertsCount][mask] = true;

    int cur = y * m, ans = 0;
    for (int x = 0; x <= m; ++x) {
        int happiness = 0;
        if ((mask >> x) & 1) {
            happiness -= 30;
            if (x > 0 && (mask & 1))
                happiness -= 30;
            else
                happiness += 20;
        }
        ans = max(ans, happiness + maxHappy(m, n, introvertsCount, extrovertsCount, y + 1, (mask | (1 << x)) >> 1));
    }

    return dp[m][n][introvertsCount][mask] = ans;
}

int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) {
    return maxHappy(m, n, introvertsCount, extrovertsCount);
}
```
We use a dynamic programming approach to solve this problem.
1. First we define the function maxHappy(y, mask) to find the maximum happiness.
2. We loop through all possible "x" values (i.e., we loop through all the cells in the m * n grid).
3. For each "x" value, we calculate the happiness.
4. We decide whether to add an introvert or extrovert in the current cell.
5. We add the happiness of that person and call the function maxHappy() recursively for next row.
6. We cache the result of maxHappy() to avoid redundant calculations.
7. The result will be the maximum happiness of the grid.

The main function getMaxGridHappiness() initializes the required values and calls the maxHappy() function.

## A solution in Python

```python
from functools import lru_cache

def getMaxGridHappiness(m, n, introvertsCount, extrovertsCount):
    @lru_cache(None)
    def maxHappy(y, mask):
        if y == n:
            return 0

        ans = 0
        for x in range(m + 1):
            happiness = 0
            if mask >> x & 1:
                happiness -= 30
                if x > 0 and mask & 1:
                    happiness -= 30
                else:
                    happiness += 20
            ans = max(ans, happiness + maxHappy(y + 1, (mask | (1 << x)) >> 1))

        return ans

    return maxHappy(0, 0)
```
We use a dynamic programming approach to solve this problem.
1. First we define the function maxHappy(y, mask) to find the maximum happiness.
2. We loop through all possible "x" values (i.e., we loop through all the cells in the m * n grid).
3. For each "x" value, we calculate the happiness.
4. We decide whether to add an introvert or extrovert in the current cell.
5. We add the happiness of that person and call the function maxHappy() recursively for next row.
6. We cache the result of maxHappy() to avoid redundant calculations.
7. The result will be the maximum happiness of the grid.

The main function getMaxGridHappiness() initializes the required values and calls the maxHappy() function.

## A solution in Javascript

```javascript
function getMaxGridHappiness(m, n, introvertsCount, extrovertsCount) {
    const dp = Array.from({ length: 6 }, () => Array.from({ length: 6 }, () => Array.from({ length: 37 }, () => Array(64).fill(0))));
    const seen = Array.from({ length: 6 }, () => Array.from({ length: 6 }, () => Array.from({ length: 37 }, () => Array(64).fill(false))));

    function maxHappy(y, mask) {
        if (y == n)
            return 0;

        if (seen[m][n][introvertsCount][mask])
            return dp[m][n][introvertsCount][mask];
        seen[m][n][introvertsCount][mask] = true;

        let ans = 0;
        for (let x = 0; x <= m; ++x) {
            let happiness = 0;
            if (mask >> x & 1) {
                happiness -= 30;
                if (x > 0 && mask & 1)
                    happiness -= 30;
                else
                    happiness += 20;
            }
            ans = Math.max(ans, happiness + maxHappy(y + 1, (mask | (1 << x)) >> 1));
        }

        return dp[m][n][introvertsCount][mask] = ans;
    }

    return maxHappy(0, 0);
}
```
We use a dynamic programming approach to solve this problem.
1. First we define the function maxHappy(y, mask) to find the maximum happiness.
2. We loop through all possible "x" values (i.e., we loop through all the cells in the m * n grid).
3. For each "x" value, we calculate the happiness.
4. We decide whether to add an introvert or extrovert in the current cell.
5. We add the happiness of that person and call the function maxHappy() recursively for next row.
6. We cache the result of maxHappy() to avoid redundant calculations.
7. The result will be the maximum happiness of the grid.

The main function getMaxGridHappiness() initializes the required values and calls the maxHappy() function.


# Find Nearest Point That Has the Same X or Y Coordinate

- slug: find-nearest-point-that-has-the-same-x-or-y-coordinate
- difficulty: Easy

You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location.

Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`.

The **Manhattan distance** between two points `(x1, y1)` and `(x2, y2)` is `abs(x1 - x2) + abs(y1 - y2)`.

**Example 1:**

**Input:** x = 3, y = 4, points = \[\[1,2\],\[3,1\],\[2,4\],\[2,3\],\[4,4\]\]
**Output:** 2
**Explanation:** Of all the points, only \[3,1\], \[2,4\] and \[4,4\] are valid. Of the valid points, \[2,4\] and \[4,4\] have the smallest Manhattan distance from your current location, with a distance of 1. \[2,4\] has the smallest index, so return 2.

**Example 2:**

**Input:** x = 3, y = 4, points = \[\[3,4\]\]
**Output:** 0
**Explanation:** The answer is allowed to be on the same location as your current location.

**Example 3:**

**Input:** x = 3, y = 4, points = \[\[2,3\]\]
**Output:** -1
**Explanation:** There are no valid points.

**Constraints:**

*   `1 <= points.length <= 104`
*   `points[i].length == 2`
*   `1 <= x, y, ai, bi <= 104`

## A solution in Java

```java
public int nearestValidPoint(int x, int y, int[][] points) {
    int min_distance = Integer.MAX_VALUE, index = -1;
    for (int i = 0; i < points.length; i++) {
        if (x == points[i][0] || y == points[i][1]) {
            int distance = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]);
            if (distance < min_distance) {
                min_distance = distance;
                index = i;
            }
        }
    }
    return index;
}
```
Iterate through each point in the `points` array, checking if its x or y coordinate is the same as the input x or y coordinate, making the point a valid point. If the point is valid, calculate the Manhattan distance between the input point and the current point. If the calculated distance is smaller than the current minimum distance, update the minimum distance and store the index of the current point. After iterating through all points, return the index of the point with the smallest Manhattan distance. If no point is valid, return -1.

## A solution in C++

```cpp
int nearestValidPoint(int x, int y, vector<vector<int>>& points) {
    int min_distance = INT_MAX, index = -1;
    for (int i = 0; i < points.size(); i++) {
        if (x == points[i][0] || y == points[i][1]) {
            int distance = abs(x - points[i][0]) + abs(y - points[i][1]);
            if (distance < min_distance) {
                min_distance = distance;
                index = i;
            }
        }
    }
    return index;
}
```
Iterate through each point in the `points` array, checking if its x or y coordinate is the same as the input x or y coordinate, making the point a valid point. If the point is valid, calculate the Manhattan distance between the input point and the current point. If the calculated distance is smaller than the current minimum distance, update the minimum distance and store the index of the current point. After iterating through all points, return the index of the point with the smallest Manhattan distance. If no point is valid, return -1.

## A solution in Python

```python
def nearestValidPoint(x: int, y: int, points: List[List[int]]) -> int:
    min_distance = float("inf")
    index = -1
    for i, point in enumerate(points):
        if x == point[0] or y == point[1]:
            distance = abs(x - point[0]) + abs(y - point[1])
            if distance < min_distance:
                min_distance = distance
                index = i
    return index
```
Iterate through each point in the `points` array, checking if its x or y coordinate is the same as the input x or y coordinate, making the point a valid point. If the point is valid, calculate the Manhattan distance between the input point and the current point. If the calculated distance is smaller than the current minimum distance, update the minimum distance and store the index of the current point. After iterating through all points, return the index of the point with the smallest Manhattan distance. If no point is valid, return -1.

## A solution in Javascript

```javascript
function nearestValidPoint(x, y, points) {
    let min_distance = Number.MAX_VALUE, index = -1;
    for (let i = 0; i < points.length; i++) {
        if (x === points[i][0] || y === points[i][1]) {
            const distance = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]);
            if (distance < min_distance) {
                min_distance = distance;
                index = i;
            }
        }
    }
    return index;
}
```
Iterate through each point in the `points` array, checking if its x or y coordinate is the same as the input x or y coordinate, making the point a valid point. If the point is valid, calculate the Manhattan distance between the input point and the current point. If the calculated distance is smaller than the current minimum distance, update the minimum distance and store the index of the current point. After iterating through all points, return the index of the point with the smallest Manhattan distance. If no point is valid, return -1.


# Check if Number is a Sum of Powers of Three

- slug: check-if-number-is-a-sum-of-powers-of-three
- difficulty: Medium

Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.

An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.

**Example 1:**

**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32

**Example 2:**

**Input:** n = 91
**Output:** true
**Explanation:** 91 = 30 + 32 + 34

**Example 3:**

**Input:** n = 21
**Output:** false

**Constraints:**

*   `1 <= n <= 107`

## A solution in Java

```java
public boolean checkPowersOfThree(int n) {
    while (n > 0) {
        if (n % 3 == 2) return false;
        n /= 3;
    }
    return true;
}
```
The algorithm uses a simple approach by iteratively dividing the given number `n` by 3 (the base of the powers of three). During the division process, it checks if any of the remainders of division is 2. If it finds a remainder of 2 at any stage, it immediately returns `false` since having a 2 in the base-3 representation of the number indicates that it cannot be represented solely by distinct powers of three.

The time complexity of this algorithm is O(log n), as each iteration reduces the number by a factor of 3.

## A solution in C++

```cpp
bool checkPowersOfThree(int n) {
    while (n > 0) {
        if (n % 3 == 2) return false;
        n /= 3;
    }
    return true;
}
```
The algorithm uses a simple approach by iteratively dividing the given number `n` by 3 (the base of the powers of three). During the division process, it checks if any of the remainders of division is 2. If it finds a remainder of 2 at any stage, it immediately returns `false` since having a 2 in the base-3 representation of the number indicates that it cannot be represented solely by distinct powers of three.

The time complexity of this algorithm is O(log n), as each iteration reduces the number by a factor of 3.

## A solution in Python

```python
def check_powers_of_three(n: int) -> bool:
    while n > 0:
        if n % 3 == 2:
            return False
        n //= 3
    return True
```
The algorithm uses a simple approach by iteratively dividing the given number `n` by 3 (the base of the powers of three). During the division process, it checks if any of the remainders of division is 2. If it finds a remainder of 2 at any stage, it immediately returns `false` since having a 2 in the base-3 representation of the number indicates that it cannot be represented solely by distinct powers of three.

The time complexity of this algorithm is O(log n), as each iteration reduces the number by a factor of 3.

## A solution in Javascript

```javascript
function checkPowersOfThree(n) {
    while (n > 0) {
        if (n % 3 === 2) return false;
        n = Math.floor(n / 3);
    }
    return true;
}
```
The algorithm uses a simple approach by iteratively dividing the given number `n` by 3 (the base of the powers of three). During the division process, it checks if any of the remainders of division is 2. If it finds a remainder of 2 at any stage, it immediately returns `false` since having a 2 in the base-3 representation of the number indicates that it cannot be represented solely by distinct powers of three.

The time complexity of this algorithm is O(log n), as each iteration reduces the number by a factor of 3.


# Sum of Beauty of All Substrings

- slug: sum-of-beauty-of-all-substrings
- difficulty: Medium

The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters.

*   For example, the beauty of `"abaacc "` is `3 - 1 = 2`.

Given a string `s`, return _the sum of **beauty** of all of its substrings._

**Example 1:**

**Input:** s =  "aabcb "
**Output:** 5
**Explanation:** The substrings with non-zero beauty are \[ "aab ", "aabc ", "aabcb ", "abcb ", "bcb "\], each with beauty equal to 1.

**Example 2:**

**Input:** s =  "aabcbaa "
**Output:** 17

**Constraints:**

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

## A solution in Java

```java
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
    StringBuilder s1 = new StringBuilder();
    StringBuilder s2 = new StringBuilder();
    for (String w : word1) s1.append(w);
    for (String w : word2) s2.append(w);
    return s1.toString().equals(s2.toString());
}
```
The algorithm first concatenates the elements of the input arrays, `word1` and `word2`, to form the resulting strings. In C++ and Java, we use loops and the respective concatenation methods for the strings. In Python and JavaScript, we use the `join` method to concatenate the elements.

After the concatenation, the algorithm compares the resulting strings. If they are equal, the function returns `true`, indicating that the two arrays represent the same string. If they are not equal, the function returns `false`.

## A solution in C++

```cpp
bool arrayStringsAreEqual(std::vector<std::string>& word1, std::vector<std::string>& word2) {
    std::string s1, s2;
    for (auto& w : word1) s1 += w;
    for (auto& w : word2) s2 += w;
    return s1 == s2;
}
```
The algorithm first concatenates the elements of the input arrays, `word1` and `word2`, to form the resulting strings. In C++ and Java, we use loops and the respective concatenation methods for the strings. In Python and JavaScript, we use the `join` method to concatenate the elements.

After the concatenation, the algorithm compares the resulting strings. If they are equal, the function returns `true`, indicating that the two arrays represent the same string. If they are not equal, the function returns `false`.

## A solution in Python

```python
def arrayStringsAreEqual(word1, word2):
    return "".join(word1) == "".join(word2)
```
The algorithm first concatenates the elements of the input arrays, `word1` and `word2`, to form the resulting strings. In C++ and Java, we use loops and the respective concatenation methods for the strings. In Python and JavaScript, we use the `join` method to concatenate the elements.

After the concatenation, the algorithm compares the resulting strings. If they are equal, the function returns `true`, indicating that the two arrays represent the same string. If they are not equal, the function returns `false`.

## A solution in Javascript

```javascript
function arrayStringsAreEqual(word1, word2) {
    return word1.join("") === word2.join("");
}
```
The algorithm first concatenates the elements of the input arrays, `word1` and `word2`, to form the resulting strings. In C++ and Java, we use loops and the respective concatenation methods for the strings. In Python and JavaScript, we use the `join` method to concatenate the elements.

After the concatenation, the algorithm compares the resulting strings. If they are equal, the function returns `true`, indicating that the two arrays represent the same string. If they are not equal, the function returns `false`.


# Count Pairs Of Nodes

- slug: count-pairs-of-nodes
- difficulty: Hard

You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.

Let `incident(a, b)` be defined as the **number of edges** that are connected to **either** node `a` or `b`.

The answer to the `jth` query is the **number of pairs** of nodes `(a, b)` that satisfy **both** of the following conditions:

*   `a < b`
*   `incident(a, b) > queries[j]`

Return _an array_ `answers` _such that_ `answers.length == queries.length` _and_ `answers[j]` _is the answer of the_ `jth` _query_.

Note that there can be **multiple edges** between the same two nodes.

**Example 1:**

**Input:** n = 4, edges = \[\[1,2\],\[2,4\],\[1,3\],\[2,3\],\[2,1\]\], queries = \[2,3\]
**Output:** \[6,5\]
**Explanation:** The calculations for incident(a, b) are shown in the table above.
The answers for each of the queries are as follows:
- answers\[0\] = 6. All the pairs have an incident(a, b) value greater than 2.
- answers\[1\] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.

**Example 2:**

**Input:** n = 5, edges = \[\[1,5\],\[1,5\],\[3,4\],\[2,5\],\[1,3\],\[5,1\],\[2,3\],\[2,5\]\], queries = \[1,2,3,4,5\]
**Output:** \[10,10,9,8,6\]

**Constraints:**

*   `2 <= n <= 2 * 104`
*   `1 <= edges.length <= 105`
*   `1 <= ui, vi <= n`
*   `ui != vi`
*   `1 <= queries.length <= 20`
*   `0 <= queries[j] < edges.length`

## A solution in Java

```java
public class Solution {
    public String getSmallestString(int n, int k) {
        char[] result = new char[n];
        k -= n;
        for (int i = n - 1; i >= 0; --i) {
            int value = Math.min(k, 25);
            result[i] = (char) ('a' + value);
            k -= value;
            if (k == 0) break;
        }
        return new String(result);
    }
}
```
1. Initialize the result string of size `n` with all `'a'` characters.
2. Subtract `n` from `k` because we've already accounted for the 'a' characters.
3. Iterate over the string in reverse, and update each character based on the remaining value `k`.
4. At each position, calculate the smallest possible value for the current character. Choose the minimum between `k` and `25` (since 26 - 1 is the maximum we can increment the character), and update the character accordingly.
5. Subtract the chosen value from `k`, then update the index to the left.
6. Continue this process until there's nothing left to add, i.e., `k == 0`.
7. Return the result string.

## A solution in C++

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

string getSmallestString(int n, int k) {
    string result(n, 'a');
    k -= n;
    for (int i = n - 1; i >= 0; --i) {
        int value = min(k, 25);
        result[i] += value;
        k -= value;
        if (k == 0) break;
    }
    return result;
}
```
1. Initialize the result string of size `n` with all `'a'` characters.
2. Subtract `n` from `k` because we've already accounted for the 'a' characters.
3. Iterate over the string in reverse, and update each character based on the remaining value `k`.
4. At each position, calculate the smallest possible value for the current character. Choose the minimum between `k` and `25` (since 26 - 1 is the maximum we can increment the character), and update the character accordingly.
5. Subtract the chosen value from `k`, then update the index to the left.
6. Continue this process until there's nothing left to add, i.e., `k == 0`.
7. Return the result string.

## A solution in Python

```python
def get_smallest_string(n: int, k: int) -> str:
    result = ['a'] * n
    k -= n
    idx = n - 1
    while k > 0:
        value = min(k, 25)
        result[idx] = chr(ord(result[idx]) + value)
        k -= value
        idx -= 1
    return ''.join(result)
```
1. Initialize the result string of size `n` with all `'a'` characters.
2. Subtract `n` from `k` because we've already accounted for the 'a' characters.
3. Iterate over the string in reverse, and update each character based on the remaining value `k`.
4. At each position, calculate the smallest possible value for the current character. Choose the minimum between `k` and `25` (since 26 - 1 is the maximum we can increment the character), and update the character accordingly.
5. Subtract the chosen value from `k`, then update the index to the left.
6. Continue this process until there's nothing left to add, i.e., `k == 0`.
7. Return the result string.

## A solution in Javascript

```javascript
function getSmallestString(n, k) {
    const result = Array(n).fill('a');
    k -= n;
    for (let i = n - 1; i >= 0; --i) {
        const value = Math.min(k, 25);
        result[i] = String.fromCharCode(result[i].charCodeAt(0) + value);
        k -= value;
        if (k === 0) break;
    }
    return result.join('');
}
```
1. Initialize the result string of size `n` with all `'a'` characters.
2. Subtract `n` from `k` because we've already accounted for the 'a' characters.
3. Iterate over the string in reverse, and update each character based on the remaining value `k`.
4. At each position, calculate the smallest possible value for the current character. Choose the minimum between `k` and `25` (since 26 - 1 is the maximum we can increment the character), and update the character accordingly.
5. Subtract the chosen value from `k`, then update the index to the left.
6. Continue this process until there's nothing left to add, i.e., `k == 0`.
7. Return the result string.


# Check if Binary String Has at Most One Segment of Ones

- slug: check-if-binary-string-has-at-most-one-segment-of-ones
- difficulty: Easy

Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.

**Example 1:**

**Input:** s =  "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.

**Example 2:**

**Input:** s =  "110 "
**Output:** true

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int minimumEnergy(int[][] tasks) {
    Arrays.sort(tasks, (a, b) -> (b[1] - b[0]) - (a[1] - a[0]));

    int energy = 0;
    for (int[] task : tasks) {
        energy = Math.max(energy + task[0], task[1]);
    }
    return energy;
}
```
1. Sort the tasks in descending order based on the difference between the minimum energy required to start the task and the actual energy cost to complete the task `(minimum[i] - actual[i])`.
2. Initialize the current energy to 0.
3. Iterate through the sorted list of tasks, for each task:
   - Calculate the maximum of the current energy plus the actual energy cost to complete the task, or the minimum energy required to start the task, and set it as the current energy.
4. Return the current energy after processing all tasks. This will be the minimum initial amount of energy required to finish all tasks.

## A solution in C++

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

int minimumEnergy(std::vector<std::vector<int>>& tasks) {
    std::sort(tasks.begin(), tasks.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
        return a[1] - a[0] > b[1] - b[0];
    });

    int energy = 0;
    for (const auto& task : tasks) {
        energy = std::max(energy + task[0], task[1]);
    }
    return energy;
}
```
1. Sort the tasks in descending order based on the difference between the minimum energy required to start the task and the actual energy cost to complete the task `(minimum[i] - actual[i])`.
2. Initialize the current energy to 0.
3. Iterate through the sorted list of tasks, for each task:
   - Calculate the maximum of the current energy plus the actual energy cost to complete the task, or the minimum energy required to start the task, and set it as the current energy.
4. Return the current energy after processing all tasks. This will be the minimum initial amount of energy required to finish all tasks.

## A solution in Python

```python
def minimum_energy(tasks):
    tasks.sort(key=lambda task: task[1] - task[0], reverse=True)

    energy = 0
    for task in tasks:
        energy = max(energy + task[0], task[1])
    return energy
```
1. Sort the tasks in descending order based on the difference between the minimum energy required to start the task and the actual energy cost to complete the task `(minimum[i] - actual[i])`.
2. Initialize the current energy to 0.
3. Iterate through the sorted list of tasks, for each task:
   - Calculate the maximum of the current energy plus the actual energy cost to complete the task, or the minimum energy required to start the task, and set it as the current energy.
4. Return the current energy after processing all tasks. This will be the minimum initial amount of energy required to finish all tasks.

## A solution in Javascript

```javascript
function minimumEnergy(tasks) {
    tasks.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]));

    let energy = 0;
    for (let task of tasks) {
        energy = Math.max(energy + task[0], task[1]);
    }
    return energy;
}
```
1. Sort the tasks in descending order based on the difference between the minimum energy required to start the task and the actual energy cost to complete the task `(minimum[i] - actual[i])`.
2. Initialize the current energy to 0.
3. Iterate through the sorted list of tasks, for each task:
   - Calculate the maximum of the current energy plus the actual energy cost to complete the task, or the minimum energy required to start the task, and set it as the current energy.
4. Return the current energy after processing all tasks. This will be the minimum initial amount of energy required to finish all tasks.


# Minimum Elements to Add to Form a Given Sum

- slug: minimum-elements-to-add-to-form-a-given-sum
- difficulty: Medium

You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.

Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.

Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.

**Example 1:**

**Input:** nums = \[1,-1,1\], limit = 3, goal = -4
**Output:** 2
**Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.

**Example 2:**

**Input:** nums = \[1,-10,9,1\], limit = 100, goal = 0
**Output:** 1

**Constraints:**

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

## A solution in Java

```java
public int minElements(int[] nums, int limit, int goal) {
    long sum = 0;
    for (int num : nums) sum += num;
    long diff = Math.abs(goal - sum);

    return (int)((diff + limit - 1) / limit);
}
```
1. Calculate the sum of the elements in the input array `nums`.
2. Calculate the absolute difference between the `goal` and the sum of `nums`.
3. Divide the absolute difference by the `limit`, rounding up to the nearest integer. This gives the minimum number of elements needed to add to make the sum of the array `nums` equal to `goal` while maintaining the property that `abs(nums[i]) <= limit`.

## A solution in C++

```cpp
int minElements(vector<int>& nums, int limit, int goal) {
    long long sum = 0;
    for (int num : nums) sum += num;
    long long diff = abs(goal - sum);

    return (diff + limit - 1) / limit;
}
```
1. Calculate the sum of the elements in the input array `nums`.
2. Calculate the absolute difference between the `goal` and the sum of `nums`.
3. Divide the absolute difference by the `limit`, rounding up to the nearest integer. This gives the minimum number of elements needed to add to make the sum of the array `nums` equal to `goal` while maintaining the property that `abs(nums[i]) <= limit`.

## A solution in Python

```python
def minElements(nums, limit, goal):
    sum_nums = sum(nums)
    diff = abs(goal - sum_nums)

    return (diff + limit - 1) // limit
```
1. Calculate the sum of the elements in the input array `nums`.
2. Calculate the absolute difference between the `goal` and the sum of `nums`.
3. Divide the absolute difference by the `limit`, rounding up to the nearest integer. This gives the minimum number of elements needed to add to make the sum of the array `nums` equal to `goal` while maintaining the property that `abs(nums[i]) <= limit`.

## A solution in Javascript

```javascript
function minElements(nums, limit, goal) {
    let sum = nums.reduce((a, b) => a + b, 0);
    let diff = Math.abs(goal - sum);

    return Math.ceil(diff / limit);
}
```
1. Calculate the sum of the elements in the input array `nums`.
2. Calculate the absolute difference between the `goal` and the sum of `nums`.
3. Divide the absolute difference by the `limit`, rounding up to the nearest integer. This gives the minimum number of elements needed to add to make the sum of the array `nums` equal to `goal` while maintaining the property that `abs(nums[i]) <= limit`.


# Number of Restricted Paths From First to Last Node

- slug: number-of-restricted-paths-from-first-to-last-node
- difficulty: Medium

There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.

A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`.

The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.

Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** n = 5, edges = \[\[1,2,3\],\[1,3,3\],\[2,3,1\],\[1,4,2\],\[5,2,2\],\[3,5,1\],\[5,4,10\]\]
**Output:** 3
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5

**Example 2:**

**Input:** n = 7, edges = \[\[1,3,1\],\[4,1,2\],\[7,3,4\],\[2,5,3\],\[5,6,1\],\[6,7,2\],\[7,5,3\],\[2,6,4\]\]
**Output:** 1
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7.

**Constraints:**

*   `1 <= n <= 2 * 104`
*   `n - 1 <= edges.length <= 4 * 104`
*   `edges[i].length == 3`
*   `1 <= ui, vi <= n`
*   `ui != vi`
*   `1 <= weighti <= 105`
*   There is at most one edge between any two nodes.
*   There is at least one path between any two nodes.

## A solution in Java

```java
public int countConsistentStrings(String allowed, String[] words) {
    Set<Character> allowedSet = new HashSet<>();
    for (char c : allowed.toCharArray()) {
        allowedSet.add(c);
    }
    int count = 0;
    for (String word : words) {
        boolean isValid = true;
        for (char c : word.toCharArray()) {
            if (!allowedSet.contains(c)) {
                isValid = false;
                break;
            }
        }
        if (isValid) {
            count++;
        }
    }
    return count;
}
```
We create a set (allowedSet) with the characters of the allowed string. This makes it easy to check if a character is in the allowed string. We initialize a count variable with 0 as the number of consistent words.

For each word in the words array, we consider it valid initially. Then, we check each character in the word. If it's not in the allowedSet, the word is not valid, and we break the loop. If the word is valid, we increment the count by 1.

After checking all the words, we return the count as the result. Our algorithm has a time complexity of O(n*m) where n is the number of words and m is the average length of those words.

## A solution in C++

```cpp
int countConsistentStrings(string allowed, vector<string>& words) {
    unordered_set<char> allowedSet(allowed.begin(), allowed.end());
    int count = 0;
    for (const string& word : words) {
        bool isValid = true;
        for (char c : word) {
            if (allowedSet.count(c) == 0) {
                isValid = false;
                break;
            }
        }
        if (isValid) {
            count++;
        }
    }
    return count;
}
```
We create a set (allowedSet) with the characters of the allowed string. This makes it easy to check if a character is in the allowed string. We initialize a count variable with 0 as the number of consistent words.

For each word in the words array, we consider it valid initially. Then, we check each character in the word. If it's not in the allowedSet, the word is not valid, and we break the loop. If the word is valid, we increment the count by 1.

After checking all the words, we return the count as the result. Our algorithm has a time complexity of O(n*m) where n is the number of words and m is the average length of those words.

## A solution in Python

```python
def count_consistent_strings(allowed, words):
    allowed_set = set(allowed)
    count = 0
    for word in words:
        is_valid = True
        for c in word:
            if c not in allowed_set:
                is_valid = False
                break
        if is_valid:
            count += 1
    return count
```
We create a set (allowedSet) with the characters of the allowed string. This makes it easy to check if a character is in the allowed string. We initialize a count variable with 0 as the number of consistent words.

For each word in the words array, we consider it valid initially. Then, we check each character in the word. If it's not in the allowedSet, the word is not valid, and we break the loop. If the word is valid, we increment the count by 1.

After checking all the words, we return the count as the result. Our algorithm has a time complexity of O(n*m) where n is the number of words and m is the average length of those words.

## A solution in Javascript

```javascript
function countConsistentStrings(allowed, words) {
    const allowedSet = new Set(allowed);
    let count = 0;
    for (const word of words) {
        let isValid = true;
        for (const c of word) {
            if (!allowedSet.has(c)) {
                isValid = false;
                break;
            }
        }
        if (isValid) {
            count++;
        }
    }
    return count;
}
```
We create a set (allowedSet) with the characters of the allowed string. This makes it easy to check if a character is in the allowed string. We initialize a count variable with 0 as the number of consistent words.

For each word in the words array, we consider it valid initially. Then, we check each character in the word. If it's not in the allowedSet, the word is not valid, and we break the loop. If the word is valid, we increment the count by 1.

After checking all the words, we return the count as the result. Our algorithm has a time complexity of O(n*m) where n is the number of words and m is the average length of those words.


# Make the XOR of All Segments Equal to Zero

- slug: make-the-xor-of-all-segments-equal-to-zero
- difficulty: Hard

You are given an array `nums` and an integer `k`. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.

Return _the minimum number of elements to change in the array_ such that the `XOR` of all segments of size `k` is equal to zero.

**Example 1:**

**Input:** nums = \[1,2,0,3,0\], k = 1
**Output:** 3
**Explanation:** Modify the array from \[**1**,**2**,0,**3**,0\] to from \[**0**,**0**,0,**0**,0\].

**Example 2:**

**Input:** nums = \[3,4,5,2,1,7,3,4,7\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[3,4,**5**,**2**,**1**,7,3,4,7\] to \[3,4,**7**,**3**,**4**,7,3,4,7\].

**Example 3:**

**Input:** nums = \[1,2,4,1,2,5,1,2,6\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[1,2,**4,**1,2,**5**,1,2,**6**\] to \[1,2,**3**,1,2,**3**,1,2,**3**\].

**Constraints:**

*   `1 <= k <= nums.length <= 2000`
*   `0 <= nums[i] < 210`

## A solution in Java

```java
public int[] calculateSummationOfAbsoluteDifferences(int[] nums) {
    int n = nums.length;
    int[] result = new int[n];

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            if(i != j) {
                result[i] += Math.abs(nums[i] - nums[j]);
            }
        }
    }

    return result;
}
```
The algorithm iterates through each element `nums[i]` in the given integer array `nums`. For each element `nums[i]`, it also iterates through all other elements `nums[j]` in the array, skipping the case when `i == j`. Then, it calculates the absolute difference between `nums[i]` and `nums[j]`, and sums it to the corresponding result for element `nums[i]`. After iterating through all elements, an array `result` containing the summations of absolute differences for each element is returned.

## A solution in C++

```cpp
#include <vector>
#include <cstdlib>

std::vector<int> calculate_summation_of_absolute_differences(const std::vector<int>& nums) {
    int n = nums.size();
    std::vector<int> result(n, 0);

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            if(i != j) {
                result[i] += std::abs(nums[i] - nums[j]);
            }
        }
    }

    return result;
}
```
The algorithm iterates through each element `nums[i]` in the given integer array `nums`. For each element `nums[i]`, it also iterates through all other elements `nums[j]` in the array, skipping the case when `i == j`. Then, it calculates the absolute difference between `nums[i]` and `nums[j]`, and sums it to the corresponding result for element `nums[i]`. After iterating through all elements, an array `result` containing the summations of absolute differences for each element is returned.

## A solution in Python

```python
def calculate_summation_of_absolute_differences(nums):
    n = len(nums)
    result = [0] * n

    for i in range(n):
        for j in range(n):
            if i != j:
                result[i] += abs(nums[i] - nums[j])

    return result
```
The algorithm iterates through each element `nums[i]` in the given integer array `nums`. For each element `nums[i]`, it also iterates through all other elements `nums[j]` in the array, skipping the case when `i == j`. Then, it calculates the absolute difference between `nums[i]` and `nums[j]`, and sums it to the corresponding result for element `nums[i]`. After iterating through all elements, an array `result` containing the summations of absolute differences for each element is returned.

## A solution in Javascript

```javascript
function calculateSummationOfAbsoluteDifferences(nums) {
    let n = nums.length;
    let result = new Array(n).fill(0);

    for(let i = 0; i < n; i++) {
        for(let j = 0; j < n; j++) {
            if(i !== j) {
                result[i] += Math.abs(nums[i] - nums[j]);
            }
        }
    }

    return result;
}
```
The algorithm iterates through each element `nums[i]` in the given integer array `nums`. For each element `nums[i]`, it also iterates through all other elements `nums[j]` in the array, skipping the case when `i == j`. Then, it calculates the absolute difference between `nums[i]` and `nums[j]`, and sums it to the corresponding result for element `nums[i]`. After iterating through all elements, an array `result` containing the summations of absolute differences for each element is returned.


# Maximize the Beauty of the Garden

- slug: maximize-the-beauty-of-the-garden
- difficulty: Hard

There is a garden of `n` flowers, and each flower has an integer beauty value. The flowers are arranged in a line. You are given an integer array `flowers` of size `n` and each `flowers[i]` represents the beauty of the `ith` flower.

A garden is **valid** if it meets these conditions:

*   The garden has at least two flowers.
*   The first and the last flower of the garden have the same beauty value.

As the appointed gardener, you have the ability to **remove** any (possibly none) flowers from the garden. You want to remove flowers in a way that makes the remaining garden **valid**. The beauty of the garden is the sum of the beauty of all the remaining flowers.

Return the maximum possible beauty of some **valid** garden after you have removed any (possibly none) flowers.

**Example 1:**

**Input:** flowers = \[1,2,3,1,2\]
**Output:** 8
**Explanation:** You can produce the valid garden \[2,3,1,2\] to have a total beauty of 2 + 3 + 1 + 2 = 8.

**Example 2:**

**Input:** flowers = \[100,1,1,-3,1\]
**Output:** 3
**Explanation:** You can produce the valid garden \[1,1,1\] to have a total beauty of 1 + 1 + 1 = 3.

**Example 3:**

**Input:** flowers = \[-1,-2,0,-1\]
**Output:** -2
**Explanation:** You can produce the valid garden \[-1,-1\] to have a total beauty of -1 + -1 = -2.

**Constraints:**

*   `2 <= flowers.length <= 105`
*   `-104 <= flowers[i] <= 104`
*   It is possible to create a valid garden by removing some (possibly none) flowers.

## A solution in Java

```java
public int stoneGameVI(int[] aliceValues, int[] bobValues) {
    int n = aliceValues.length;
    Integer[] indexes = new Integer[n];
    for (int i = 0; i < n; ++i) {
        indexes[i] = i;
    }

    Arrays.sort(indexes, (a, b) -> (bobValues[b] + aliceValues[b]) - (bobValues[a] + aliceValues[a]));

    int aliceScore = 0, bobScore = 0;
    for (int i = 0; i < n; ++i) {
        if (i % 2 == 0) aliceScore += aliceValues[indexes[i]];
        else bobScore += bobValues[indexes[i]];
    }

    return Integer.compare(aliceScore, bobScore);
}
```
The game is played optimally. Therefore, each player will pick the stones that maximize the difference in scores. To achieve this, both players will consider the sum of their values and the opponent's values for each stone. Sort the stone indices in descending order according to the sums of Alice's and Bob's values. Then, each player takes turns picking stones according to this sorted order. Calculate the total scores for Alice and Bob. Finally, return 0 if the scores are equal, 1 if Alice has a higher score, and -1 if Bob has a higher score.

## A solution in C++

```cpp
int stoneGameVI(vector<int>& aliceValues, vector<int>& bobValues) {
    int n = aliceValues.size();
    vector<pair<int, int>> sums;

    for (int i = 0; i < n; ++i) {
        sums.push_back({aliceValues[i] + bobValues[i], i});
    }

    sort(sums.rbegin(), sums.rend());

    int aliceScore = 0, bobScore = 0;
    for (int i = 0; i < n; ++i) {
        if (i % 2 == 0) aliceScore += aliceValues[sums[i].second];
        else bobScore += bobValues[sums[i].second];
    }

    return (aliceScore == bobScore) ? 0 : (aliceScore > bobScore) ? 1 : -1;
}
```
The game is played optimally. Therefore, each player will pick the stones that maximize the difference in scores. To achieve this, both players will consider the sum of their values and the opponent's values for each stone. Sort the stone indices in descending order according to the sums of Alice's and Bob's values. Then, each player takes turns picking stones according to this sorted order. Calculate the total scores for Alice and Bob. Finally, return 0 if the scores are equal, 1 if Alice has a higher score, and -1 if Bob has a higher score.

## A solution in Python

```python
def stoneGameVI(aliceValues, bobValues):
    n = len(aliceValues)
    sums = sorted([(aliceValues[i] + bobValues[i], i) for i in range(n)], reverse=True)

    aliceScore = sum(aliceValues[i] for _, i in sums[::2])
    bobScore = sum(bobValues[i] for _, i in sums[1::2])

    return 0 if aliceScore == bobScore else 1 if aliceScore > bobScore else -1
```
The game is played optimally. Therefore, each player will pick the stones that maximize the difference in scores. To achieve this, both players will consider the sum of their values and the opponent's values for each stone. Sort the stone indices in descending order according to the sums of Alice's and Bob's values. Then, each player takes turns picking stones according to this sorted order. Calculate the total scores for Alice and Bob. Finally, return 0 if the scores are equal, 1 if Alice has a higher score, and -1 if Bob has a higher score.

## A solution in Javascript

```javascript
function stoneGameVI(aliceValues, bobValues) {
    const n = aliceValues.length;
    const sums = aliceValues.map((v, i) => [v + bobValues[i], i]).sort((a, b) => b[0] - a[0]);

    let aliceScore = 0, bobScore = 0;
    for (let i = 0; i < n; ++i) {
        if (i % 2 === 0) aliceScore += aliceValues[sums[i][1]];
        else bobScore += bobValues[sums[i][1]];
    }

    return aliceScore === bobScore ? 0 : aliceScore > bobScore ? 1 : -1;
}
```
The game is played optimally. Therefore, each player will pick the stones that maximize the difference in scores. To achieve this, both players will consider the sum of their values and the opponent's values for each stone. Sort the stone indices in descending order according to the sums of Alice's and Bob's values. Then, each player takes turns picking stones according to this sorted order. Calculate the total scores for Alice and Bob. Finally, return 0 if the scores are equal, 1 if Alice has a higher score, and -1 if Bob has a higher score.


# Check if One String Swap Can Make Strings Equal

- slug: check-if-one-string-swap-can-make-strings-equal
- difficulty: Easy

You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.

Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly one** of the strings._ Otherwise, return `false`.

**Example 1:**

**Input:** s1 =  "bank ", s2 =  "kanb "
**Output:** true
**Explanation:** For example, swap the first character with the last character of s2 to make  "bank ".

**Example 2:**

**Input:** s1 =  "attack ", s2 =  "defend "
**Output:** false
**Explanation:** It is impossible to make them equal with one string swap.

**Example 3:**

**Input:** s1 =  "kelb ", s2 =  "kelb "
**Output:** true
**Explanation:** The two strings are already equal, so no string swap operation is required.

**Constraints:**

*   `1 <= s1.length, s2.length <= 100`
*   `s1.length == s2.length`
*   `s1` and `s2` consist of only lowercase English letters.

## A solution in Java

```java
public boolean areAlmostEqual(String s1, String s2) {
    if(s1.equals(s2)) return true;
    List<Integer> diff = new ArrayList<>();
    for(int i = 0; i < s1.length(); i++) {
        if(s1.charAt(i) != s2.charAt(i)) {
            diff.add(i);
        }
    }
    return diff.size() == 2 && s1.charAt(diff.get(0)) == s2.charAt(diff.get(1)) && s1.charAt(diff.get(1)) == s2.charAt(diff.get(0));
}
```
1. Check if the two given strings are already equal, if so return `True`.
2. Iterate through the characters of the strings, if the characters at the same index are different, store the index in a list called `diff`.
3. Check if the `diff` list has exactly 2 indices, and if the character in s1 at the first index of `diff` is the same as the character in s2 at the second index of `diff`, and if the character in s1 at the second index of `diff` is the same as the character in s2 at the first index of `diff`. If these conditions are satisfied, return `True`, otherwise return `False`.

## A solution in C++

```cpp
bool areAlmostEqual(string s1, string s2) {
    if(s1 == s2) return true;
    vector<int> diff;
    for(int i = 0; i < s1.length(); i++) {
        if(s1[i] != s2[i]) {
            diff.push_back(i);
        }
    }
    return diff.size() == 2 && s1[diff[0]] == s2[diff[1]] && s1[diff[1]] == s2[diff[0]];
}
```
1. Check if the two given strings are already equal, if so return `True`.
2. Iterate through the characters of the strings, if the characters at the same index are different, store the index in a list called `diff`.
3. Check if the `diff` list has exactly 2 indices, and if the character in s1 at the first index of `diff` is the same as the character in s2 at the second index of `diff`, and if the character in s1 at the second index of `diff` is the same as the character in s2 at the first index of `diff`. If these conditions are satisfied, return `True`, otherwise return `False`.

## A solution in Python

```python
def are_almost_equal(s1, s2):
    if s1 == s2:
        return True
    diff = [i for i in range(len(s1)) if s1[i] != s2[i]]
    return len(diff) == 2 and s1[diff[0]] == s2[diff[1]] and s1[diff[1]] == s2[diff[0]]
```
1. Check if the two given strings are already equal, if so return `True`.
2. Iterate through the characters of the strings, if the characters at the same index are different, store the index in a list called `diff`.
3. Check if the `diff` list has exactly 2 indices, and if the character in s1 at the first index of `diff` is the same as the character in s2 at the second index of `diff`, and if the character in s1 at the second index of `diff` is the same as the character in s2 at the first index of `diff`. If these conditions are satisfied, return `True`, otherwise return `False`.

## A solution in Javascript

```javascript
function areAlmostEqual(s1, s2) {
    if(s1 === s2) return true;
    let diff = [];
    for(let i = 0; i < s1.length; i++) {
        if(s1.charAt(i) !== s2.charAt(i)) {
            diff.push(i);
        }
    }
    return diff.length === 2 && s1.charAt(diff[0]) === s2.charAt(diff[1]) && s1.charAt(diff[1]) === s2.charAt(diff[0]);
}
```
1. Check if the two given strings are already equal, if so return `True`.
2. Iterate through the characters of the strings, if the characters at the same index are different, store the index in a list called `diff`.
3. Check if the `diff` list has exactly 2 indices, and if the character in s1 at the first index of `diff` is the same as the character in s2 at the second index of `diff`, and if the character in s1 at the second index of `diff` is the same as the character in s2 at the first index of `diff`. If these conditions are satisfied, return `True`, otherwise return `False`.


# Find Center of Star Graph

- slug: find-center-of-star-graph
- difficulty: Easy

There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.

You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.

**Example 1:**

**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.

**Example 2:**

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

**Constraints:**

*   `3 <= n <= 105`
*   `edges.length == n - 1`
*   `edges[i].length == 2`
*   `1 <= ui, vi <= n`
*   `ui != vi`
*   The given `edges` represent a valid star graph.

## A solution in Java

```java
public int maximumWealth(int[][] accounts) {
    int maxWealth = 0;
    for (int[] customer : accounts) {
        int wealth = 0;
        for (int account : customer) {
            wealth += account;
        }
        maxWealth = Math.max(maxWealth, wealth);
    }
    return maxWealth;
}
```
Iterate through each customer's accounts in the grid. For each customer, calculate the total wealth by summing the values of all their bank accounts. Compare the total wealth of each customer with the previously calculated maximum wealth, and set the maximum wealth to the current customer's wealth if it is greater. Continue this process for all customers and return the final maximum wealth value when finished.

The implementations in C++, Java, and JavaScript use loops or built-in functions to iterate through the grid and calculate the sums. Python uses a small one-liner to achieve the same result with a generator expression.

## A solution in C++

```cpp
int maximumWealth(vector<vector<int>>& accounts) {
    int max_wealth = 0;
    for (const auto& customer : accounts) {
        max_wealth = max(max_wealth, accumulate(customer.begin(), customer.end(), 0));
    }
    return max_wealth;
}
```
Iterate through each customer's accounts in the grid. For each customer, calculate the total wealth by summing the values of all their bank accounts. Compare the total wealth of each customer with the previously calculated maximum wealth, and set the maximum wealth to the current customer's wealth if it is greater. Continue this process for all customers and return the final maximum wealth value when finished.

The implementations in C++, Java, and JavaScript use loops or built-in functions to iterate through the grid and calculate the sums. Python uses a small one-liner to achieve the same result with a generator expression.

## A solution in Python

```python
def maximum_wealth(accounts):
    return max(sum(customer) for customer in accounts)
```
Iterate through each customer's accounts in the grid. For each customer, calculate the total wealth by summing the values of all their bank accounts. Compare the total wealth of each customer with the previously calculated maximum wealth, and set the maximum wealth to the current customer's wealth if it is greater. Continue this process for all customers and return the final maximum wealth value when finished.

The implementations in C++, Java, and JavaScript use loops or built-in functions to iterate through the grid and calculate the sums. Python uses a small one-liner to achieve the same result with a generator expression.

## A solution in Javascript

```javascript
function maximumWealth(accounts) {
    return accounts.reduce((maxWealth, customer) =>
        Math.max(maxWealth, customer.reduce((wealth, account) => wealth + account, 0)), 0);
}
```
Iterate through each customer's accounts in the grid. For each customer, calculate the total wealth by summing the values of all their bank accounts. Compare the total wealth of each customer with the previously calculated maximum wealth, and set the maximum wealth to the current customer's wealth if it is greater. Continue this process for all customers and return the final maximum wealth value when finished.

The implementations in C++, Java, and JavaScript use loops or built-in functions to iterate through the grid and calculate the sums. Python uses a small one-liner to achieve the same result with a generator expression.


# Maximum Average Pass Ratio

- slug: maximum-average-pass-ratio
- difficulty: Medium

There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam.

You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes.

The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes.

Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted.

**Example 1:**

**Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2
**Output:** 0.78333
**Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.

**Example 2:**

**Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4
**Output:** 0.53485

**Constraints:**

*   `1 <= classes.length <= 105`
*   `classes[i].length == 2`
*   `1 <= passi <= totali <= 105`
*   `1 <= extraStudents <= 105`

## A solution in Java

```java
import java.util.Stack;

public int[] mostCompetitive(int[] nums, int k) {
    Stack<Integer> stack = new Stack<>();
    int n = nums.length;

    for (int i = 0; i < n; i++) {
        while (!stack.isEmpty() && nums[i] < stack.peek() && stack.size() + n - i > k) {
            stack.pop();
        }
        if (stack.size() < k) {
            stack.push(nums[i]);
        }
    }

    int[] result = new int[k];
    for (int i = k - 1; i >= 0; i--) {
        result[i] = stack.pop();
    }

    return result;
}
```
The algorithm utilizes a stack and goes through the `nums` array once. It decides whether to add an element to the stack based on the following criteria:
1. The stack is not empty (to allow pop operation).
2. The current element is smaller than the top element of the stack (the most recent element).
3. The sum of stack size and remaining elements (n - i) in the array is greater than k, ensuring that we have enough elements left to form a subsequence of size `k`.

Then, if the stack size is less than `k`, we add the current element of `nums` to the stack.

Finally, we pop out the elements and add them to the result array in a reversed order, creating the most competitive subsequence with size `k`.

## A solution in C++

```cpp
#include <vector>
#include <stack>

std::vector<int> mostCompetitive(std::vector<int>& nums, int k) {
    std::stack<int> stk;
    int n = nums.size();

    for (int i = 0; i < n; i++) {
        while (!stk.empty() && nums[i] < stk.top() && stk.size() + n - i > k) {
            stk.pop();
        }
        if (stk.size() < k) {
            stk.push(nums[i]);
        }
    }

    std::vector<int> result(k);
    for (int i = k - 1; i >= 0; i--) {
        result[i] = stk.top();
        stk.pop();
    }

    return result;
}
```
The algorithm utilizes a stack and goes through the `nums` array once. It decides whether to add an element to the stack based on the following criteria:
1. The stack is not empty (to allow pop operation).
2. The current element is smaller than the top element of the stack (the most recent element).
3. The sum of stack size and remaining elements (n - i) in the array is greater than k, ensuring that we have enough elements left to form a subsequence of size `k`.

Then, if the stack size is less than `k`, we add the current element of `nums` to the stack.

Finally, we pop out the elements and add them to the result array in a reversed order, creating the most competitive subsequence with size `k`.

## A solution in Python

```python
def most_competitive(nums, k):
    stack = []
    n = len(nums)

    for i in range(n):
        while stack and nums[i] < stack[-1] and len(stack) + n - i > k:
            stack.pop()
        if len(stack) < k:
            stack.append(nums[i])

    return stack
```
The algorithm utilizes a stack and goes through the `nums` array once. It decides whether to add an element to the stack based on the following criteria:
1. The stack is not empty (to allow pop operation).
2. The current element is smaller than the top element of the stack (the most recent element).
3. The sum of stack size and remaining elements (n - i) in the array is greater than k, ensuring that we have enough elements left to form a subsequence of size `k`.

Then, if the stack size is less than `k`, we add the current element of `nums` to the stack.

Finally, we pop out the elements and add them to the result array in a reversed order, creating the most competitive subsequence with size `k`.

## A solution in Javascript

```javascript
function mostCompetitive(nums, k) {
    const stack = [];
    const n = nums.length;

    for (let i = 0; i < n; i++) {
        while (stack.length > 0 && nums[i] < stack[stack.length - 1] && stack.length + n - i > k) {
            stack.pop();
        }
        if (stack.length < k) {
            stack.push(nums[i]);
        }
    }

    return stack;
}
```
The algorithm utilizes a stack and goes through the `nums` array once. It decides whether to add an element to the stack based on the following criteria:
1. The stack is not empty (to allow pop operation).
2. The current element is smaller than the top element of the stack (the most recent element).
3. The sum of stack size and remaining elements (n - i) in the array is greater than k, ensuring that we have enough elements left to form a subsequence of size `k`.

Then, if the stack size is less than `k`, we add the current element of `nums` to the stack.

Finally, we pop out the elements and add them to the result array in a reversed order, creating the most competitive subsequence with size `k`.