# Find the Difference of Two Arrays

- slug: find-the-difference-of-two-arrays
- difficulty: Easy

Given two **0-indexed** integer arrays `nums1` and `nums2`, return _a list_ `answer` _of size_ `2` _where:_

*   `answer[0]` _is a list of all **distinct** integers in_ `nums1` _which are **not** present in_ `nums2`_._
*   `answer[1]` _is a list of all **distinct** integers in_ `nums2` _which are **not** present in_ `nums1`.

**Note** that the integers in the lists may be returned in **any** order.

**Example 1:**

**Input:** nums1 = \[1,2,3\], nums2 = \[2,4,6\]
**Output:** \[\[1,3\],\[4,6\]\]
**Explanation:**
For nums1, nums1\[1\] = 2 is present at index 0 of nums2, whereas nums1\[0\] = 1 and nums1\[2\] = 3 are not present in nums2. Therefore, answer\[0\] = \[1,3\].
For nums2, nums2\[0\] = 2 is present at index 1 of nums1, whereas nums2\[1\] = 4 and nums2\[2\] = 6 are not present in nums2. Therefore, answer\[1\] = \[4,6\].

**Example 2:**

**Input:** nums1 = \[1,2,3,3\], nums2 = \[1,1,2,2\]
**Output:** \[\[3\],\[\]\]
**Explanation:**
For nums1, nums1\[2\] and nums1\[3\] are not present in nums2. Since nums1\[2\] == nums1\[3\], their value is only included once and answer\[0\] = \[3\].
Every integer in nums2 is present in nums1. Therefore, answer\[1\] = \[\].

**Constraints:**

*   `1 <= nums1.length, nums2.length <= 1000`
*   `-1000 <= nums1[i], nums2[i] <= 1000`

## A solution in Java

```java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Solution {
    void helper(int[] digits, ArrayList<Integer> current, Set<Integer> result, boolean[] used) {
        if (current.size() == digits.length) {
            int num = 0;
            for (int d : current) {
                num = num * 10 + d;
            }
            result.add(num);
            return;
        }
        for (int i = 0; i < digits.length; ++i) {
            if (!used[i]) {
                used[i] = true;
                current.add(digits[i]);
                helper(digits, current, result, used);
                current.remove(current.size() - 1);
                used[i] = false;
            }
        }
    }

    public List<Integer> uniquePermutations(int[] digits) {
        ArrayList<Integer> current = new ArrayList<>();
        Set<Integer> result = new HashSet<>();
        boolean[] used = new boolean[digits.length];
        java.util.Arrays.sort(digits);

        helper(digits, current, result, used);

        return result.stream().sorted().collect(Collectors.toList());
    }
}
```
1. For each language, the function accepts the input array `digits`.
2. We sort the input array in non-decreasing order.
3. We use a helper function to perform recursion and create permutations. The helper function takes parameters for the digits, the current permutation being formed, the set of unique permutations, and a tracking array called `used` to keep track of digits that have been used in the current permutation.
4. In the helper function, if the length of the current permutation matches the length of the input array, we have a complete permutation, so we convert the current permutation into an integer and insert it into the result set.
5. If the current permutation is not complete, we iterate through the input array, and for each digit that is not already used in the current permutation, we mark it as used, add it to the current permutation, and call the helper function recursively.
6. After a recursive call, we remove the last added digit from the current permutation and mark that digit as unused.
7. Once the helper function is done, we convert the result set into a sorted array and return it.

## A solution in C++

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

void helper(vector<int>& digits, vector<int>& current, set<int>& result, vector<bool>& used) {
    if (current.size() == digits.size()) {
        int num = 0;
        for (int d : current) {
            num = num * 10 + d;
        }
        result.insert(num);
        return;
    }
    for (int i = 0; i < digits.size(); ++i) {
        if (!used[i]) {
            used[i] = true;
            current.push_back(digits[i]);
            helper(digits, current, result, used);
            current.pop_back();
            used[i] = false;
        }
    }
}

vector<int> uniquePermutations(vector<int>& digits) {
    vector<int> current;
    set<int> result;
    vector<bool> used(digits.size(), false);
    sort(digits.begin(), digits.end());

    helper(digits, current, result, used);

    return vector<int>(result.begin(), result.end());
}
```
1. For each language, the function accepts the input array `digits`.
2. We sort the input array in non-decreasing order.
3. We use a helper function to perform recursion and create permutations. The helper function takes parameters for the digits, the current permutation being formed, the set of unique permutations, and a tracking array called `used` to keep track of digits that have been used in the current permutation.
4. In the helper function, if the length of the current permutation matches the length of the input array, we have a complete permutation, so we convert the current permutation into an integer and insert it into the result set.
5. If the current permutation is not complete, we iterate through the input array, and for each digit that is not already used in the current permutation, we mark it as used, add it to the current permutation, and call the helper function recursively.
6. After a recursive call, we remove the last added digit from the current permutation and mark that digit as unused.
7. Once the helper function is done, we convert the result set into a sorted array and return it.

## A solution in Python

```python
from itertools import permutations

def unique_permutations(digits):
    unique_perms = set(permutations(digits))
    unique_ints = sorted({int(''.join(map(str, perm))) for perm in unique_perms})

    return unique_ints
```
1. For each language, the function accepts the input array `digits`.
2. We sort the input array in non-decreasing order.
3. We use a helper function to perform recursion and create permutations. The helper function takes parameters for the digits, the current permutation being formed, the set of unique permutations, and a tracking array called `used` to keep track of digits that have been used in the current permutation.
4. In the helper function, if the length of the current permutation matches the length of the input array, we have a complete permutation, so we convert the current permutation into an integer and insert it into the result set.
5. If the current permutation is not complete, we iterate through the input array, and for each digit that is not already used in the current permutation, we mark it as used, add it to the current permutation, and call the helper function recursively.
6. After a recursive call, we remove the last added digit from the current permutation and mark that digit as unused.
7. Once the helper function is done, we convert the result set into a sorted array and return it.

## A solution in Javascript

```javascript
function helper(digits, current, result, used) {
    if (current.length === digits.length) {
        let num = parseInt(current.join(''), 10);
        result.add(num);
        return;
    }
    for (let i = 0; i < digits.length; ++i) {
        if (!used[i]) {
            used[i] = true;
            current.push(digits[i]);
            helper(digits, current, result, used);
            current.pop();
            used[i] = false;
        }
    }
}

function uniquePermutations(digits) {
    let current = [];
    let result = new Set();
    let used = new Array(digits.length).fill(false);
    digits.sort((a, b) => a - b);

    helper(digits, current, result, used);

    return Array.from(result).sort((a, b) => a - b);
}
```
1. For each language, the function accepts the input array `digits`.
2. We sort the input array in non-decreasing order.
3. We use a helper function to perform recursion and create permutations. The helper function takes parameters for the digits, the current permutation being formed, the set of unique permutations, and a tracking array called `used` to keep track of digits that have been used in the current permutation.
4. In the helper function, if the length of the current permutation matches the length of the input array, we have a complete permutation, so we convert the current permutation into an integer and insert it into the result set.
5. If the current permutation is not complete, we iterate through the input array, and for each digit that is not already used in the current permutation, we mark it as used, add it to the current permutation, and call the helper function recursively.
6. After a recursive call, we remove the last added digit from the current permutation and mark that digit as unused.
7. Once the helper function is done, we convert the result set into a sorted array and return it.


# Minimum Deletions to Make Array Beautiful

- slug: minimum-deletions-to-make-array-beautiful
- difficulty: Medium

You are given a **0-indexed** integer array `nums`. The array `nums` is **beautiful** if:

*   `nums.length` is even.
*   `nums[i] != nums[i + 1]` for all `i % 2 == 0`.

Note that an empty array is considered beautiful.

You can delete any number of elements from `nums`. When you delete an element, all the elements to the right of the deleted element will be **shifted one unit to the left** to fill the gap created and all the elements to the left of the deleted element will remain **unchanged**.

Return _the **minimum** number of elements to delete from_ `nums` _to make it_ _beautiful._

**Example 1:**

**Input:** nums = \[1,1,2,3,5\]
**Output:** 1
**Explanation:** You can delete either `nums[0]` or `nums[1]` to make `nums` = \[1,2,3,5\] which is beautiful. It can be proven you need at least 1 deletion to make `nums` beautiful.

**Example 2:**

**Input:** nums = \[1,1,2,2,3,3\]
**Output:** 2
**Explanation:** You can delete `nums[0]` and `nums[5]` to make nums = \[1,2,2,3\] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.

**Constraints:**

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

## A solution in Java

```java
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

public ListNode deleteMiddle(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode slow = head;
    ListNode fast = head;
    ListNode prev = null;

    while (fast != null && fast.next != null) {
        prev = slow;
        slow = slow.next;
        fast = fast.next.next;
    }

    prev.next = slow.next;
    return head;
}
```
The algorithm utilizes the slow and fast pointer approach to find the middle node of the linked list. Initialize two pointers: slow and fast both pointing to the head of the list. Additionally, have a prev pointer to store the previous node of slow pointer.

In each iteration of the while loop, move the slow pointer by one step and fast pointer by two steps. When fast pointer reaches the end of the linked list or there is no next for fast pointer, then the slow pointer points to the middle node.

At each step, update the prev pointer to the current slow pointer, so when we reach the middle node, the prev pointer points to the node before the middle node. Then, update the next attribute of the prev node to skip the middle node (slow->next). Finally, return the head of the modified linked list.

## A solution in C++

```cpp
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* deleteMiddle(ListNode* head) {
    if (!head || !head->next) return head;
    ListNode* slow = head;
    ListNode* fast = head;
    ListNode* prev = nullptr;

    while (fast && fast->next) {
        prev = slow;
        slow = slow->next;
        fast = fast->next->next;
    }

    prev->next = slow->next;
    delete slow;
    return head;
}
```
The algorithm utilizes the slow and fast pointer approach to find the middle node of the linked list. Initialize two pointers: slow and fast both pointing to the head of the list. Additionally, have a prev pointer to store the previous node of slow pointer.

In each iteration of the while loop, move the slow pointer by one step and fast pointer by two steps. When fast pointer reaches the end of the linked list or there is no next for fast pointer, then the slow pointer points to the middle node.

At each step, update the prev pointer to the current slow pointer, so when we reach the middle node, the prev pointer points to the node before the middle node. Then, update the next attribute of the prev node to skip the middle node (slow->next). Finally, return the head of the modified linked list.

## A solution in Python

```python
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def delete_middle(head):
    if not head or not head.next:
        return head
    slow = head
    fast = head
    prev = None

    while fast and fast.next:
        prev = slow
        slow = slow.next
        fast = fast.next.next

    prev.next = slow.next
    return head
```
The algorithm utilizes the slow and fast pointer approach to find the middle node of the linked list. Initialize two pointers: slow and fast both pointing to the head of the list. Additionally, have a prev pointer to store the previous node of slow pointer.

In each iteration of the while loop, move the slow pointer by one step and fast pointer by two steps. When fast pointer reaches the end of the linked list or there is no next for fast pointer, then the slow pointer points to the middle node.

At each step, update the prev pointer to the current slow pointer, so when we reach the middle node, the prev pointer points to the node before the middle node. Then, update the next attribute of the prev node to skip the middle node (slow->next). Finally, return the head of the modified linked list.

## A solution in Javascript

```javascript
class ListNode {
    constructor(val, next = null) {
        this.val = val;
        this.next = next;
    }
}

function deleteMiddle(head) {
    if (!head || !head.next) return head;
    let slow = head;
    let fast = head;
    let prev = null;

    while (fast && fast.next) {
        prev = slow;
        slow = slow.next;
        fast = fast.next.next;
    }

    prev.next = slow.next;
    return head;
}
```
The algorithm utilizes the slow and fast pointer approach to find the middle node of the linked list. Initialize two pointers: slow and fast both pointing to the head of the list. Additionally, have a prev pointer to store the previous node of slow pointer.

In each iteration of the while loop, move the slow pointer by one step and fast pointer by two steps. When fast pointer reaches the end of the linked list or there is no next for fast pointer, then the slow pointer points to the middle node.

At each step, update the prev pointer to the current slow pointer, so when we reach the middle node, the prev pointer points to the node before the middle node. Then, update the next attribute of the prev node to skip the middle node (slow->next). Finally, return the head of the modified linked list.


# Find Palindrome With Fixed Length

- slug: find-palindrome-with-fixed-length
- difficulty: Medium

Given an integer array `queries` and a **positive** integer `intLength`, return _an array_ `answer` _where_ `answer[i]` _is either the_ `queries[i]th` _smallest **positive palindrome** of length_ `intLength` _or_ `-1` _if no such palindrome exists_.

A **palindrome** is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.

**Example 1:**

**Input:** queries = \[1,2,3,4,5,90\], intLength = 3
**Output:** \[101,111,121,131,141,999\]
**Explanation:**
The first few palindromes of length 3 are:
101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...
The 90th palindrome of length 3 is 999.

**Example 2:**

**Input:** queries = \[2,4,6\], intLength = 4
**Output:** \[1111,1331,1551\]
**Explanation:**
The first six palindromes of length 4 are:
1001, 1111, 1221, 1331, 1441, and 1551.

**Constraints:**

*   `1 <= queries.length <= 5 * 104`
*   `1 <= queries[i] <= 109`
*   `1 <= intLength <= 15`

## A solution in Java

```java
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public String findPath(TreeNode root, int target, String path) {
    if (root == null) return "";
    if (root.val == target) return path;
    String left = findPath(root.left, target, path + "L");
    String right = findPath(root.right, target, path + "R");
    return left.isEmpty() ? right : left;
}

public String shortestPath(TreeNode root, int startValue, int destValue) {
    String sPath = findPath(root, startValue, "");
    String tPath = findPath(root, destValue, "");
    int i = 0;
    while (i < sPath.length() && i < tPath.length() && sPath.charAt(i) == tPath.charAt(i)) i++;
    String res = "";
    for (int j = sPath.length() - 1; j >= i; j--) res += "U";
    for (int j = i; j < tPath.length(); j++) res += tPath.charAt(j);
    return res;
}
```
To solve the problem:
1. Create a helper function `findPath` that takes the root of the binary tree, the target value, and the current path as a string. This function returns the path to reach the target value from the root.
2. In this function, return an empty string if the root is null. If the root value is equal to the target value, return the current path.
3. Recursively call the same function for the left and right child nodes, appending 'L' or 'R' to the path string accordingly.
4. Return the path found in either the left or right subtree.
5. Use this helper function to find the paths for both the start and destination values.
6. Iterate through both paths to find the common prefix in the paths.
7. The shortest path from the start to the destination node is obtained by first moving up from the start node the number of steps required to reach the common ancestor, and then following the path from the common ancestor to the destination node.

This is implemented in all four programming languages (C++, Java, Python, and JavaScript).

## A solution in C++

```cpp
#include<bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

string findPath(TreeNode* root, int target, string path) {
    if (!root) return "";
    if (root->val == target) return path;
    string left = findPath(root->left, target, path + "L");
    string right = findPath(root->right, target, path + "R");
    return left.empty() ? right : left;
}

string shortestPath(TreeNode* root, int startValue, int destValue) {
    string sPath = findPath(root, startValue, "");
    string tPath = findPath(root, destValue, "");
    int i = 0;
    while (i < sPath.size() && i < tPath.size() && sPath[i] == tPath[i]) i++;
    string res = "";
    for (int j = sPath.size() - 1; j >= i; j--) res += "U";
    for (int j = i; j < tPath.size(); j++) res += tPath[j];
    return res;
}
```
To solve the problem:
1. Create a helper function `findPath` that takes the root of the binary tree, the target value, and the current path as a string. This function returns the path to reach the target value from the root.
2. In this function, return an empty string if the root is null. If the root value is equal to the target value, return the current path.
3. Recursively call the same function for the left and right child nodes, appending 'L' or 'R' to the path string accordingly.
4. Return the path found in either the left or right subtree.
5. Use this helper function to find the paths for both the start and destination values.
6. Iterate through both paths to find the common prefix in the paths.
7. The shortest path from the start to the destination node is obtained by first moving up from the start node the number of steps required to reach the common ancestor, and then following the path from the common ancestor to the destination node.

This is implemented in all four programming languages (C++, Java, Python, and JavaScript).

## A solution in Python

```python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def find_path(root, target, path):
    if not root: return ""
    if root.val == target: return path
    left = find_path(root.left, target, path + "L")
    right = find_path(root.right, target, path + "R")
    return left if left else right

def shortest_path(root, start_value, dest_value):
    s_path = find_path(root, start_value, "")
    t_path = find_path(root, dest_value, "")
    i = 0
    while i < len(s_path) and i < len(t_path) and s_path[i] == t_path[i]: i += 1
    res = "U" * (len(s_path) - i) + t_path[i:]
    return res
```
To solve the problem:
1. Create a helper function `findPath` that takes the root of the binary tree, the target value, and the current path as a string. This function returns the path to reach the target value from the root.
2. In this function, return an empty string if the root is null. If the root value is equal to the target value, return the current path.
3. Recursively call the same function for the left and right child nodes, appending 'L' or 'R' to the path string accordingly.
4. Return the path found in either the left or right subtree.
5. Use this helper function to find the paths for both the start and destination values.
6. Iterate through both paths to find the common prefix in the paths.
7. The shortest path from the start to the destination node is obtained by first moving up from the start node the number of steps required to reach the common ancestor, and then following the path from the common ancestor to the destination node.

This is implemented in all four programming languages (C++, Java, Python, and JavaScript).

## A solution in Javascript

```javascript
class TreeNode {
    constructor(val, left = null, right = null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

function findPath(root, target, path) {
    if (!root) return "";
    if (root.val === target) return path;
    let left = findPath(root.left, target, path + "L");
    let right = findPath(root.right, target, path + "R");
    return left ? left : right;
}

function shortestPath(root, startValue, destValue) {
    let sPath = findPath(root, startValue, "");
    let tPath = findPath(root, destValue, "");
    let i = 0;
    while (i < sPath.length && i < tPath.length && sPath[i] === tPath[i]) i++;
    let res = "";
    for (let j = sPath.length - 1; j >= i; j--) res += "U";
    for (let j = i; j < tPath.length; j++) res += tPath[j];
    return res;
}
```
To solve the problem:
1. Create a helper function `findPath` that takes the root of the binary tree, the target value, and the current path as a string. This function returns the path to reach the target value from the root.
2. In this function, return an empty string if the root is null. If the root value is equal to the target value, return the current path.
3. Recursively call the same function for the left and right child nodes, appending 'L' or 'R' to the path string accordingly.
4. Return the path found in either the left or right subtree.
5. Use this helper function to find the paths for both the start and destination values.
6. Iterate through both paths to find the common prefix in the paths.
7. The shortest path from the start to the destination node is obtained by first moving up from the start node the number of steps required to reach the common ancestor, and then following the path from the common ancestor to the destination node.

This is implemented in all four programming languages (C++, Java, Python, and JavaScript).


# Maximum Value of K Coins From Piles

- slug: maximum-value-of-k-coins-from-piles
- difficulty: Hard

There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations.

In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet.

Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `ith` pile from **top to bottom**, and a positive integer `k`, return _the **maximum total value** of coins you can have in your wallet if you choose **exactly**_ `k` _coins optimally_.

**Example 1:**

**Input:** piles = \[\[1,100,3\],\[7,8,9\]\], k = 2
**Output:** 101
**Explanation:**
The above diagram shows the different ways we can choose k coins.
The maximum total we can obtain is 101.

**Example 2:**

**Input:** piles = \[\[100\],\[100\],\[100\],\[100\],\[100\],\[100\],\[1,1,1,1,1,1,700\]\], k = 7
**Output:** 706
**Explanation:**
The maximum total can be obtained if we choose all coins from the last pile.

**Constraints:**

*   `n == piles.length`
*   `1 <= n <= 1000`
*   `1 <= piles[i][j] <= 105`
*   `1 <= k <= sum(piles[i].length) <= 2000`

## A solution in Java

```java
import java.util.PriorityQueue;
import java.util.List;

public int maxCoins(List<List<Integer>> piles, int k) {
    PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
    for (List<Integer> pile : piles) {
        for (Integer coin : pile) {
            pq.offer(coin);
        }
    }

    int maxValue = 0;
    while (k > 0) {
        maxValue += pq.poll();
        k--;
    }
    return maxValue;
}
```
1. We use a priority queue (max heap) to keep track of the top coins in each pile. The priority queue will store all the coins from the piles, sorted in descending order.
2. Iterate through each pile in `piles`. For each coin in the pile, add it to the priority queue.
3. Initialize `max_value` to 0. While there are still moves allowed (k > 0), pop the top coin (max value coin) from the priority queue, add it to `max_value`, and decrement k.
4. Return `max_value` as the final result after k moves.

## A solution in C++

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

int maxCoins(vector<vector<int>>& piles, int k) {
    priority_queue<int> pq;
    for (const auto& pile : piles) {
        for (const auto& coin : pile) {
            pq.push(coin);
        }
    }

    int max_value = 0;
    while (k > 0) {
        max_value += pq.top();
        pq.pop();
        k--;
    }
    return max_value;
}
```
1. We use a priority queue (max heap) to keep track of the top coins in each pile. The priority queue will store all the coins from the piles, sorted in descending order.
2. Iterate through each pile in `piles`. For each coin in the pile, add it to the priority queue.
3. Initialize `max_value` to 0. While there are still moves allowed (k > 0), pop the top coin (max value coin) from the priority queue, add it to `max_value`, and decrement k.
4. Return `max_value` as the final result after k moves.

## A solution in Python

```python
import heapq

def maxCoins(piles, k):
    pq = []
    for pile in piles:
        for coin in pile:
            heapq.heappush(pq, -coin)

    max_value = 0
    while k > 0:
        max_value += -heapq.heappop(pq)
        k -= 1
    return max_value
```
1. We use a priority queue (max heap) to keep track of the top coins in each pile. The priority queue will store all the coins from the piles, sorted in descending order.
2. Iterate through each pile in `piles`. For each coin in the pile, add it to the priority queue.
3. Initialize `max_value` to 0. While there are still moves allowed (k > 0), pop the top coin (max value coin) from the priority queue, add it to `max_value`, and decrement k.
4. Return `max_value` as the final result after k moves.

## A solution in Javascript

```javascript
function maxCoins(piles, k) {
    let pq = new PriorityQueue((a, b) => b - a);
    for (let pile of piles) {
        for (let coin of pile) {
            pq.enqueue(coin);
        }
    }

    let maxValue = 0;
    while (k > 0) {
        maxValue += pq.dequeue();
        k--;
    }
    return maxValue;
}

class PriorityQueue {
    constructor(comparator) {
        this.data = [];
        this.comparator = comparator;
    }

    enqueue(element) {
        this.data.push(element);
        this.data.sort(this.comparator);
    }

    dequeue() {
        return this.data.shift();
    }

    isEmpty() {
        return this.data.length === 0;
    }
}
```
1. We use a priority queue (max heap) to keep track of the top coins in each pile. The priority queue will store all the coins from the piles, sorted in descending order.
2. Iterate through each pile in `piles`. For each coin in the pile, add it to the priority queue.
3. Initialize `max_value` to 0. While there are still moves allowed (k > 0), pop the top coin (max value coin) from the priority queue, add it to `max_value`, and decrement k.
4. Return `max_value` as the final result after k moves.


# Maximum Sum Score of Array

- slug: maximum-sum-score-of-array
- difficulty: Medium

You are given a **0-indexed** integer array `nums` of length `n`.

The **sum** **score** of `nums` at an index `i` where `0 <= i < n` is the **maximum** of:

*   The sum of the **first** `i + 1` elements of `nums`.
*   The sum of the **last** `n - i` elements of `nums`.

Return _the **maximum** **sum** **score** of_ `nums` _at any index._

**Example 1:**

**Input:** nums = \[4,3,-2,5\]
**Output:** 10
**Explanation:**
The sum score at index 0 is max(4, 4 + 3 + -2 + 5) = max(4, 10) = 10.
The sum score at index 1 is max(4 + 3, 3 + -2 + 5) = max(7, 6) = 7.
The sum score at index 2 is max(4 + 3 + -2, -2 + 5) = max(5, 3) = 5.
The sum score at index 3 is max(4 + 3 + -2 + 5, 5) = max(10, 5) = 10.
The maximum sum score of nums is 10.

**Example 2:**

**Input:** nums = \[-3,-5\]
**Output:** -3
**Explanation:**
The sum score at index 0 is max(-3, -3 + -5) = max(-3, -8) = -3.
The sum score at index 1 is max(-3 + -5, -5) = max(-8, -5) = -5.
The maximum sum score of nums is -3.

**Constraints:**

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

## A solution in Java

```java
import java.util.ArrayList;

public int maxWordsInSentence(ArrayList<String> sentences) {
    int maxWords = 0;
    for (String sentence : sentences) {
        String[] words = sentence.split(" ");
        maxWords = Math.max(maxWords, words.length);
    }
    return maxWords;
}
```
The algorithm is simple and common across all languages.

1. Initialize a variable `maxWords` to store the maximum number of words found so far, initially set to 0.
2. Loop through the given sentences in the list/array:
   a. For each sentence, split it into words using space as a delimiter.
   b. Count the number of words (`words`) in the sentence.
   c. Update `maxWords` by taking the maximum of `maxWords` and `words` count of the current sentence.
3. Return `maxWords` after iterating through all sentences.

The algorithm has a time complexity of O(N * M), where N is the number of sentences and M is the average number of words per sentence (because string split or stream operations take O(M) time).

## A solution in C++

```cpp
#include<string>
#include<vector>
#include<sstream>
int maxWordsInSentence(std::vector<std::string>& sentences) {
    int maxWords = 0;
    for (const std::string& sentence : sentences) {
        std::istringstream iss(sentence);
        int words = 0;
        std::string word;
        while (iss >> word) {
            words++;
        }
        maxWords = std::max(maxWords, words);
    }
    return maxWords;
}
```
The algorithm is simple and common across all languages.

1. Initialize a variable `maxWords` to store the maximum number of words found so far, initially set to 0.
2. Loop through the given sentences in the list/array:
   a. For each sentence, split it into words using space as a delimiter.
   b. Count the number of words (`words`) in the sentence.
   c. Update `maxWords` by taking the maximum of `maxWords` and `words` count of the current sentence.
3. Return `maxWords` after iterating through all sentences.

The algorithm has a time complexity of O(N * M), where N is the number of sentences and M is the average number of words per sentence (because string split or stream operations take O(M) time).

## A solution in Python

```python
def max_words_in_sentence(sentences):
    max_words = 0
    for sentence in sentences:
        words = len(sentence.split())
        max_words = max(max_words, words)
    return max_words
```
The algorithm is simple and common across all languages.

1. Initialize a variable `maxWords` to store the maximum number of words found so far, initially set to 0.
2. Loop through the given sentences in the list/array:
   a. For each sentence, split it into words using space as a delimiter.
   b. Count the number of words (`words`) in the sentence.
   c. Update `maxWords` by taking the maximum of `maxWords` and `words` count of the current sentence.
3. Return `maxWords` after iterating through all sentences.

The algorithm has a time complexity of O(N * M), where N is the number of sentences and M is the average number of words per sentence (because string split or stream operations take O(M) time).

## A solution in Javascript

```javascript
function maxWordsInSentence(sentences) {
    let maxWords = 0;
    for (let sentence of sentences) {
        let words = sentence.split(" ");
        maxWords = Math.max(maxWords, words.length);
    }
    return maxWords;
}
```
The algorithm is simple and common across all languages.

1. Initialize a variable `maxWords` to store the maximum number of words found so far, initially set to 0.
2. Loop through the given sentences in the list/array:
   a. For each sentence, split it into words using space as a delimiter.
   b. Count the number of words (`words`) in the sentence.
   c. Update `maxWords` by taking the maximum of `maxWords` and `words` count of the current sentence.
3. Return `maxWords` after iterating through all sentences.

The algorithm has a time complexity of O(N * M), where N is the number of sentences and M is the average number of words per sentence (because string split or stream operations take O(M) time).


# Minimum Bit Flips to Convert Number

- slug: minimum-bit-flips-to-convert-number
- difficulty: Easy

A **bit flip** of a number `x` is choosing a bit in the binary representation of `x` and **flipping** it from either `0` to `1` or `1` to `0`.

*   For example, for `x = 7`, the binary representation is `111` and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get `110`, flip the second bit from the right to get `101`, flip the fifth bit from the right (a leading zero) to get `10111`, etc.

Given two integers `start` and `goal`, return _the **minimum** number of **bit flips** to convert_ `start` _to_ `goal`.

**Example 1:**

**Input:** start = 10, goal = 7
**Output:** 3
**Explanation:** The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:
- Flip the first bit from the right: 1010 -> 1011.
- Flip the third bit from the right: 1011 -> 1111.
- Flip the fourth bit from the right: 1111 -> 0111.
It can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.

**Example 2:**

**Input:** start = 3, goal = 4
**Output:** 3
**Explanation:** The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:
- Flip the first bit from the right: 011 -> 010.
- Flip the second bit from the right: 010 -> 000.
- Flip the third bit from the right: 000 -> 100.
It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.

**Constraints:**

*   `0 <= start, goal <= 109`

## A solution in Java

```java
import java.util.*;

class Solution {
    public List<String> makeableRecipes(String[] recipes, String[][] ingredients, String[] supplies) {
        Map<String, Set<String>> dependentRecipes = new HashMap<>();
        Set<String> availableSupplies = new HashSet<>(Arrays.asList(supplies));
        for (int i = 0; i < recipes.length; i++) {
            dependentRecipes.put(recipes[i], new HashSet<>(Arrays.asList(ingredients[i])));
        }

        Queue<String> q = new LinkedList<>();
        for (String supply : availableSupplies) {
            q.offer(supply);
        }

        while (!q.isEmpty()) {
            String currentItem = q.poll();
            for (Map.Entry<String, Set<String>> recipe : dependentRecipes.entrySet()) {
                if (recipe.getValue().contains(currentItem)) {
                    recipe.getValue().remove(currentItem);
                    if (recipe.getValue().isEmpty()) {
                        availableSupplies.add(recipe.getKey());
                        q.offer(recipe.getKey());
                    }
                }
            }
        }

        List<String> result = new ArrayList<>();
        for (String recipe : recipes) {
            if (availableSupplies.contains(recipe)) {
                result.add(recipe);
            }
```
None

## A solution in C++

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

std::vector<std::string> makeableRecipes(std::vector<std::string>& recipes, std::vector<std::vector<std::string>>& ingredients, std::vector<std::string>& supplies) {
    std::unordered_map<std::string, std::unordered_set<std::string>> dependentRecipes;
    std::unordered_set<std::string> availableSupplies(supplies.begin(), supplies.end());
    for (size_t i = 0; i < recipes.size(); ++i) {
        dependentRecipes[recipes[i]] = std::unordered_set<std::string>(ingredients[i].begin(), ingredients[i].end());
    }

    std::queue<std::string> q;
    for (const auto& supply : availableSupplies) {
        q.push(supply);
    }

    while (!q.empty()) {
        const std::string currentItem = q.front();
        q.pop();
        for (const auto& recipe : dependentRecipes) {
            if (recipe.second.count(currentItem)) {
                recipe.second.erase(currentItem);
                if (recipe.second.empty()) {
                    availableSupplies.insert(recipe.first);
                    q.push(recipe.first);
                }
            }
        }
    }

    std::vector<std::string> result;
    for (const auto& recipe : recipes) {
        if (availableSupplies.count(recipe)) {
            result.push_back(recipe);
        }
    }
    return result;
}

```
None

## A solution in Python

    None
    None

## A solution in Javascript

    None
    None


# Find Triangular Sum of an Array

- slug: find-triangular-sum-of-an-array
- difficulty: Medium

You are given a **0-indexed** integer array `nums`, where `nums[i]` is a digit between `0` and `9` (**inclusive**).

The **triangular sum** of `nums` is the value of the only element present in `nums` after the following process terminates:

1.  Let `nums` comprise of `n` elements. If `n == 1`, **end** the process. Otherwise, **create** a new **0-indexed** integer array `newNums` of length `n - 1`.
2.  For each index `i`, where `0 <= i < n - 1`, **assign** the value of `newNums[i]` as `(nums[i] + nums[i+1]) % 10`, where `%` denotes modulo operator.
3.  **Replace** the array `nums` with `newNums`.
4.  **Repeat** the entire process starting from step 1.

Return _the triangular sum of_ `nums`.

**Example 1:**

**Input:** nums = \[1,2,3,4,5\]
**Output:** 8
**Explanation:**
The above diagram depicts the process from which we obtain the triangular sum of the array.

**Example 2:**

**Input:** nums = \[5\]
**Output:** 5
**Explanation:**
Since there is only one element in nums, the triangular sum is the value of that element itself.

**Constraints:**

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

## A solution in Java

```java
boolean isValidParenthesesString(String s, String locked) {
    int balance = 0;
    for (int i = 0; i < s.length(); i++) {
        if (locked.charAt(i) == '0') {
            balance += s.charAt(i) == '(' ? 1 : -1;
            if (balance < 0) return false;
        }
    }
    return balance == 0;
}
```
The algorithm iterates through both the `s` and `locked` strings simultaneously. It keeps track of the balance of open and close parentheses. If the current character of `locked` is '0', it means the current character of `s` can be toggled. Depending on its value, either increment or decrement the balance. If balance becomes negative at any point, it means there is an unmatched ')' so we return false. After the iteration, if the balance is 0, it implies that we have an equal number of '(' and ')' and thus a valid parentheses string, so we return true. Otherwise, we return false.

## A solution in C++

```cpp
bool isValidParenthesesString(std::string s, std::string locked) {
    int balance = 0;
    for (int i = 0; i < s.length(); i++) {
        if (locked[i] == '0') {
            s[i] == '(' ? balance++ : balance--;
            if (balance < 0) return false;
        }
    }
    return balance == 0;
}
```
The algorithm iterates through both the `s` and `locked` strings simultaneously. It keeps track of the balance of open and close parentheses. If the current character of `locked` is '0', it means the current character of `s` can be toggled. Depending on its value, either increment or decrement the balance. If balance becomes negative at any point, it means there is an unmatched ')' so we return false. After the iteration, if the balance is 0, it implies that we have an equal number of '(' and ')' and thus a valid parentheses string, so we return true. Otherwise, we return false.

## A solution in Python

```python
def is_valid_parentheses_string(s: str, locked: str) -> bool:
    balance = 0
    for i in range(len(s)):
        if locked[i] == '0':
            balance += 1 if s[i] == '(' else -1
            if balance < 0:
                return False
    return balance == 0
```
The algorithm iterates through both the `s` and `locked` strings simultaneously. It keeps track of the balance of open and close parentheses. If the current character of `locked` is '0', it means the current character of `s` can be toggled. Depending on its value, either increment or decrement the balance. If balance becomes negative at any point, it means there is an unmatched ')' so we return false. After the iteration, if the balance is 0, it implies that we have an equal number of '(' and ')' and thus a valid parentheses string, so we return true. Otherwise, we return false.

## A solution in Javascript

```javascript
function isValidParenthesesString(s, locked) {
    let balance = 0;
    for (let i = 0; i < s.length; i++) {
        if (locked[i] === '0') {
            balance += s[i] === '(' ? 1 : -1;
            if (balance < 0) return false;
        }
    }
    return balance === 0;
}
```
The algorithm iterates through both the `s` and `locked` strings simultaneously. It keeps track of the balance of open and close parentheses. If the current character of `locked` is '0', it means the current character of `s` can be toggled. Depending on its value, either increment or decrement the balance. If balance becomes negative at any point, it means there is an unmatched ')' so we return false. After the iteration, if the balance is 0, it implies that we have an equal number of '(' and ')' and thus a valid parentheses string, so we return true. Otherwise, we return false.


# Number of Ways to Select Buildings

- slug: number-of-ways-to-select-buildings
- difficulty: Medium

You are given a **0-indexed** binary string `s` which represents the types of buildings along a street where:

*   `s[i] = '0'` denotes that the `ith` building is an office and
*   `s[i] = '1'` denotes that the `ith` building is a restaurant.

As a city official, you would like to **select** 3 buildings for random inspection. However, to ensure variety, **no two consecutive** buildings out of the **selected** buildings can be of the same type.

*   For example, given `s = "0**0**1**1**0**1** "`, we cannot select the `1st`, `3rd`, and `5th` buildings as that would form `"0**11** "` which is **not** allowed due to having two consecutive buildings of the same type.

Return _the **number of valid ways** to select 3 buildings._

**Example 1:**

**Input:** s =  "001101 "
**Output:** 6
**Explanation:**
The following sets of indices selected are valid:
- \[0,2,4\] from  "**0**0**1**1**0**1 " forms  "010 "
- \[0,3,4\] from  "**0**01**10**1 " forms  "010 "
- \[1,2,4\] from  "0**01**1**0**1 " forms  "010 "
- \[1,3,4\] from  "0**0**1**10**1 " forms  "010 "
- \[2,4,5\] from  "00**1**1**01** " forms  "101 "
- \[3,4,5\] from  "001**101** " forms  "101 "
No other selection is valid. Thus, there are 6 total ways.

**Example 2:**

**Input:** s =  "11100 "
**Output:** 0
**Explanation:** It can be shown that there are no valid selections.

**Constraints:**

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

## A solution in Java

```java
public String abbreviatedProduct(int left, int right) {
    long product = 1;
    for (int i = left; i <= right; i++) {
        product *= i;
    }
    return Long.toString(product);
}
```
The algorithm for this problem is quite simple. We just need to calculate the product of all integers between left and right, inclusive. To do this, we initialize a variable `product` as 1, and then iterate through all integers in the range [left, right], multiplying the `product` variable by each of these integers. After we've iterated through all integers in the range, `product` will have the result of the multiplication. Finally, we convert the product into a string format and return it. Since the input integers are positive, the product will always be non-negative.

Please note that this code may not work for very large ranges or numbers due to the limitation of number representation in each language. If more precision or the ability to handle larger numbers is required, you can consider using specialized libraries for arbitrary-precision arithmetic like GMP (C++), BigInteger (Java), or bigint (JavaScript). In Python, you don't need an external library, as you can use Python's built-in support for large integers.

## A solution in C++

```cpp
#include <string>
std::string abbreviatedProduct(int left, int right) {
    long long product = 1;
    for (int i = left; i <= right; ++i) {
        product *= i;
    }
    return std::to_string(product);
}
```
The algorithm for this problem is quite simple. We just need to calculate the product of all integers between left and right, inclusive. To do this, we initialize a variable `product` as 1, and then iterate through all integers in the range [left, right], multiplying the `product` variable by each of these integers. After we've iterated through all integers in the range, `product` will have the result of the multiplication. Finally, we convert the product into a string format and return it. Since the input integers are positive, the product will always be non-negative.

Please note that this code may not work for very large ranges or numbers due to the limitation of number representation in each language. If more precision or the ability to handle larger numbers is required, you can consider using specialized libraries for arbitrary-precision arithmetic like GMP (C++), BigInteger (Java), or bigint (JavaScript). In Python, you don't need an external library, as you can use Python's built-in support for large integers.

## A solution in Python

```python
def abbreviated_product(left: int, right: int) -> str:
    product = 1
    for i in range(left, right + 1):
        product *= i
    return str(product)
```
The algorithm for this problem is quite simple. We just need to calculate the product of all integers between left and right, inclusive. To do this, we initialize a variable `product` as 1, and then iterate through all integers in the range [left, right], multiplying the `product` variable by each of these integers. After we've iterated through all integers in the range, `product` will have the result of the multiplication. Finally, we convert the product into a string format and return it. Since the input integers are positive, the product will always be non-negative.

Please note that this code may not work for very large ranges or numbers due to the limitation of number representation in each language. If more precision or the ability to handle larger numbers is required, you can consider using specialized libraries for arbitrary-precision arithmetic like GMP (C++), BigInteger (Java), or bigint (JavaScript). In Python, you don't need an external library, as you can use Python's built-in support for large integers.

## A solution in Javascript

```javascript
function abbreviatedProduct(left, right) {
    let product = 1;
    for (let i = left; i <= right; i++) {
        product *= i;
    }
    return product.toString();
}
```
The algorithm for this problem is quite simple. We just need to calculate the product of all integers between left and right, inclusive. To do this, we initialize a variable `product` as 1, and then iterate through all integers in the range [left, right], multiplying the `product` variable by each of these integers. After we've iterated through all integers in the range, `product` will have the result of the multiplication. Finally, we convert the product into a string format and return it. Since the input integers are positive, the product will always be non-negative.

Please note that this code may not work for very large ranges or numbers due to the limitation of number representation in each language. If more precision or the ability to handle larger numbers is required, you can consider using specialized libraries for arbitrary-precision arithmetic like GMP (C++), BigInteger (Java), or bigint (JavaScript). In Python, you don't need an external library, as you can use Python's built-in support for large integers.


# Sum of Scores of Built Strings

- slug: sum-of-scores-of-built-strings
- difficulty: Hard

You are **building** a string `s` of length `n` **one** character at a time, **prepending** each new character to the **front** of the string. The strings are labeled from `1` to `n`, where the string with length `i` is labeled `si`.

*   For example, for `s = "abaca "`, `s1 == "a "`, `s2 == "ca "`, `s3 == "aca "`, etc.

The **score** of `si` is the length of the **longest common prefix** between `si` and `sn` (Note that `s == sn`).

Given the final string `s`, return _the **sum** of the **score** of every_ `si`.

**Example 1:**

**Input:** s =  "babab "
**Output:** 9
**Explanation:**
For s1 ==  "b ", the longest common prefix is  "b " which has a score of 1.
For s2 ==  "ab ", there is no common prefix so the score is 0.
For s3 ==  "bab ", the longest common prefix is  "bab " which has a score of 3.
For s4 ==  "abab ", there is no common prefix so the score is 0.
For s5 ==  "babab ", the longest common prefix is  "babab " which has a score of 5.
The sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.

**Example 2:**

**Input:** s =  "azbazbzaz "
**Output:** 14
**Explanation:**
For s2 ==  "az ", the longest common prefix is  "az " which has a score of 2.
For s6 ==  "azbzaz ", the longest common prefix is  "azb " which has a score of 3.
For s9 ==  "azbazbzaz ", the longest common prefix is  "azbazbzaz " which has a score of 9.
For all other si, the score is 0.
The sum of the scores is 2 + 3 + 9 = 14, so we return 14.

**Constraints:**

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

## A solution in Java

```java
public int stringSumScores(String s){
    int score = 0;
    int prefix_length = 0;

    for (int i = s.length() - 1; i >= 0; i--) {
        if (s.charAt(i) == s.charAt(s.length() - 1)) {
            prefix_length++;
        } else {
            prefix_length = 0;
        }
        score += prefix_length;
    }
    return score;
}

```
The algorithm starts iterating from the end of the string `s` to the beginning. For each character, it checks if the character is equal to the last character of the string. If the character is equal, it increases the `prefix_length` counter, otherwise, it resets the `prefix_length` to 0. We update the `score` by adding the `prefix_length` after each iteration.

As we are prepending the new characters to the front of the string, iterating in reverse order will generate the desired strings (s_i) in the correct order.

## A solution in C++

```cpp
int stringSumScores(const std::string &s) {
    int score = 0;
    int prefix_length = 0;

    for (int i = s.size() - 1; i >= 0; i--) {
        if (s[i] == s[s.size() - 1]) {
            prefix_length++;
        } else {
            prefix_length = 0;
        }
        score += prefix_length;
    }
    return score;
}
```
The algorithm starts iterating from the end of the string `s` to the beginning. For each character, it checks if the character is equal to the last character of the string. If the character is equal, it increases the `prefix_length` counter, otherwise, it resets the `prefix_length` to 0. We update the `score` by adding the `prefix_length` after each iteration.

As we are prepending the new characters to the front of the string, iterating in reverse order will generate the desired strings (s_i) in the correct order.

## A solution in Python

```python
def string_sum_scores(s):
    score = 0
    prefix_length = 0

    for i in range(len(s) - 1, -1, -1):
        if s[i] == s[-1]:
            prefix_length += 1
        else:
            prefix_length = 0
        score += prefix_length

    return score
```
The algorithm starts iterating from the end of the string `s` to the beginning. For each character, it checks if the character is equal to the last character of the string. If the character is equal, it increases the `prefix_length` counter, otherwise, it resets the `prefix_length` to 0. We update the `score` by adding the `prefix_length` after each iteration.

As we are prepending the new characters to the front of the string, iterating in reverse order will generate the desired strings (s_i) in the correct order.

## A solution in Javascript

```javascript
function stringSumScores(s) {
    let score = 0;
    let prefix_length = 0;

    for (let i = s.length - 1; i >= 0; i--) {
        if (s[i] === s[s.length - 1]) {
            prefix_length++;
        } else {
            prefix_length = 0;
        }
        score += prefix_length;
    }
    return score;
}
```
The algorithm starts iterating from the end of the string `s` to the beginning. For each character, it checks if the character is equal to the last character of the string. If the character is equal, it increases the `prefix_length` counter, otherwise, it resets the `prefix_length` to 0. We update the `score` by adding the `prefix_length` after each iteration.

As we are prepending the new characters to the front of the string, iterating in reverse order will generate the desired strings (s_i) in the correct order.


# Minimum Number of Operations to Convert Time

- slug: minimum-number-of-operations-to-convert-time
- difficulty: Easy

You are given two strings `current` and `correct` representing two **24-hour times**.

24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`.

In one operation you can increase the time `current` by `1`, `5`, `15`, or `60` minutes. You can perform this operation **any** number of times.

Return _the **minimum number of operations** needed to convert_ `current` _to_ `correct`.

**Example 1:**

**Input:** current =  "02:30 ", correct =  "04:35 "
**Output:** 3
**Explanation:**
We can convert current to correct in 3 operations as follows:
- Add 60 minutes to current. current becomes  "03:30 ".
- Add 60 minutes to current. current becomes  "04:30 ".
- Add 5 minutes to current. current becomes  "04:35 ".
It can be proven that it is not possible to convert current to correct in fewer than 3 operations.

**Example 2:**

**Input:** current =  "11:00 ", correct =  "11:01 "
**Output:** 1
**Explanation:** We only have to add one minute to current, so the minimum number of operations needed is 1.

**Constraints:**

*   `current` and `correct` are in the format `"HH:MM "`
*   `current <= correct`

## A solution in Java

```java
int minimumOperations(String current, String correct) {
    int ch = Integer.parseInt(current.substring(0, 2)), cm = Integer.parseInt(current.substring(3));
    int th = Integer.parseInt(correct.substring(0,2)), tm = Integer.parseInt(correct.substring(3));
    int ct = ch * 60 + cm, tt = th * 60 + tm;

    int operations = 0;
    while (ct < tt) {
        if (tt - ct >= 60)
            ct += 60;
        else if (tt - ct >= 15)
            ct += 15;
        else if (tt - ct >= 5)
            ct += 5;
        else
            ct += 1;

        operations++;
    }
    return operations;
}
```
The approach to solving this problem is fairly straightforward. First, we parse the input strings 'current' and 'correct' into hours and minutes. We then calculate the total minutes for both 'current' (ct) and 'correct' (tt).

We initialize a variable `operations` tokeep track of the minimum number of operations needed.

Using a while loop, we check if ct is smaller than tt indicating that we still need to perform operations. In each iteration, we choose the largest operation possible (60, 15, 5, or 1 minute(s)) based on the difference between tt and ct. After performing the operation, we increment the operations counter.

The final result is the value of the `operations` counter at the end of the loop.

## A solution in C++

```cpp
int minimumOperations(string current, string correct) {
    int ch = stoi(current.substr(0, 2)), cm = stoi(current.substr(3));
    int th = stoi(correct.substr(0, 2)), tm = stoi(correct.substr(3));
    int ct = ch * 60 + cm, tt = th * 60 + tm;

    int operations = 0;
    while (ct < tt) {
        if (tt - ct >= 60)
            ct += 60;
        else if (tt - ct >= 15)
            ct += 15;
        else if (tt - ct >= 5)
            ct += 5;
        else
            ct += 1;

        operations++;
    }
    return operations;
}
```
The approach to solving this problem is fairly straightforward. First, we parse the input strings 'current' and 'correct' into hours and minutes. We then calculate the total minutes for both 'current' (ct) and 'correct' (tt).

We initialize a variable `operations` tokeep track of the minimum number of operations needed.

Using a while loop, we check if ct is smaller than tt indicating that we still need to perform operations. In each iteration, we choose the largest operation possible (60, 15, 5, or 1 minute(s)) based on the difference between tt and ct. After performing the operation, we increment the operations counter.

The final result is the value of the `operations` counter at the end of the loop.

## A solution in Python

```python
def minimum_operations(current: str, correct: str) -> int:
    ch, cm = map(int, current.split(':'))
    th, tm = map(int, correct.split(':'))
    ct = ch * 60 + cm
    tt = th * 60 + tm

    operations = 0
    while ct < tt:
        if tt - ct >= 60:
            ct += 60
        elif tt - ct >= 15:
            ct += 15
        elif tt - ct >= 5:
            ct += 5
        else:
            ct += 1

        operations += 1

    return operations
```
The approach to solving this problem is fairly straightforward. First, we parse the input strings 'current' and 'correct' into hours and minutes. We then calculate the total minutes for both 'current' (ct) and 'correct' (tt).

We initialize a variable `operations` tokeep track of the minimum number of operations needed.

Using a while loop, we check if ct is smaller than tt indicating that we still need to perform operations. In each iteration, we choose the largest operation possible (60, 15, 5, or 1 minute(s)) based on the difference between tt and ct. After performing the operation, we increment the operations counter.

The final result is the value of the `operations` counter at the end of the loop.

## A solution in Javascript

```javascript
function minimumOperations(current, correct) {
    let [ch, cm] = current.split(':').map(Number);
    let [th, tm] = correct.split(':').map(Number);
    let ct = ch * 60 + cm, tt = th * 60 + tm;

    let operations = 0;
    while (ct < tt) {
        if (tt - ct >= 60)
            ct += 60;
        else if (tt - ct >= 15)
            ct += 15;
        else if (tt - ct >= 5)
            ct += 5;
        else
            ct += 1;

        operations++;
    }
    return operations;
}
```
The approach to solving this problem is fairly straightforward. First, we parse the input strings 'current' and 'correct' into hours and minutes. We then calculate the total minutes for both 'current' (ct) and 'correct' (tt).

We initialize a variable `operations` tokeep track of the minimum number of operations needed.

Using a while loop, we check if ct is smaller than tt indicating that we still need to perform operations. In each iteration, we choose the largest operation possible (60, 15, 5, or 1 minute(s)) based on the difference between tt and ct. After performing the operation, we increment the operations counter.

The final result is the value of the `operations` counter at the end of the loop.


# Find Players With Zero or One Losses

- slug: find-players-with-zero-or-one-losses
- difficulty: Medium

You are given an integer array `matches` where `matches[i] = [winneri, loseri]` indicates that the player `winneri` defeated player `loseri` in a match.

Return _a list_ `answer` _of size_ `2` _where:_

*   `answer[0]` is a list of all players that have **not** lost any matches.
*   `answer[1]` is a list of all players that have lost exactly **one** match.

The values in the two lists should be returned in **increasing** order.

**Note:**

*   You should only consider the players that have played **at least one** match.
*   The testcases will be generated such that **no** two matches will have the **same** outcome.

**Example 1:**

**Input:** matches = \[\[1,3\],\[2,3\],\[3,6\],\[5,6\],\[5,7\],\[4,5\],\[4,8\],\[4,9\],\[10,4\],\[10,9\]\]
**Output:** \[\[1,2,10\],\[4,5,7,8\]\]
**Explanation:**
Players 1, 2, and 10 have not lost any matches.
Players 4, 5, 7, and 8 each have lost one match.
Players 3, 6, and 9 each have lost two matches.
Thus, answer\[0\] = \[1,2,10\] and answer\[1\] = \[4,5,7,8\].

**Example 2:**

**Input:** matches = \[\[2,3\],\[1,3\],\[5,4\],\[6,4\]\]
**Output:** \[\[1,2,5,6\],\[\]\]
**Explanation:**
Players 1, 2, 5, and 6 have not lost any matches.
Players 3 and 4 each have lost two matches.
Thus, answer\[0\] = \[1,2,5,6\] and answer\[1\] = \[\].

**Constraints:**

*   `1 <= matches.length <= 105`
*   `matches[i].length == 2`
*   `1 <= winneri, loseri <= 105`
*   `winneri != loseri`
*   All `matches[i]` are **unique**.

## A solution in Java

```java
import java.util.*;

public List<Set<Integer>> twoLists(List<List<Integer>> matches) {
    Map<Integer, Integer> loss_count = new HashMap<>();
    Set<Integer> participants = new HashSet<>();

    for (List<Integer> match : matches) {
        int winner = match.get(0);
        int loser = match.get(1);
        loss_count.put(loser, loss_count.getOrDefault(loser, 0) + 1);
        participants.add(winner);
        participants.add(loser);
    }

    Set<Integer> no_losses = new TreeSet<>();
    Set<Integer> one_loss = new TreeSet<>();

    for (int participant : participants) {
        int count = loss_count.getOrDefault(participant, 0);
        if (count == 0) {
            no_losses.add(participant);
        } else if (count == 1) {
            one_loss.add(participant);
        }
    }

    return Arrays.asList(no_losses, one_loss);
}
```
First, we create two data structures: a hash map to store the loss count of each participant, and a set to store all participants. For each match, increment the loss count for the loser and add both winner and loser to the participants set.

Next, we create two sets, one for participants with no losses and another for participants with exactly one loss. Go through each participant in the set and check their loss count. If a participant's loss count is zero or one, add them to the corresponding set.

Finally, return a list containing the no_losses and one_loss sets.

## A solution in C++

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

std::vector<std::set<int>> twoLists(std::vector<std::vector<int>>& matches) {
    std::unordered_map<int, int> loss_count;
    std::set<int> participants;

    for (auto& match : matches) {
        int winner = match[0];
        int loser = match[1];
        loss_count[loser]++;
        participants.insert(winner);
        participants.insert(loser);
    }

    std::set<int> no_losses;
    std::set<int> one_loss;

    for (int participant : participants) {
        if (loss_count[participant] == 0) {
            no_losses.insert(participant);
        } else if (loss_count[participant] == 1) {
            one_loss.insert(participant);
        }
    }

    return {no_losses, one_loss};
}
```
First, we create two data structures: a hash map to store the loss count of each participant, and a set to store all participants. For each match, increment the loss count for the loser and add both winner and loser to the participants set.

Next, we create two sets, one for participants with no losses and another for participants with exactly one loss. Go through each participant in the set and check their loss count. If a participant's loss count is zero or one, add them to the corresponding set.

Finally, return a list containing the no_losses and one_loss sets.

## A solution in Python

```python
from collections import defaultdict
from typing import List, Set

def twoLists(matches: List[List[int]]) -> List[Set[int]]:
    loss_count = defaultdict(int)
    participants = set()

    for winner, loser in matches:
        loss_count[loser] += 1
        participants.add(winner)
        participants.add(loser)

    no_losses = {participant for participant in participants if loss_count[participant] == 0}
    one_loss = {participant for participant in participants if loss_count[participant] == 1}

    return [no_losses, one_loss]
```
First, we create two data structures: a hash map to store the loss count of each participant, and a set to store all participants. For each match, increment the loss count for the loser and add both winner and loser to the participants set.

Next, we create two sets, one for participants with no losses and another for participants with exactly one loss. Go through each participant in the set and check their loss count. If a participant's loss count is zero or one, add them to the corresponding set.

Finally, return a list containing the no_losses and one_loss sets.

## A solution in Javascript

```javascript
function twoLists(matches) {
    const loss_count = new Map();
    const participants = new Set();

    for (const [winner, loser] of matches) {
        loss_count.set(loser, (loss_count.get(loser) || 0) + 1);
        participants.add(winner);
        participants.add(loser);
    }

    const no_losses = new Set();
    const one_loss = new Set();

    for (const participant of participants) {
        const count = loss_count.get(participant) || 0;
        if (count === 0) {
            no_losses.add(participant);
        } else if (count === 1) {
            one_loss.add(participant);
        }
    }

    return [no_losses, one_loss];
}
```
First, we create two data structures: a hash map to store the loss count of each participant, and a set to store all participants. For each match, increment the loss count for the loser and add both winner and loser to the participants set.

Next, we create two sets, one for participants with no losses and another for participants with exactly one loss. Go through each participant in the set and check their loss count. If a participant's loss count is zero or one, add them to the corresponding set.

Finally, return a list containing the no_losses and one_loss sets.


# Maximum Candies Allocated to K Children

- slug: maximum-candies-allocated-to-k-children
- difficulty: Medium

You are given a **0-indexed** integer array `candies`. Each element in the array denotes a pile of candies of size `candies[i]`. You can divide each pile into any number of **sub piles**, but you **cannot** merge two piles together.

You are also given an integer `k`. You should allocate piles of candies to `k` children such that each child gets the **same** number of candies. Each child can take **at most one** pile of candies and some piles of candies may go unused.

Return _the **maximum number of candies** each child can get._

**Example 1:**

**Input:** candies = \[5,8,6\], k = 3
**Output:** 5
**Explanation:** We can divide candies\[1\] into 2 piles of size 5 and 3, and candies\[2\] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.

**Example 2:**

**Input:** candies = \[2,5\], k = 11
**Output:** 0
**Explanation:** There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.

**Constraints:**

*   `1 <= candies.length <= 105`
*   `1 <= candies[i] <= 107`
*   `1 <= k <= 1012`

## A solution in Java

```java
public int countRodsWithAllColors(String rings) {
    int[] rod_colors = new int[10];

    for (int i = 0; i < rings.length(); i += 2) {
        int color = rings.charAt(i) - 'A';
        int rod = rings.charAt(i + 1) - '0';

        rod_colors[rod] |= (1 << color);
    }

    int count = 0;
    for (int colors : rod_colors) {
        if (colors == 7) {
            count++;
        }
    }

    return count;
}
```
1. We will use an array `rod_colors` to represent the color state of each rod. The integer value 7 is used to represent all three colors being present, where each bit corresponds to the different colors (red=001, green=010, blue=100).
2. Loop through the given string `rings` with a step of 2. For each pair of characters, calculate the color and rod index.
3. Using a bitwise OR operation, we update the corresponding rod's color state by OR'ing its current state with the new color bit.
4. Count the number of elements in `rod_colors` array that have a value of 7 (all three color bits set) and return the count.

## A solution in C++

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

int countRodsWithAllColors(const std::string &rings) {
    int rod_colors[10] = {0};

    for (size_t i = 0; i < rings.length(); i += 2) {
        int color = rings[i] - 'A';
        int rod = rings[i + 1] - '0';

        rod_colors[rod] |= (1 << color);
    }

    return std::count(rod_colors, rod_colors + 10, 7);
}
```
1. We will use an array `rod_colors` to represent the color state of each rod. The integer value 7 is used to represent all three colors being present, where each bit corresponds to the different colors (red=001, green=010, blue=100).
2. Loop through the given string `rings` with a step of 2. For each pair of characters, calculate the color and rod index.
3. Using a bitwise OR operation, we update the corresponding rod's color state by OR'ing its current state with the new color bit.
4. Count the number of elements in `rod_colors` array that have a value of 7 (all three color bits set) and return the count.

## A solution in Python

```python
def count_rods_with_all_colors(rings: str) -> int:
    rod_colors = [0] * 10

    for i in range(0, len(rings), 2):
        color = ord(rings[i]) - ord('A')
        rod = int(rings[i + 1])

        rod_colors[rod] |= (1 << color)

    return rod_colors.count(7)
```
1. We will use an array `rod_colors` to represent the color state of each rod. The integer value 7 is used to represent all three colors being present, where each bit corresponds to the different colors (red=001, green=010, blue=100).
2. Loop through the given string `rings` with a step of 2. For each pair of characters, calculate the color and rod index.
3. Using a bitwise OR operation, we update the corresponding rod's color state by OR'ing its current state with the new color bit.
4. Count the number of elements in `rod_colors` array that have a value of 7 (all three color bits set) and return the count.

## A solution in Javascript

```javascript
function countRodsWithAllColors(rings) {
    let rod_colors = new Array(10).fill(0);

    for (let i = 0; i < rings.length; i += 2) {
        let color = rings.charCodeAt(i) - 'A'.charCodeAt(0);
        let rod = parseInt(rings[i + 1]);

        rod_colors[rod] |= (1 << color);
    }

    return rod_colors.filter(x => x === 7).length;
}
```
1. We will use an array `rod_colors` to represent the color state of each rod. The integer value 7 is used to represent all three colors being present, where each bit corresponds to the different colors (red=001, green=010, blue=100).
2. Loop through the given string `rings` with a step of 2. For each pair of characters, calculate the color and rod index.
3. Using a bitwise OR operation, we update the corresponding rod's color state by OR'ing its current state with the new color bit.
4. Count the number of elements in `rod_colors` array that have a value of 7 (all three color bits set) and return the count.


# Encrypt and Decrypt Strings

- slug: encrypt-and-decrypt-strings
- difficulty: Hard

You are given a character array `keys` containing **unique** characters and a string array `values` containing strings of length 2. You are also given another string array `dictionary` that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a **0-indexed** string.

A string is **encrypted** with the following process:

1.  For each character `c` in the string, we find the index `i` satisfying `keys[i] == c` in `keys`.
2.  Replace `c` with `values[i]` in the string.

Note that in case a character of the string is **not present** in `keys`, the encryption process cannot be carried out, and an empty string `" "` is returned.

A string is **decrypted** with the following process:

1.  For each substring `s` of length 2 occurring at an even index in the string, we find an `i` such that `values[i] == s`. If there are multiple valid `i`, we choose **any** one of them. This means a string could have multiple possible strings it can decrypt to.
2.  Replace `s` with `keys[i]` in the string.

Implement the `Encrypter` class:

*   `Encrypter(char[] keys, String[] values, String[] dictionary)` Initializes the `Encrypter` class with `keys, values`, and `dictionary`.
*   `String encrypt(String word1)` Encrypts `word1` with the encryption process described above and returns the encrypted string.
*   `int decrypt(String word2)` Returns the number of possible strings `word2` could decrypt to that also appear in `dictionary`.

**Example 1:**

**Input**
\[ "Encrypter ",  "encrypt ",  "decrypt "\]
\[\[\['a', 'b', 'c', 'd'\], \[ "ei ",  "zf ",  "ei ",  "am "\], \[ "abcd ",  "acbd ",  "adbc ",  "badc ",  "dacb ",  "cadb ",  "cbda ",  "abad "\]\], \[ "abcd "\], \[ "eizfeiam "\]\]
**Output**
\[null,  "eizfeiam ", 2\]

**Explanation**
Encrypter encrypter = new Encrypter(\[\['a', 'b', 'c', 'd'\], \[ "ei ",  "zf ",  "ei ",  "am "\], \[ "abcd ",  "acbd ",  "adbc ",  "badc ",  "dacb ",  "cadb ",  "cbda ",  "abad "\]);
encrypter.encrypt( "abcd "); // return  "eizfeiam ".
                           // 'a' maps to  "ei ", 'b' maps to  "zf ", 'c' maps to  "ei ", and 'd' maps to  "am ".
encrypter.decrypt( "eizfeiam "); // return 2.
                              //  "ei " can map to 'a' or 'c',  "zf " maps to 'b', and  "am " maps to 'd'.
                              // Thus, the possible strings after decryption are  "abad ",  "cbad ",  "abcd ", and  "cbcd ".
                              // 2 of those strings,  "abad " and  "abcd ", appear in dictionary, so the answer is 2.

**Constraints:**

*   `1 <= keys.length == values.length <= 26`
*   `values[i].length == 2`
*   `1 <= dictionary.length <= 100`
*   `1 <= dictionary[i].length <= 100`
*   All `keys[i]` and `dictionary[i]` are **unique**.
*   `1 <= word1.length <= 2000`
*   `1 <= word2.length <= 200`
*   All `word1[i]` appear in `keys`.
*   `word2.length` is even.
*   `keys`, `values[i]`, `dictionary[i]`, `word1`, and `word2` only contain lowercase English letters.
*   At most `200` calls will be made to `encrypt` and `decrypt` **in total**.

## A solution in Java

```java
public int sumOfSubarrayRanges(int[] nums) {
    int n = nums.length;
    int ans = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = i; j < n; ++j) {
            ans += maxElement(nums, i, j) - minElement(nums, i, j);
        }
    }
    return ans;
}

private int maxElement(int[] nums, int start, int end) {
    int max = nums[start];
    for (int i = start + 1; i <= end; ++i) {
        max = Math.max(max, nums[i]);
    }
    return max;
}

private int minElement(int[] nums, int start, int end) {
    int min = nums[start];
    for (int i = start + 1; i <= end; ++i) {
        min = Math.min(min, nums[i]);
    }
    return min;
}
```
The algorithm is a straightforward brute force solution which calculates the range of all possible subarrays and then sums them up. The solution iterates through all possible subarray starting positions (i) and ending positions (j), and for each subarray, it computes the maximum and minimum element. The sum of all subarray ranges is updated by incrementing the answer variable by the difference between the maximum and minimum elements (the range) for each subarray. This is implemented similarly in all four languages using nested loops.

## A solution in C++

```cpp
int sumOfSubarrayRanges(vector<int>& nums) {
    int n = nums.size();
    int ans = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = i; j < n; ++j) {
            ans += *max_element(nums.begin() + i, nums.begin() + j + 1) -
                   *min_element(nums.begin() + i, nums.begin() + j + 1);
        }
    }
    return ans;
}
```
The algorithm is a straightforward brute force solution which calculates the range of all possible subarrays and then sums them up. The solution iterates through all possible subarray starting positions (i) and ending positions (j), and for each subarray, it computes the maximum and minimum element. The sum of all subarray ranges is updated by incrementing the answer variable by the difference between the maximum and minimum elements (the range) for each subarray. This is implemented similarly in all four languages using nested loops.

## A solution in Python

```python
def sum_of_subarray_ranges(nums):
    n = len(nums)
    ans = 0
    for i in range(n):
        for j in range(i, n):
            ans += max(nums[i:j+1]) - min(nums[i:j+1])
    return ans
```
The algorithm is a straightforward brute force solution which calculates the range of all possible subarrays and then sums them up. The solution iterates through all possible subarray starting positions (i) and ending positions (j), and for each subarray, it computes the maximum and minimum element. The sum of all subarray ranges is updated by incrementing the answer variable by the difference between the maximum and minimum elements (the range) for each subarray. This is implemented similarly in all four languages using nested loops.

## A solution in Javascript

```javascript
function sumOfSubarrayRanges(nums) {
    let n = nums.length;
    let ans = 0;
    for (let i = 0; i < n; ++i) {
        for (let j = i; j < n; ++j) {
            ans += Math.max(...nums.slice(i, j + 1)) - Math.min(...nums.slice(i, j + 1));
        }
    }
    return ans;
}
```
The algorithm is a straightforward brute force solution which calculates the range of all possible subarrays and then sums them up. The solution iterates through all possible subarray starting positions (i) and ending positions (j), and for each subarray, it computes the maximum and minimum element. The sum of all subarray ranges is updated by incrementing the answer variable by the difference between the maximum and minimum elements (the range) for each subarray. This is implemented similarly in all four languages using nested loops.


# Check if an Array Is Consecutive

- slug: check-if-an-array-is-consecutive
- difficulty: Easy

Given an integer array `nums`, return `true` _if_ `nums` _is **consecutive**, otherwise return_ `false`_._

An array is **consecutive** if it contains every number in the range `[x, x + n - 1]` (**inclusive**), where `x` is the minimum number in the array and `n` is the length of the array.

**Example 1:**

**Input:** nums = \[1,3,4,2\]
**Output:** true
**Explanation:**
The minimum value is 1 and the length of nums is 4.
All of the values in the range \[x, x + n - 1\] = \[1, 1 + 4 - 1\] = \[1, 4\] = (1, 2, 3, 4) occur in nums.
Therefore, nums is consecutive.

**Example 2:**

**Input:** nums = \[1,3\]
**Output:** false
**Explanation:**
The minimum value is 1 and the length of nums is 2.
The value 2 in the range \[x, x + n - 1\] = \[1, 1 + 2 - 1\], = \[1, 2\] = (1, 2) does not occur in nums.
Therefore, nums is not consecutive.

**Example 3:**

**Input:** nums = \[3,5,4\]
**Output:** true
**Explanation:**
The minimum value is 3 and the length of nums is 3.
All of the values in the range \[x, x + n - 1\] = \[3, 3 + 3 - 1\] = \[3, 5\] = (3, 4, 5) occur in nums.
Therefore, nums is consecutive.

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int maxFruits(int[][] fruits, int startPos, int k) {
    int n = fruits.length;
    int[] left = new int[n + 1], right = new int[n + 1];
    int j = 0;

    for (int i = 0; i < n; i++) {
        while (j < n && fruits[j][0] - fruits[i][0] <= k) {
            right[i + 1] += fruits[j][1];
            j++;
        }
        right[i + 1] += right[i];
        if (j < n && fruits[j][0] - startPos <= k) {
            right[0] += fruits[j][1];
            j++;
        }
    }

    j = n - 1;
    for (int i = n - 1; i >= 0; i--) {
        while (j >= 0 && fruits[j][0] - fruits[i][0] <= k) {
            left[i] += fruits[j][1];
            j--;
        }
        left[i] += left[i + 1];
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
        int rest = Math.max(0, k - Math.abs(fruits[i][0] - startPos));
        int idx = Arrays.binarySearch(fruits, i, n, new int[]{fruits[i][0] + rest, Integer.MIN_VALUE}, (a, b) -> a[0] - b[0]);
        if (idx < 0) idx = ~idx;
        ans = Math.max(ans, left[i] + right[idx]);
    }
    return ans;
}
```
1. Create left and right arrays of size n+1 filled with zeros, to store the cumulative fruits at each position.
2. Initialize a cursor j with value 0.
3. Iterate the fruits array and populate the right array with total fruits in the range of k units.
4. Then populate the left array with the remaining fruits by iterating the array in reverse order.
5. Initialize an answer variable, ans, to 0.
6. Iterate the fruits array again, calculating the remaining steps after reaching a position and using a binary search technique (in each language) to find the index of the next fruit that can be reached. Update ans with the maximum sum of fruit harvest.
7. Finally, return ans as the solution.

## A solution in C++

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

int maxFruits(vector<vector<int>>& fruits, int startPos, int k) {
    int n = fruits.size();
    vector<int> left(n + 1, 0), right(n + 1, 0);
    int j = 0;

    for (int i = 0; i < n; i++) {
        while (j < n && fruits[j][0] - fruits[i][0] <= k) {
            right[i + 1] += fruits[j][1];
            j++;
        }
        right[i + 1] += right[i];
        if (j < n && fruits[j][0] - startPos <= k) {
            right[0] += fruits[j][1];
            j++;
        }
    }

    j = n - 1;
    for (int i = n - 1; i >= 0; i--) {
        while (j >= 0 && fruits[j][0] - fruits[i][0] <= k) {
            left[i] += fruits[j][1];
            j--;
        }
        left[i] += left[i + 1];
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
        int rest = max(0, k - abs(fruits[i][0] - startPos));
        int idx = upper_bound(fruits.begin(), fruits.end(), vector<int>{fruits[i][0] + rest, 0}) - fruits.begin();
        ans = max(ans, left[i] + right[idx]);
    }
    return ans;
}
```
1. Create left and right arrays of size n+1 filled with zeros, to store the cumulative fruits at each position.
2. Initialize a cursor j with value 0.
3. Iterate the fruits array and populate the right array with total fruits in the range of k units.
4. Then populate the left array with the remaining fruits by iterating the array in reverse order.
5. Initialize an answer variable, ans, to 0.
6. Iterate the fruits array again, calculating the remaining steps after reaching a position and using a binary search technique (in each language) to find the index of the next fruit that can be reached. Update ans with the maximum sum of fruit harvest.
7. Finally, return ans as the solution.

## A solution in Python

```python
from bisect import bisect_left

def maxFruits(fruits, startPos, k):
    n = len(fruits)
    left, right = [0] * (n + 1), [0] * (n + 1)
    j = 0

    for i in range(n):
        while j < n and fruits[j][0] - fruits[i][0] <= k:
            right[i + 1] += fruits[j][1]
            j += 1
        right[i + 1] += right[i]
        if j < n and fruits[j][0] - startPos <= k:
            right[0] += fruits[j][1]
            j += 1

    j = n - 1
    for i in range(n - 1, -1, -1):
        while j >= 0 and fruits[j][0] - fruits[i][0] <= k:
            left[i] += fruits[j][1]
            j -= 1
        left[i] += left[i + 1]

    ans = 0
    for i in range(n):
        rest = max(0, k - abs(fruits[i][0] - startPos))
        idx = bisect_left(fruits, [fruits[i][0] + rest, 0])
        ans = max(ans, left[i] + right[idx])

    return ans
```
1. Create left and right arrays of size n+1 filled with zeros, to store the cumulative fruits at each position.
2. Initialize a cursor j with value 0.
3. Iterate the fruits array and populate the right array with total fruits in the range of k units.
4. Then populate the left array with the remaining fruits by iterating the array in reverse order.
5. Initialize an answer variable, ans, to 0.
6. Iterate the fruits array again, calculating the remaining steps after reaching a position and using a binary search technique (in each language) to find the index of the next fruit that can be reached. Update ans with the maximum sum of fruit harvest.
7. Finally, return ans as the solution.

## A solution in Javascript

```javascript
function maxFruits(fruits, startPos, k) {
    const n = fruits.length;
    const left = new Array(n + 1).fill(0);
    const right = new Array(n + 1).fill(0);
    let j = 0;

    for (let i = 0; i < n; i++) {
        while (j < n && fruits[j][0] - fruits[i][0] <= k) {
            right[i + 1] += fruits[j][1];
            j++;
        }
        right[i + 1] += right[i];
        if (j < n && fruits[j][0] - startPos <= k) {
            right[0] += fruits[j][1];
            j++;
        }
    }

    j = n - 1;
    for (let i = n - 1; i >= 0; i--) {
        while (j >= 0 && fruits[j][0] - fruits[i][0] <= k) {
            left[i] += fruits[j][1];
            j--;
        }
        left[i] += left[i + 1];
    }

    let ans = 0;
    for (let i = 0; i < n; i++) {
        const rest = Math.max(0, k - Math.abs(fruits[i][0] - startPos));
        const idx = fruits.findIndex((a) => a[0] >= fruits[i][0] + rest);
        ans = Math.max(ans, left[i] + right[(idx === -1) ? n : idx]);
    }

    return ans;
}
```
1. Create left and right arrays of size n+1 filled with zeros, to store the cumulative fruits at each position.
2. Initialize a cursor j with value 0.
3. Iterate the fruits array and populate the right array with total fruits in the range of k units.
4. Then populate the left array with the remaining fruits by iterating the array in reverse order.
5. Initialize an answer variable, ans, to 0.
6. Iterate the fruits array again, calculating the remaining steps after reaching a position and using a binary search technique (in each language) to find the index of the next fruit that can be reached. Update ans with the maximum sum of fruit harvest.
7. Finally, return ans as the solution.


# Largest Number After Digit Swaps by Parity

- slug: largest-number-after-digit-swaps-by-parity
- difficulty: Easy

You are given a positive integer `num`. You may swap any two digits of `num` that have the same **parity** (i.e. both odd digits or both even digits).

Return _the **largest** possible value of_ `num` _after **any** number of swaps._

**Example 1:**

**Input:** num = 1234
**Output:** 3412
**Explanation:** Swap the digit 3 with the digit 1, this results in the number 3214.
Swap the digit 2 with the digit 4, this results in the number 3412.
Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.

**Example 2:**

**Input:** num = 65875
**Output:** 87655
**Explanation:** Swap the digit 8 with the digit 6, this results in the number 85675.
Swap the first digit 5 with the digit 7, this results in the number 87655.
Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.

**Constraints:**

*   `1 <= num <= 109`

## A solution in Java

```java
import java.util.List;

public String firstPalindrome(List<String> words) {
    for (String word : words) {
        String reversedWord = new StringBuilder(word).reverse().toString();
        if (word.equals(reversedWord)) {
            return word;
        }
    }
    return "";
}
```
The algorithm used in each function iterates through the given array of strings, and for each string, it checks if it's a palindrome by comparing it to its reversed version. If a palindrome is found, it immediately returns that string. If no palindromes are found after iterating through the entire array, an empty string is returned. Each language's implementation follows similar logic, with some differences:

- C++: We use a range-based loop to iterate through the words, and the `std::reverse()` function to reverse the string.
- Java: We use a `StringBuilder` to reverse the string, and the `equals()` method to compare the strings.
- Python: A Pythonic approach is used with slicing to reverse the string.
- JavaScript: We use the `split()`, `reverse()`, and `join()` methods to reverse the string.

## A solution in C++

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

std::string firstPalindrome(const std::vector<std::string>& words) {
    for (const std::string& word : words) {
        std::string reversedWord = word;
        std::reverse(reversedWord.begin(), reversedWord.end());
        if (word == reversedWord) {
            return word;
        }
    }
    return "";
}
```
The algorithm used in each function iterates through the given array of strings, and for each string, it checks if it's a palindrome by comparing it to its reversed version. If a palindrome is found, it immediately returns that string. If no palindromes are found after iterating through the entire array, an empty string is returned. Each language's implementation follows similar logic, with some differences:

- C++: We use a range-based loop to iterate through the words, and the `std::reverse()` function to reverse the string.
- Java: We use a `StringBuilder` to reverse the string, and the `equals()` method to compare the strings.
- Python: A Pythonic approach is used with slicing to reverse the string.
- JavaScript: We use the `split()`, `reverse()`, and `join()` methods to reverse the string.

## A solution in Python

```python
def first_palindrome(words):
    for word in words:
        if word == word[::-1]:
            return word
    return ""
```
The algorithm used in each function iterates through the given array of strings, and for each string, it checks if it's a palindrome by comparing it to its reversed version. If a palindrome is found, it immediately returns that string. If no palindromes are found after iterating through the entire array, an empty string is returned. Each language's implementation follows similar logic, with some differences:

- C++: We use a range-based loop to iterate through the words, and the `std::reverse()` function to reverse the string.
- Java: We use a `StringBuilder` to reverse the string, and the `equals()` method to compare the strings.
- Python: A Pythonic approach is used with slicing to reverse the string.
- JavaScript: We use the `split()`, `reverse()`, and `join()` methods to reverse the string.

## A solution in Javascript

```javascript
function firstPalindrome(words) {
    for (const word of words) {
        const reversedWord = word.split('').reverse().join('');
        if (word === reversedWord) {
            return word;
        }
    }
    return "";
}
```
The algorithm used in each function iterates through the given array of strings, and for each string, it checks if it's a palindrome by comparing it to its reversed version. If a palindrome is found, it immediately returns that string. If no palindromes are found after iterating through the entire array, an empty string is returned. Each language's implementation follows similar logic, with some differences:

- C++: We use a range-based loop to iterate through the words, and the `std::reverse()` function to reverse the string.
- Java: We use a `StringBuilder` to reverse the string, and the `equals()` method to compare the strings.
- Python: A Pythonic approach is used with slicing to reverse the string.
- JavaScript: We use the `split()`, `reverse()`, and `join()` methods to reverse the string.