# Count Elements With Strictly Smaller and Greater Elements

- slug: count-elements-with-strictly-smaller-and-greater-elements
- difficulty: Easy

Given an integer array `nums`, return _the number of elements that have **both** a strictly smaller and a strictly greater element appear in_ `nums`.

**Example 1:**

**Input:** nums = \[11,7,2,15\]
**Output:** 2
**Explanation:** The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.
Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it.
In total there are 2 elements having both a strictly smaller and a strictly greater element appear in `nums`.

**Example 2:**

**Input:** nums = \[-3,3,3,90\]
**Output:** 2
**Explanation:** The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.
Since there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in `nums`.

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int minMoves(int[] seats, int[] students) {
    Arrays.sort(seats);
    Arrays.sort(students);

    int moves = 0;
    for (int i = 0; i < seats.length; i++) {
        moves += Math.abs(seats[i] - students[i]);
    }
    return moves;
}
```
1. Sort both the `seats` and `students` arrays in ascending order.
   This ensures that students will be paired up with the nearest available seat.
2. Initialize a variable `moves` to store the total number of moves.
3. Iterate through both arrays simultaneously using a single index.
4. In each iteration, add the absolute difference between the current seat and student position to the `moves` variable.
5. After the iteration, return the `moves` variable for the minimum number of moves required.

Note: This solution assumes that the input arrays have the same length and are non-empty.

## A solution in C++

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

int min_moves(std::vector<int>& seats, std::vector<int>& students) {
    std::sort(seats.begin(), seats.end());
    std::sort(students.begin(), students.end());

    int moves = 0;
    for (int i = 0; i < seats.size(); i++) {
        moves += std::abs(seats[i] - students[i]);
    }
    return moves;
}
```
1. Sort both the `seats` and `students` arrays in ascending order.
   This ensures that students will be paired up with the nearest available seat.
2. Initialize a variable `moves` to store the total number of moves.
3. Iterate through both arrays simultaneously using a single index.
4. In each iteration, add the absolute difference between the current seat and student position to the `moves` variable.
5. After the iteration, return the `moves` variable for the minimum number of moves required.

Note: This solution assumes that the input arrays have the same length and are non-empty.

## A solution in Python

```python
def min_moves(seats, students):
    seats.sort()
    students.sort()

    moves = 0
    for i in range(len(seats)):
        moves += abs(seats[i] - students[i])
    return moves
```
1. Sort both the `seats` and `students` arrays in ascending order.
   This ensures that students will be paired up with the nearest available seat.
2. Initialize a variable `moves` to store the total number of moves.
3. Iterate through both arrays simultaneously using a single index.
4. In each iteration, add the absolute difference between the current seat and student position to the `moves` variable.
5. After the iteration, return the `moves` variable for the minimum number of moves required.

Note: This solution assumes that the input arrays have the same length and are non-empty.

## A solution in Javascript

```javascript
function minMoves(seats, students) {
    seats.sort((a, b) => a - b);
    students.sort((a, b) => a - b);

    let moves = 0;
    for (let i = 0; i < seats.length; i++) {
        moves += Math.abs(seats[i] - students[i]);
    }
    return moves;
}
```
1. Sort both the `seats` and `students` arrays in ascending order.
   This ensures that students will be paired up with the nearest available seat.
2. Initialize a variable `moves` to store the total number of moves.
3. Iterate through both arrays simultaneously using a single index.
4. In each iteration, add the absolute difference between the current seat and student position to the `moves` variable.
5. After the iteration, return the `moves` variable for the minimum number of moves required.

Note: This solution assumes that the input arrays have the same length and are non-empty.


# Rearrange Array Elements by Sign

- slug: rearrange-array-elements-by-sign
- difficulty: Medium

You are given a **0-indexed** integer array `nums` of **even** length consisting of an **equal** number of positive and negative integers.

You should **rearrange** the elements of `nums` such that the modified array follows the given conditions:

1.  Every **consecutive pair** of integers have **opposite signs**.
2.  For all integers with the same sign, the **order** in which they were present in `nums` is **preserved**.
3.  The rearranged array begins with a positive integer.

Return _the modified array after rearranging the elements to satisfy the aforementioned conditions_.

**Example 1:**

**Input:** nums = \[3,1,-2,-5,2,-4\]
**Output:** \[3,-2,1,-5,2,-4\]
**Explanation:**
The positive integers in nums are \[3,1,2\]. The negative integers are \[-2,-5,-4\].
The only possible way to rearrange them such that they satisfy all conditions is \[3,-2,1,-5,2,-4\].
Other ways such as \[1,-2,2,-5,3,-4\], \[3,1,2,-2,-5,-4\], \[-2,3,-5,1,-4,2\] are incorrect because they do not satisfy one or more conditions.

**Example 2:**

**Input:** nums = \[-1,1\]
**Output:** \[1,-1\]
**Explanation:**
1 is the only positive integer and -1 the only negative integer in nums.
So nums is rearranged to \[1,-1\].

**Constraints:**

*   `2 <= nums.length <= 2 * 105`
*   `nums.length` is **even**
*   `1 <= |nums[i]| <= 105`
*   `nums` consists of **equal** number of positive and negative integers.

## A solution in Java

```java
public boolean solvePuzzle(String colors) {
    int countA = 0;
    for (char c : colors.toCharArray()) {
        if (c == 'A') countA++;
    }
    return countA % 2 == 1;
}
```
The optimal strategy for Alice and Bob is to remove pieces with the same color, since removing pieces with different colors will leave the opponent with an option to still remove pieces. With that strategy in mind, the game will only end when only pieces of different colors are left, and the player who is able to remove the last piece wins the game.

Therefore, to determine the winner, we only need to count the number of 'A' pieces in the given `colors` string, and check if it's an odd number. If it is, then it means there are more 'A' pieces than 'B' pieces, and Alice (who moves first) will win. Otherwise, Bob will win the game.

Thus, the function returns `true` if the count of 'A's is odd, and `false` otherwise.

## A solution in C++

```cpp
bool solve_puzzle(const std::string& colors) {
    return std::count(colors.begin(), colors.end(), 'A') % 2 == 1;
}
```
The optimal strategy for Alice and Bob is to remove pieces with the same color, since removing pieces with different colors will leave the opponent with an option to still remove pieces. With that strategy in mind, the game will only end when only pieces of different colors are left, and the player who is able to remove the last piece wins the game.

Therefore, to determine the winner, we only need to count the number of 'A' pieces in the given `colors` string, and check if it's an odd number. If it is, then it means there are more 'A' pieces than 'B' pieces, and Alice (who moves first) will win. Otherwise, Bob will win the game.

Thus, the function returns `true` if the count of 'A's is odd, and `false` otherwise.

## A solution in Python

```python
def solve_puzzle(colors: str) -> bool:
    return colors.count('A') % 2 == 1
```
The optimal strategy for Alice and Bob is to remove pieces with the same color, since removing pieces with different colors will leave the opponent with an option to still remove pieces. With that strategy in mind, the game will only end when only pieces of different colors are left, and the player who is able to remove the last piece wins the game.

Therefore, to determine the winner, we only need to count the number of 'A' pieces in the given `colors` string, and check if it's an odd number. If it is, then it means there are more 'A' pieces than 'B' pieces, and Alice (who moves first) will win. Otherwise, Bob will win the game.

Thus, the function returns `true` if the count of 'A's is odd, and `false` otherwise.

## A solution in Javascript

```javascript
function solvePuzzle(colors) {
    let countA = 0;
    for (let c of colors) {
        if (c === 'A') countA++;
    }
    return countA % 2 === 1;
}
```
The optimal strategy for Alice and Bob is to remove pieces with the same color, since removing pieces with different colors will leave the opponent with an option to still remove pieces. With that strategy in mind, the game will only end when only pieces of different colors are left, and the player who is able to remove the last piece wins the game.

Therefore, to determine the winner, we only need to count the number of 'A' pieces in the given `colors` string, and check if it's an odd number. If it is, then it means there are more 'A' pieces than 'B' pieces, and Alice (who moves first) will win. Otherwise, Bob will win the game.

Thus, the function returns `true` if the count of 'A's is odd, and `false` otherwise.


# Find All Lonely Numbers in the Array

- slug: find-all-lonely-numbers-in-the-array
- difficulty: Medium

You are given an integer array `nums`. A number `x` is **lonely** when it appears only **once**, and no **adjacent** numbers (i.e. `x + 1` and `x - 1)` appear in the array.

Return _**all** lonely numbers in_ `nums`. You may return the answer in **any order**.

**Example 1:**

**Input:** nums = \[10,6,5,8\]
**Output:** \[10,8\]
**Explanation:**
- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.
- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.
- 5 is not a lonely number since 6 appears in nums and vice versa.
Hence, the lonely numbers in nums are \[10, 8\].
Note that \[8, 10\] may also be returned.

**Example 2:**

**Input:** nums = \[1,3,5,3\]
**Output:** \[1,5\]
**Explanation:**
- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.
- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.
- 3 is not a lonely number since it appears twice.
Hence, the lonely numbers in nums are \[1, 5\].
Note that \[5, 1\] may also be returned.

**Constraints:**

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

## A solution in Java

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

public List<Integer> lonelyNumbers(int[] nums) {
    Map<Integer, Integer> count = new HashMap<>();
    List<Integer> result = new ArrayList<>();

    for (int num : nums) {
        count.put(num, count.getOrDefault(num, 0) + 1);
    }

    for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
        if (entry.getValue() == 1 && !count.containsKey(entry.getKey() - 1) && !count.containsKey(entry.getKey() + 1)) {
            result.add(entry.getKey());
        }
    }

    return result;
}
```
For this problem, we start by counting the occurrences of each number in the input list/array. This can be done using either a hash map (C++/Java/JavaScript) or a Counter (Python). This will allow us to easily check if a number appears only once and if its adjacent numbers are in the input.

Next, we iterate through the counted numbers, and for each number, we check if the count is 1 (appears only once) and if the adjacent numbers (x-1) and (x+1) are not present. If these conditions are met, the number is considered "lonely" and added to the result list/array.

Finally, we return the result list/array containing all the lonely numbers found during the iteration.

## A solution in C++

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

vector<int> lonelyNumbers(vector<int>& nums) {
    unordered_map<int, int> count;
    vector<int> result;

    for (int num : nums) {
        count[num]++;
    }

    for (const auto& entry : count) {
        if (entry.second == 1 && count.find(entry.first - 1) == count.end() && count.find(entry.first + 1) == count.end()) {
            result.push_back(entry.first);
        }
    }

    return result;
}
```
For this problem, we start by counting the occurrences of each number in the input list/array. This can be done using either a hash map (C++/Java/JavaScript) or a Counter (Python). This will allow us to easily check if a number appears only once and if its adjacent numbers are in the input.

Next, we iterate through the counted numbers, and for each number, we check if the count is 1 (appears only once) and if the adjacent numbers (x-1) and (x+1) are not present. If these conditions are met, the number is considered "lonely" and added to the result list/array.

Finally, we return the result list/array containing all the lonely numbers found during the iteration.

## A solution in Python

```javascript
function lonelyNumbers(nums) {
    const count = {};
    const result = [];

    for (const num of nums) {
        if (count[num] === undefined) {
            count[num] = 1;
        } else {
            count[num]++;
        }
    }

    for (const key in count) {
        const k = parseInt(key);
        if (count[k] === 1 && count[k - 1] === undefined && count[k + 1] === undefined) {
            result.push(k);
        }
    }

    return result;
}
```
For this problem, we start by counting the occurrences of each number in the input list/array. This can be done using either a hash map (C++/Java/JavaScript) or a Counter (Python). This will allow us to easily check if a number appears only once and if its adjacent numbers are in the input.

Next, we iterate through the counted numbers, and for each number, we check if the count is 1 (appears only once) and if the adjacent numbers (x-1) and (x+1) are not present. If these conditions are met, the number is considered "lonely" and added to the result list/array.

Finally, we return the result list/array containing all the lonely numbers found during the iteration.

## A solution in Javascript

```python
from collections import Counter

def lonelyNumbers(nums):
    count = Counter(nums)
    result = []

    for k, v in count.items():
        if v == 1 and k - 1 not in count and k + 1 not in count:
            result.append(k)

    return result
```
For this problem, we start by counting the occurrences of each number in the input list/array. This can be done using either a hash map (C++/Java/JavaScript) or a Counter (Python). This will allow us to easily check if a number appears only once and if its adjacent numbers are in the input.

Next, we iterate through the counted numbers, and for each number, we check if the count is 1 (appears only once) and if the adjacent numbers (x-1) and (x+1) are not present. If these conditions are met, the number is considered "lonely" and added to the result list/array.

Finally, we return the result list/array containing all the lonely numbers found during the iteration.


# Maximum Good People Based on Statements

- slug: maximum-good-people-based-on-statements
- difficulty: Hard

There are two types of persons:

*   The **good person**: The person who always tells the truth.
*   The **bad person**: The person who might tell the truth and might lie.

You are given a **0-indexed** 2D integer array `statements` of size `n x n` that represents the statements made by `n` people about each other. More specifically, `statements[i][j]` could be one of the following:

*   `0` which represents a statement made by person `i` that person `j` is a **bad** person.
*   `1` which represents a statement made by person `i` that person `j` is a **good** person.
*   `2` represents that **no statement** is made by person `i` about person `j`.

Additionally, no person ever makes a statement about themselves. Formally, we have that `statements[i][i] = 2` for all `0 <= i < n`.

Return _the **maximum** number of people who can be **good** based on the statements made by the_ `n` _people_.

**Example 1:**

**Input:** statements = \[\[2,1,2\],\[1,2,2\],\[2,0,2\]\]
**Output:** 2
**Explanation:** Each person makes a single statement.
- Person 0 states that person 1 is good.
- Person 1 states that person 0 is good.
- Person 2 states that person 1 is bad.
Let's take person 2 as the key.
- Assuming that person 2 is a good person:
    - Based on the statement made by person 2, person 1 is a bad person.
    - Now we know for sure that person 1 is bad and person 2 is good.
    - Based on the statement made by person 1, and since person 1 is bad, they could be:
        - telling the truth. There will be a contradiction in this case and this assumption is invalid.
        - lying. In this case, person 0 is also a bad person and lied in their statement.
    - **Following that person 2 is a good person, there will be only one good person in the group**.
- Assuming that person 2 is a bad person:
    - Based on the statement made by person 2, and since person 2 is bad, they could be:
        - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before.
            - **Following that person 2 is bad but told the truth, there will be no good persons in the group**.
        - lying. In this case person 1 is a good person.
            - Since person 1 is a good person, person 0 is also a good person.
            - **Following that person 2 is bad and lied, there will be two good persons in the group**.
We can see that at most 2 persons are good in the best case, so we return 2.
Note that there is more than one way to arrive at this conclusion.

**Example 2:**

**Input:** statements = \[\[2,0\],\[0,2\]\]
**Output:** 1
**Explanation:** Each person makes a single statement.
- Person 0 states that person 1 is bad.
- Person 1 states that person 0 is bad.
Let's take person 0 as the key.
- Assuming that person 0 is a good person:
    - Based on the statement made by person 0, person 1 is a bad person and was lying.
    - **Following that person 0 is a good person, there will be only one good person in the group**.
- Assuming that person 0 is a bad person:
    - Based on the statement made by person 0, and since person 0 is bad, they could be:
        - telling the truth. Following this scenario, person 0 and 1 are both bad.
            - **Following that person 0 is bad but told the truth, there will be no good persons in the group**.
        - lying. In this case person 1 is a good person.
            - **Following that person 0 is bad and lied, there will be only one good person in the group**.
We can see that at most, one person is good in the best case, so we return 1.
Note that there is more than one way to arrive at this conclusion.

**Constraints:**

*   `n == statements.length == statements[i].length`
*   `2 <= n <= 15`
*   `statements[i][j]` is either `0`, `1`, or `2`.
*   `statements[i][i] == 2`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int networkBecomesIdle(int[][] edges, int[] patience) {
        int n = patience.length;
        List<List<Integer>> graph = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            graph.add(new ArrayList<>());
        }

        for (int[] edge : edges) {
            graph.get(edge[0]).add(edge[1]);
            graph.get(edge[1]).add(edge[0]);
        }

        int[] dist = new int[n];
        Arrays.fill(dist, -1);
        dist[0] = 0;
        Queue<Integer> q = new LinkedList<>();
        q.add(0);

        while (!q.isEmpty()) {
            int node = q.poll();

            for (int neighbor : graph.get(node)) {
                if (dist[neighbor] == -1) {
                    dist[neighbor] = dist[node] + 1;
                    q.add(neighbor);
                }
            }
        }

        int max_time = 0;
        for (int i = 1; i < n; i++) {
            int time = ((2 * dist[i] - 1) / patience[i]) * patience[i] + 2 * dist[i];
            max_time = Math.max(max_time, time);
        }

        return max_time + 1;
    }
}
```
1. Build a graph with the given edges.
2. Use BFS to calculate the shortest distance from server 0 to each other server.
3. For each data server, calculate the time it takes for the messages to be sent and replied (use patience to compute the message waiting time).
4. Find the maximum time among all data servers.
5. Return the maximum time + 1 as the earliest second the network becomes idle.

## A solution in C++

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

using namespace std;

int networkBecomesIdle(vector<vector<int>>& edges, vector<int>& patience) {
    int n = patience.size();
    vector<vector<int>> graph(n);

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

    vector<int> dist(n, -1);
    dist[0] = 0;
    queue<int> q;
    q.push(0);

    while (!q.empty()) {
        int node = q.front();
        q.pop();

        for (int neighbor : graph[node]) {
            if (dist[neighbor] == -1) {
                dist[neighbor] = dist[node] + 1;
                q.push(neighbor);
            }
        }
    }

    int max_time = 0;
    for (int i = 1; i < n; i++) {
        int time = ((2 * dist[i] - 1) / patience[i]) * patience[i] + 2 * dist[i];
        max_time = max(max_time, time);
    }

    return max_time + 1;
}
```
1. Build a graph with the given edges.
2. Use BFS to calculate the shortest distance from server 0 to each other server.
3. For each data server, calculate the time it takes for the messages to be sent and replied (use patience to compute the message waiting time).
4. Find the maximum time among all data servers.
5. Return the maximum time + 1 as the earliest second the network becomes idle.

## A solution in Python

```python
from collections import defaultdict, deque

def network_becomes_idle(edges, patience):
    n = len(patience)
    graph = defaultdict(list)

    for edge in edges:
        graph[edge[0]].append(edge[1])
        graph[edge[1]].append(edge[0])

    dist = [-1] * n
    dist[0] = 0
    q = deque([0])

    while q:
        node = q.popleft()

        for neighbor in graph[node]:
            if dist[neighbor] == -1:
                dist[neighbor] = dist[node] + 1
                q.append(neighbor)

    max_time = 0
    for i in range(1, n):
        time = ((2 * dist[i] - 1) // patience[i]) * patience[i] + 2 * dist[i]
        max_time = max(max_time, time)

    return max_time + 1
```
1. Build a graph with the given edges.
2. Use BFS to calculate the shortest distance from server 0 to each other server.
3. For each data server, calculate the time it takes for the messages to be sent and replied (use patience to compute the message waiting time).
4. Find the maximum time among all data servers.
5. Return the maximum time + 1 as the earliest second the network becomes idle.

## A solution in Javascript

```javascript
function networkBecomesIdle(edges, patience) {
    const n = patience.length;
    const graph = new Array(n).fill(null).map(() => []);

    for (const edge of edges) {
        graph[edge[0]].push(edge[1]);
        graph[edge[1]].push(edge[0]);
    }

    const dist = new Array(n).fill(-1);
    dist[0] = 0;
    const q = [0];

    while (q.length > 0) {
        const node = q.shift();

        for (const neighbor of graph[node]) {
            if (dist[neighbor] === -1) {
                dist[neighbor] = dist[node] + 1;
                q.push(neighbor);
            }
        }
    }

    let max_time = 0;
    for (let i = 1; i < n; i++) {
        const time = Math.floor((2 * dist[i] - 1) / patience[i]) * patience[i] + 2 * dist[i];
        max_time = Math.max(max_time, time);
    }

    return max_time + 1;
}
```
1. Build a graph with the given edges.
2. Use BFS to calculate the shortest distance from server 0 to each other server.
3. For each data server, calculate the time it takes for the messages to be sent and replied (use patience to compute the message waiting time).
4. Find the maximum time among all data servers.
5. Return the maximum time + 1 as the earliest second the network becomes idle.


# Minimum Number of Lines to Cover Points

- slug: minimum-number-of-lines-to-cover-points
- difficulty: Medium

You are given an array `points` where `points[i] = [xi, yi]` represents a point on an **X-Y** plane.

**Straight lines** are going to be added to the **X-Y** plane, such that every point is covered by at **least** one line.

Return _the **minimum** number of **straight lines** needed to cover all the points_.

**Example 1:**

**Input:** points = \[\[0,1\],\[2,3\],\[4,5\],\[4,3\]\]
**Output:** 2
**Explanation:** The minimum number of straight lines needed is two. One possible solution is to add:
- One line connecting the point at (0, 1) to the point at (4, 5).
- Another line connecting the point at (2, 3) to the point at (4, 3).

**Example 2:**

**Input:** points = \[\[0,2\],\[-2,-2\],\[1,4\]\]
**Output:** 1
**Explanation:** The minimum number of straight lines needed is one. The only solution is to add:
- One line connecting the point at (-2, -2) to the point at (1, 4).

**Constraints:**

*   `1 <= points.length <= 10`
*   `points[i].length == 2`
*   `-100 <= xi, yi <= 100`
*   All the `points` are **unique**.

## A solution in Java

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

public int minStraightLines(int[][] points) {
    int len = points.length;
    Set<Integer> set = new HashSet<>();
    for (int i = 0; i < len; i++) {
        for (int j = i + 1; j < len; j++) {
            int deltaX = points[j][0] - points[i][0];
            int deltaY = points[j][1] - points[i][1];
            int gcd = gcd(deltaX, deltaY);
            int hash = deltaY / gcd * 1000 + deltaX / gcd;
            set.add(hash);
        }
    }
    return set.size();
}

private int gcd(int a, int b) {
    return (b == 0) ? a : gcd(b, a % b);
}
```
The algorithm checks all possible pairs of points in the plane, and calculates the line connecting them. To avoid duplicates, we use the greatest common divisor (gcd) to normalize the lines by calculating the slope `(dx, dy) // gcd`. Then, we store these lines in a hash set. The gcd is calculated using a helper function (JavaScript) or directly using the math library (Python) or built-in functions (C++).

The algorithm does not require any specific language implementation because it is based only on the basic concept of comparing slopes and keeping a count of unique slopes. For each pair of points, the algorithm calculates the slope, normalizes it using the gcd, and stores it in the hash set. The final answer is found by taking the size of the hash set.

## A solution in C++

```cpp
#include <unordered_set>
#include <utility>

int minStraightLines(vector<vector<int>>& points) {
    int len = points.size();
    unordered_set<int> uh;
    for (int i = 0; i < len; i++) {
        for (int j = i + 1; j < len; j++) {
            if (i != j) {
                int delta_x = points[j][0] - points[i][0];
                int delta_y = points[j][1] - points[i][1];
                int gcd = __gcd(delta_x, delta_y);
                delta_x /= gcd;
                delta_y /= gcd;
                uh.insert(delta_y * 1000 + delta_x);
            }
        }
    }
    return uh.size();
}
```
The algorithm checks all possible pairs of points in the plane, and calculates the line connecting them. To avoid duplicates, we use the greatest common divisor (gcd) to normalize the lines by calculating the slope `(dx, dy) // gcd`. Then, we store these lines in a hash set. The gcd is calculated using a helper function (JavaScript) or directly using the math library (Python) or built-in functions (C++).

The algorithm does not require any specific language implementation because it is based only on the basic concept of comparing slopes and keeping a count of unique slopes. For each pair of points, the algorithm calculates the slope, normalizes it using the gcd, and stores it in the hash set. The final answer is found by taking the size of the hash set.

## A solution in Python

```python
from math import gcd
from itertools import combinations

def minStraightLines(points):
    lines = set()
    for p1, p2 in combinations(points, 2):
        dy, dx = p2[1] - p1[1], p2[0] - p1[0]
        g = gcd(dx, dy)
        lines.add((dy // g, dx // g))
    return len(lines)
```
The algorithm checks all possible pairs of points in the plane, and calculates the line connecting them. To avoid duplicates, we use the greatest common divisor (gcd) to normalize the lines by calculating the slope `(dx, dy) // gcd`. Then, we store these lines in a hash set. The gcd is calculated using a helper function (JavaScript) or directly using the math library (Python) or built-in functions (C++).

The algorithm does not require any specific language implementation because it is based only on the basic concept of comparing slopes and keeping a count of unique slopes. For each pair of points, the algorithm calculates the slope, normalizes it using the gcd, and stores it in the hash set. The final answer is found by taking the size of the hash set.

## A solution in Javascript

```javascript
function minStraightLines(points) {
    const set = new Set();
    const len = points.length;

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

    for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
            const deltaX = points[j][0] - points[i][0];
            const deltaY = points[j][1] - points[i][1];
            const g = gcd(deltaY, deltaX);
            const hash = deltaY / g * 1000 + deltaX / g;
            set.add(hash);
        }
    }
    return set.size;
}
```
The algorithm checks all possible pairs of points in the plane, and calculates the line connecting them. To avoid duplicates, we use the greatest common divisor (gcd) to normalize the lines by calculating the slope `(dx, dy) // gcd`. Then, we store these lines in a hash set. The gcd is calculated using a helper function (JavaScript) or directly using the math library (Python) or built-in functions (C++).

The algorithm does not require any specific language implementation because it is based only on the basic concept of comparing slopes and keeping a count of unique slopes. For each pair of points, the algorithm calculates the slope, normalizes it using the gcd, and stores it in the hash set. The final answer is found by taking the size of the hash set.


# Keep Multiplying Found Values by Two

- slug: keep-multiplying-found-values-by-two
- difficulty: Easy

You are given an array of integers `nums`. You are also given an integer `original` which is the first number that needs to be searched for in `nums`.

You then do the following steps:

1.  If `original` is found in `nums`, **multiply** it by two (i.e., set `original = 2 * original`).
2.  Otherwise, **stop** the process.
3.  **Repeat** this process with the new number as long as you keep finding the number.

Return _the **final** value of_ `original`.

**Example 1:**

**Input:** nums = \[5,3,6,1,12\], original = 3
**Output:** 24
**Explanation:**
- 3 is found in nums. 3 is multiplied by 2 to obtain 6.
- 6 is found in nums. 6 is multiplied by 2 to obtain 12.
- 12 is found in nums. 12 is multiplied by 2 to obtain 24.
- 24 is not found in nums. Thus, 24 is returned.

**Example 2:**

**Input:** nums = \[2,7,9\], original = 4
**Output:** 4
**Explanation:**
- 4 is not found in nums. Thus, 4 is returned.

**Constraints:**

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

## A solution in Java

```java
public int minMovesToConvert(String s) {
    int count = 0;
    for (int i = 0; i < s.length() - 2; i++) {
        if (s.charAt(i) == 'X' && s.charAt(i + 1) == 'X' && s.charAt(i + 2) == 'X') {
            count++;
            i += 2; // move by 3
        }
    }
    return count;
}
```
The algorithm iterates over the given string s. For each character, if it finds a sequence of 3 consecutive 'X', it increases the 'count' and moves the iterator 3 positions forward. If it doesn't find the sequence, it moves the iterator 1 position forward. The algorithm ultimately returns the 'count', which is the minimum number of moves required to convert all characters in the string to 'O'.

## A solution in C++

```cpp
int min_moves_to_convert(const std::string& s) {
    int count = 0;
    for (size_t i = 0; i < s.length() - 2; i++) {
        if (s[i] == 'X' && s[i + 1] == 'X' && s[i + 2] == 'X') {
            count++;
            i += 2; // move by 3
        }
    }
    return count;
}
```
The algorithm iterates over the given string s. For each character, if it finds a sequence of 3 consecutive 'X', it increases the 'count' and moves the iterator 3 positions forward. If it doesn't find the sequence, it moves the iterator 1 position forward. The algorithm ultimately returns the 'count', which is the minimum number of moves required to convert all characters in the string to 'O'.

## A solution in Python

```python
def min_moves_to_convert(s):
    count = 0
    i = 0
    while i < len(s) - 2:
        if s[i] == "X" and s[i + 1] == "X" and s[i + 2] == "X":
            count += 1
            i += 3
        else:
            i += 1
    return count
```
The algorithm iterates over the given string s. For each character, if it finds a sequence of 3 consecutive 'X', it increases the 'count' and moves the iterator 3 positions forward. If it doesn't find the sequence, it moves the iterator 1 position forward. The algorithm ultimately returns the 'count', which is the minimum number of moves required to convert all characters in the string to 'O'.

## A solution in Javascript

```javascript
function minimumMovesToConvert(s) {
    let count = 0;
    for (let i = 0; i < s.length - 2; i++) {
        if (s[i] === 'X' && s[i + 1] === 'X' && s[i + 2] === 'X') {
            count++;
            i += 2; // move by 3
        }
    }
    return count;
}
```
The algorithm iterates over the given string s. For each character, if it finds a sequence of 3 consecutive 'X', it increases the 'count' and moves the iterator 3 positions forward. If it doesn't find the sequence, it moves the iterator 1 position forward. The algorithm ultimately returns the 'count', which is the minimum number of moves required to convert all characters in the string to 'O'.


# All Divisions With the Highest Score of a Binary Array

- slug: all-divisions-with-the-highest-score-of-a-binary-array
- difficulty: Medium

You are given a **0-indexed** binary array `nums` of length `n`. `nums` can be divided at index `i` (where `0 <= i <= n)` into two arrays (possibly empty) `numsleft` and `numsright`:

*   `numsleft` has all the elements of `nums` between index `0` and `i - 1` **(inclusive)**, while `numsright` has all the elements of nums between index `i` and `n - 1` **(inclusive)**.
*   If `i == 0`, `numsleft` is **empty**, while `numsright` has all the elements of `nums`.
*   If `i == n`, `numsleft` has all the elements of nums, while `numsright` is **empty**.

The **division score** of an index `i` is the **sum** of the number of `0`'s in `numsleft` and the number of `1`'s in `numsright`.

Return _**all distinct indices** that have the **highest** possible **division score**_. You may return the answer in **any order**.

**Example 1:**

**Input:** nums = \[0,0,1,0\]
**Output:** \[2,4\]
**Explanation:** Division at index
- 0: numsleft is \[\]. numsright is \[0,0,**1**,0\]. The score is 0 + 1 = 1.
- 1: numsleft is \[**0**\]. numsright is \[0,**1**,0\]. The score is 1 + 1 = 2.
- 2: numsleft is \[**0**,**0**\]. numsright is \[**1**,0\]. The score is 2 + 1 = 3.
- 3: numsleft is \[**0**,**0**,1\]. numsright is \[0\]. The score is 2 + 0 = 2.
- 4: numsleft is \[**0**,**0**,1,**0**\]. numsright is \[\]. The score is 3 + 0 = 3.
Indices 2 and 4 both have the highest possible division score 3.
Note the answer \[4,2\] would also be accepted.

**Example 2:**

**Input:** nums = \[0,0,0\]
**Output:** \[3\]
**Explanation:** Division at index
- 0: numsleft is \[\]. numsright is \[0,0,0\]. The score is 0 + 0 = 0.
- 1: numsleft is \[**0**\]. numsright is \[0,0\]. The score is 1 + 0 = 1.
- 2: numsleft is \[**0**,**0**\]. numsright is \[0\]. The score is 2 + 0 = 2.
- 3: numsleft is \[**0**,**0**,**0**\]. numsright is \[\]. The score is 3 + 0 = 3.
Only index 3 has the highest possible division score 3.

**Example 3:**

**Input:** nums = \[1,1\]
**Output:** \[0\]
**Explanation:** Division at index
- 0: numsleft is \[\]. numsright is \[**1**,**1**\]. The score is 0 + 2 = 2.
- 1: numsleft is \[1\]. numsright is \[**1**\]. The score is 0 + 1 = 1.
- 2: numsleft is \[1,1\]. numsright is \[\]. The score is 0 + 0 = 0.
Only index 0 has the highest possible division score 2.

**Constraints:**

*   `n == nums.length`
*   `1 <= n <= 105`
*   `nums[i]` is either `0` or `1`.

## A solution in Java

```java
import java.util.Arrays;

public int[] missingRolls(int[] rolls, int mean, int n) {
    int m = rolls.length;
    int sum = mean * (n + m);
    for (int roll: rolls) {
        sum -= roll;
    }

    if (sum < n || sum > 6 * n) {
        return new int[] {};
    }

    int[] ans = new int[n];
    Arrays.fill(ans, 1);
    sum -= n;
    for (int i = 0; i < n; i++) {
        int add = Math.min(5, sum);
        ans[i] += add;
        sum -= add;
    }

    return ans;
}
```
1. Calculate the total sum of all n + m rolls by multiplying mean with (n + m).
2. Subtract the sum of m rolls from the total sum.
3. Check if the remaining sum is valid for the given n (should be between n and 6 * n).
4. If valid, create an array of size n with each value initialized to 1.
5. Iterate through the array and add values ranging from 1 to 6 while updating the remaining sum.
6. The final array is the answer.

## A solution in C++

```cpp
#include <vector>

std::vector<int> missingRolls(std::vector<int>& rolls, int mean, int n) {
    int m = rolls.size();
    int sum = mean * (n + m);
    for (int roll: rolls) {
        sum -= roll;
    }

    if (sum < n || sum > 6 * n) {
        return {};
    }

    std::vector<int> ans(n, 1);
    sum -= n;
    for (int i = 0; i < n; i++) {
        int add = std::min(5, sum);
        ans[i] += add;
        sum -= add;
    }

    return ans;
}
```
1. Calculate the total sum of all n + m rolls by multiplying mean with (n + m).
2. Subtract the sum of m rolls from the total sum.
3. Check if the remaining sum is valid for the given n (should be between n and 6 * n).
4. If valid, create an array of size n with each value initialized to 1.
5. Iterate through the array and add values ranging from 1 to 6 while updating the remaining sum.
6. The final array is the answer.

## A solution in Python

```python
from typing import List

def missing_rolls(rolls: List[int], mean: int, n: int) -> List[int]:
    m = len(rolls)
    total_sum = mean * (n + m)
    sum_m = sum(rolls)

    if total_sum - sum_m < n or total_sum - sum_m > 6 * n:
        return []

    ans = [1] * n
    total_sum -= sum_m + n
    for i in range(n):
        add = min(5, total_sum)
        ans[i] += add
        total_sum -= add

    return ans
```
1. Calculate the total sum of all n + m rolls by multiplying mean with (n + m).
2. Subtract the sum of m rolls from the total sum.
3. Check if the remaining sum is valid for the given n (should be between n and 6 * n).
4. If valid, create an array of size n with each value initialized to 1.
5. Iterate through the array and add values ranging from 1 to 6 while updating the remaining sum.
6. The final array is the answer.

## A solution in Javascript

```javascript
function missingRolls(rolls, mean, n) {
    const m = rolls.length;
    let sum = mean * (n + m);
    for (const roll of rolls) {
        sum -= roll;
    }

    if (sum < n || sum > 6 * n) {
        return [];
    }

    const ans = Array(n).fill(1);
    sum -= n;
    for (let i = 0; i < n; i++) {
        const add = Math.min(5, sum);
        ans[i] += add;
        sum -= add;
    }

    return ans;
}
```
1. Calculate the total sum of all n + m rolls by multiplying mean with (n + m).
2. Subtract the sum of m rolls from the total sum.
3. Check if the remaining sum is valid for the given n (should be between n and 6 * n).
4. If valid, create an array of size n with each value initialized to 1.
5. Iterate through the array and add values ranging from 1 to 6 while updating the remaining sum.
6. The final array is the answer.


# Find Substring With Given Hash Value

- slug: find-substring-with-given-hash-value
- difficulty: Hard

The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function:

*   `hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m`.

Where `val(s[i])` represents the index of `s[i]` in the alphabet from `val('a') = 1` to `val('z') = 26`.

You are given a string `s` and the integers `power`, `modulo`, `k`, and `hashValue.` Return `sub`, _the **first** **substring** of_ `s` _of length_ `k` _such that_ `hash(sub, power, modulo) == hashValue`.

The test cases will be generated such that an answer always **exists**.

A **substring** is a contiguous non-empty sequence of characters within a string.

**Example 1:**

**Input:** s =  "leetcode ", power = 7, modulo = 20, k = 2, hashValue = 0
**Output:**  "ee "
**Explanation:** The hash of  "ee " can be computed to be hash( "ee ", 7, 20) = (5 \* 1 + 5 \* 7) mod 20 = 40 mod 20 = 0.
 "ee " is the first substring of length 2 with hashValue 0. Hence, we return  "ee ".

**Example 2:**

**Input:** s =  "fbxzaad ", power = 31, modulo = 100, k = 3, hashValue = 32
**Output:**  "fbx "
**Explanation:** The hash of  "fbx " can be computed to be hash( "fbx ", 31, 100) = (6 \* 1 + 2 \* 31 + 24 \* 312) mod 100 = 23132 mod 100 = 32.
The hash of  "bxz " can be computed to be hash( "bxz ", 31, 100) = (2 \* 1 + 24 \* 31 + 26 \* 312) mod 100 = 25732 mod 100 = 32.
 "fbx " is the first substring of length 3 with hashValue 32. Hence, we return  "fbx ".
Note that  "bxz " also has a hash of 32 but it appears later than  "fbx ".

**Constraints:**

*   `1 <= k <= s.length <= 2 * 104`
*   `1 <= power, modulo <= 109`
*   `0 <= hashValue < modulo`
*   `s` consists of lowercase English letters only.
*   The test cases are generated such that an answer always **exists**.

## A solution in Java

```java
public boolean aliceWins(int[] stones) {
    int sum = 0, count[] = new int[3];
    for (int stone : stones) {
        sum += stone;
        count[stone % 3]++;
    }
    if (sum % 3 != 0) {
        return count[sum % 3] % 2 == 1;
    }
    return count[1] % 2 == 0 || count[2] % 2 == 0 || count[1] == 0 || count[2] == 0;
}
```
1. Calculate the sum of values of all stones and counts of stones with values 1, 2 modulo 3.
2. If the sum is not divisible by 3, Alice will try to maintain it. In this case, Alice wins if the count of stones with the sum modulo 3 is odd.
3. If the sum is divisible by 3, Alice will try to prevent it from being divisible by 3. In this case, Alice wins if there are an even number of 1s and 2s modulo 3.

## A solution in C++

```cpp
bool aliceWins(std::vector<int> &stones) {
    int sum = 0, count[3] = {0};
    for (int stone : stones) {
        sum += stone;
        count[stone % 3]++;
    }
    if (sum % 3) {
        return count[sum % 3] % 2 == 1;
    }
    return count[1] % 2 == 0 || count[2] % 2 == 0 || count[1] == 0 || count[2] == 0;
}
```
1. Calculate the sum of values of all stones and counts of stones with values 1, 2 modulo 3.
2. If the sum is not divisible by 3, Alice will try to maintain it. In this case, Alice wins if the count of stones with the sum modulo 3 is odd.
3. If the sum is divisible by 3, Alice will try to prevent it from being divisible by 3. In this case, Alice wins if there are an even number of 1s and 2s modulo 3.

## A solution in Python

```python
def alice_wins(stones):
    sum_, count = 0, [0] * 3
    for stone in stones:
        sum_ += stone
        count[stone % 3] += 1
    if sum_ % 3:
        return count[sum_ % 3] % 2 == 1
    return count[1] % 2 == 0 or count[2] % 2 == 0 or count[1] == 0 or count[2] == 0
```
1. Calculate the sum of values of all stones and counts of stones with values 1, 2 modulo 3.
2. If the sum is not divisible by 3, Alice will try to maintain it. In this case, Alice wins if the count of stones with the sum modulo 3 is odd.
3. If the sum is divisible by 3, Alice will try to prevent it from being divisible by 3. In this case, Alice wins if there are an even number of 1s and 2s modulo 3.

## A solution in Javascript

```javascript
function aliceWins(stones) {
    let sum = 0, count = [0, 0, 0];
    for (let stone of stones) {
        sum += stone;
        count[stone % 3]++;
    }
    if (sum % 3 !== 0) {
        return count[sum % 3] % 2 === 1;
    }
    return count[1] % 2 === 0 || count[2] % 2 === 0 || count[1] === 0 || count[2] === 0;
}
```
1. Calculate the sum of values of all stones and counts of stones with values 1, 2 modulo 3.
2. If the sum is not divisible by 3, Alice will try to maintain it. In this case, Alice wins if the count of stones with the sum modulo 3 is odd.
3. If the sum is divisible by 3, Alice will try to prevent it from being divisible by 3. In this case, Alice wins if there are an even number of 1s and 2s modulo 3.


# Groups of Strings

- slug: groups-of-strings
- difficulty: Hard

You are given a **0-indexed** array of strings `words`. Each string consists of **lowercase English letters** only. No letter occurs more than once in any string of `words`.

Two strings `s1` and `s2` are said to be **connected** if the set of letters of `s2` can be obtained from the set of letters of `s1` by any **one** of the following operations:

*   Adding exactly one letter to the set of the letters of `s1`.
*   Deleting exactly one letter from the set of the letters of `s1`.
*   Replacing exactly one letter from the set of the letters of `s1` with any letter, **including** itself.

The array `words` can be divided into one or more non-intersecting **groups**. A string belongs to a group if any **one** of the following is true:

*   It is connected to **at least one** other string of the group.
*   It is the **only** string present in the group.

Note that the strings in `words` should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique.

Return _an array_ `ans` _of size_ `2` _where:_

*   `ans[0]` _is the **maximum number** of groups_ `words` _can be divided into, and_
*   `ans[1]` _is the **size of the largest** group_.

**Example 1:**

**Input:** words = \[ "a ", "b ", "ab ", "cde "\]
**Output:** \[2,3\]
**Explanation:**
- words\[0\] can be used to obtain words\[1\] (by replacing 'a' with 'b'), and words\[2\] (by adding 'b'). So words\[0\] is connected to words\[1\] and words\[2\].
- words\[1\] can be used to obtain words\[0\] (by replacing 'b' with 'a'), and words\[2\] (by adding 'a'). So words\[1\] is connected to words\[0\] and words\[2\].
- words\[2\] can be used to obtain words\[0\] (by deleting 'b'), and words\[1\] (by deleting 'a'). So words\[2\] is connected to words\[0\] and words\[1\].
- words\[3\] is not connected to any string in words.
Thus, words can be divided into 2 groups \[ "a ", "b ", "ab "\] and \[ "cde "\]. The size of the largest group is 3.

**Example 2:**

**Input:** words = \[ "a ", "ab ", "abc "\]
**Output:** \[1,3\]
**Explanation:**
- words\[0\] is connected to words\[1\].
- words\[1\] is connected to words\[0\] and words\[2\].
- words\[2\] is connected to words\[1\].
Since all strings are connected to each other, they should be grouped together.
Thus, the size of the largest group is 3.

**Constraints:**

*   `1 <= words.length <= 2 * 104`
*   `1 <= words[i].length <= 26`
*   `words[i]` consists of lowercase English letters only.
*   No letter occurs more than once in `words[i]`.

## A solution in Java

```java
import java.util.PriorityQueue;

public String smallestSubsequence(String s, int k, char letter, int repetition) {
    StringBuilder result = new StringBuilder();
    int letterCount = 0, n = s.length();
    for (char c : s.toCharArray()) if (c == letter) letterCount++;

    PriorityQueue<Character> pq = new PriorityQueue<>();
    for (int i = 0; i < n; i++) {
        if (s.charAt(i) <= letter || letterCount > repetition) {
            while (!pq.isEmpty() && pq.peek() > s.charAt(i)) {
                if (pq.poll() == letter) letterCount--;
            }
            pq.add(s.charAt(i));
            if (pq.size() > k) pq.poll();
        }
        if (k - pq.size() == repetition) letterCount--;
        repetition = Math.max(0, repetition);
    }

    while (!pq.isEmpty()) {
        result.append(pq.poll());
    }
    return result.toString();
}
```
1. Initialize a priority queue (min-heap in Python and JS) `pq`, a result string (a StringBuilder in Java), and count the number of occurrences of the letter in the string s.
2. Iterate through the string s with index i:
   a. If the current character `s[i]` is smaller than or equal to the letter, or the letter count is greater than the repetition, enter the loop.
   b. While `pq` is not empty and the top element is greater than the current character `s[i]`, pop the top element. (In JS, pop the first element of sorted pq). Decrease the letter count if a popped element equals the given letter.
   c. Push `s[i]` to `pq` and sort the pq in JavaScript.
   d. If the size of `pq` is larger than k, pop the top element.
   e. If the difference between k and pq's size equals the repetition, decrement letter count (letter count should not be less than desired repetitions).
   f. Update repetition by taking the maximum of 0 and the current repetition.
3. Append elements from the priority queue to the result string (in reverse order in C++).
4. Return the result string.

This algorithm ensures that lex order is maintained using a priority queue that stores elements in ascending order, and the desired repetition is achieved by keeping track of the letter count while traversing the string s.

## A solution in C++

```cpp
#include <string>
#include <queue>

std::string smallestSubsequence(std::string s, int k, char letter, int repetition) {
    std::string result;
    int letter_count = 0, n = s.length();
    for (char c : s) if (c == letter) letter_count++;

    std::priority_queue<char, std::vector<char>, std::greater<char>> pq;
    for (int i = 0; i < n; i++) {
        if (s[i] <= letter || letter_count > repetition) {
            while (!pq.empty() && pq.top() > s[i]) {
                if (pq.top() == letter) letter_count--;
                pq.pop();
            }
            pq.push(s[i]);
            if (pq.size() > k) pq.pop();
        }
        if (k - pq.size() == repetition) letter_count--;
        repetition = std::max(0, repetition);
    }

    while (!pq.empty()) {
        result.push_back(pq.top());
        pq.pop();
    }
    return result;
}
```
1. Initialize a priority queue (min-heap in Python and JS) `pq`, a result string (a StringBuilder in Java), and count the number of occurrences of the letter in the string s.
2. Iterate through the string s with index i:
   a. If the current character `s[i]` is smaller than or equal to the letter, or the letter count is greater than the repetition, enter the loop.
   b. While `pq` is not empty and the top element is greater than the current character `s[i]`, pop the top element. (In JS, pop the first element of sorted pq). Decrease the letter count if a popped element equals the given letter.
   c. Push `s[i]` to `pq` and sort the pq in JavaScript.
   d. If the size of `pq` is larger than k, pop the top element.
   e. If the difference between k and pq's size equals the repetition, decrement letter count (letter count should not be less than desired repetitions).
   f. Update repetition by taking the maximum of 0 and the current repetition.
3. Append elements from the priority queue to the result string (in reverse order in C++).
4. Return the result string.

This algorithm ensures that lex order is maintained using a priority queue that stores elements in ascending order, and the desired repetition is achieved by keeping track of the letter count while traversing the string s.

## A solution in Python

```python
from heapq import heappop, heappush

def smallest_subsequence(s, k, letter, repetition):
    result = []
    letter_count = s.count(letter)

    pq = []
    for c in s:
        if c <= letter or letter_count > repetition:
            while pq and pq[0] > c:
                if heappop(pq) == letter:
                    letter_count -= 1
            heappush(pq, c)
            if len(pq) > k:
                heappop(pq)
        if k - len(pq) == repetition:
            letter_count -= 1
        repetition = max(0, repetition)

    return "".join(pq)
```
1. Initialize a priority queue (min-heap in Python and JS) `pq`, a result string (a StringBuilder in Java), and count the number of occurrences of the letter in the string s.
2. Iterate through the string s with index i:
   a. If the current character `s[i]` is smaller than or equal to the letter, or the letter count is greater than the repetition, enter the loop.
   b. While `pq` is not empty and the top element is greater than the current character `s[i]`, pop the top element. (In JS, pop the first element of sorted pq). Decrease the letter count if a popped element equals the given letter.
   c. Push `s[i]` to `pq` and sort the pq in JavaScript.
   d. If the size of `pq` is larger than k, pop the top element.
   e. If the difference between k and pq's size equals the repetition, decrement letter count (letter count should not be less than desired repetitions).
   f. Update repetition by taking the maximum of 0 and the current repetition.
3. Append elements from the priority queue to the result string (in reverse order in C++).
4. Return the result string.

This algorithm ensures that lex order is maintained using a priority queue that stores elements in ascending order, and the desired repetition is achieved by keeping track of the letter count while traversing the string s.

## A solution in Javascript

```javascript
function smallestSubsequence(s, k, letter, repetition) {
    let result = "";
    let letterCount = 0, n = s.length;
    for (let c of s) if (c === letter) letterCount++;

    let pq = [];
    for (let i = 0; i < n; i++) {
        if (s[i] <= letter || letterCount > repetition) {
            while (pq.length > 0 && pq[0] > s[i]) {
                if (pq.shift() === letter) letterCount--;
            }
            pq.push(s[i]);
            pq.sort();
            if (pq.length > k) pq.shift();
        }
        if (k - pq.length === repetition) letterCount--;
        repetition = Math.max(0, repetition);
    }

    return pq.join("");
}
```
1. Initialize a priority queue (min-heap in Python and JS) `pq`, a result string (a StringBuilder in Java), and count the number of occurrences of the letter in the string s.
2. Iterate through the string s with index i:
   a. If the current character `s[i]` is smaller than or equal to the letter, or the letter count is greater than the repetition, enter the loop.
   b. While `pq` is not empty and the top element is greater than the current character `s[i]`, pop the top element. (In JS, pop the first element of sorted pq). Decrease the letter count if a popped element equals the given letter.
   c. Push `s[i]` to `pq` and sort the pq in JavaScript.
   d. If the size of `pq` is larger than k, pop the top element.
   e. If the difference between k and pq's size equals the repetition, decrement letter count (letter count should not be less than desired repetitions).
   f. Update repetition by taking the maximum of 0 and the current repetition.
3. Append elements from the priority queue to the result string (in reverse order in C++).
4. Return the result string.

This algorithm ensures that lex order is maintained using a priority queue that stores elements in ascending order, and the desired repetition is achieved by keeping track of the letter count while traversing the string s.


# Amount of New Area Painted Each Day

- slug: amount-of-new-area-painted-each-day
- difficulty: Hard

There is a long and thin painting that can be represented by a number line. You are given a **0-indexed** 2D integer array `paint` of length `n`, where `paint[i] = [starti, endi]`. This means that on the `ith` day you need to paint the area **between** `starti` and `endi`.

Painting the same area multiple times will create an uneven painting so you only want to paint each area of the painting at most **once**.

Return _an integer array_ `worklog` _of length_ `n`_, where_ `worklog[i]` _is the amount of **new** area that you painted on the_ `ith` _day._

**Example 1:**

**Input:** paint = \[\[1,4\],\[4,7\],\[5,8\]\]
**Output:** \[3,3,1\]
**Explanation:**
On day 0, paint everything between 1 and 4.
The amount of new area painted on day 0 is 4 - 1 = 3.
On day 1, paint everything between 4 and 7.
The amount of new area painted on day 1 is 7 - 4 = 3.
On day 2, paint everything between 7 and 8.
Everything between 5 and 7 was already painted on day 1.
The amount of new area painted on day 2 is 8 - 7 = 1.

**Example 2:**

**Input:** paint = \[\[1,4\],\[5,8\],\[4,7\]\]
**Output:** \[3,3,1\]
**Explanation:**
On day 0, paint everything between 1 and 4.
The amount of new area painted on day 0 is 4 - 1 = 3.
On day 1, paint everything between 5 and 8.
The amount of new area painted on day 1 is 8 - 5 = 3.
On day 2, paint everything between 4 and 5.
Everything between 5 and 7 was already painted on day 1.
The amount of new area painted on day 2 is 5 - 4 = 1.

**Example 3:**

**Input:** paint = \[\[1,5\],\[2,4\]\]
**Output:** \[4,0\]
**Explanation:**
On day 0, paint everything between 1 and 5.
The amount of new area painted on day 0 is 5 - 1 = 4.
On day 1, paint nothing because everything between 2 and 4 was already painted on day 0.
The amount of new area painted on day 1 is 0.

**Constraints:**

*   `1 <= paint.length <= 105`
*   `paint[i].length == 2`
*   `0 <= starti < endi <= 5 * 104`

## A solution in Java

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

public Vector<Integer> paintingPlan(int[][] paint) {
    Vector<Integer> worklog = new Vector<>(paint.length);
    Set<Integer> painted = new HashSet<>();

    for (int i = 0; i < paint.length; i++) {
        int start = paint[i][0];
        int end = paint[i][1];
        int day_work = 0;

        for (int j = start; j < end; j++) {
            if (!painted.contains(j)) {
                painted.add(j);
                day_work++;
            }
        }

        worklog.add(day_work);
    }

    return worklog;
}
```
The algorithm follows these steps:
1. Create an array or vector `worklog` which will store the new painted areas on each day, and set all the initial values to 0.
2. Create a set `painted` which will store the areas (integer points) that have already been painted.
3. Iterate through the given `paint` array, for each day:
   1. Extract the start and end points of the painting area.
   2. Iterate through the points between the start and end.
   3. If the point is not in the `painted` set, add it to the set and increment the counter for the current day in the `worklog` array.
4. Return the `worklog` array.

## A solution in C++

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

std::vector<int> paintingPlan(const std::vector<std::vector<int>>& paint) {
    std::vector<int> worklog(paint.size(), 0);
    std::set<int> painted;

    for (std::size_t i = 0; i < paint.size(); ++i) {
        int start = paint[i][0];
        int end = paint[i][1];

        for (int j = start; j < end; ++j) {
            if (painted.count(j) == 0) {
                painted.insert(j);
                worklog[i]++;
            }
        }
    }

    return worklog;
}
```
The algorithm follows these steps:
1. Create an array or vector `worklog` which will store the new painted areas on each day, and set all the initial values to 0.
2. Create a set `painted` which will store the areas (integer points) that have already been painted.
3. Iterate through the given `paint` array, for each day:
   1. Extract the start and end points of the painting area.
   2. Iterate through the points between the start and end.
   3. If the point is not in the `painted` set, add it to the set and increment the counter for the current day in the `worklog` array.
4. Return the `worklog` array.

## A solution in Python

```python
def painting_plan(paint):
    worklog = [0] * len(paint)
    painted = set()

    for i in range(len(paint)):
        start, end = paint[i]

        for j in range(start, end):
            if j not in painted:
                painted.add(j)
                worklog[i] += 1

    return worklog
```
The algorithm follows these steps:
1. Create an array or vector `worklog` which will store the new painted areas on each day, and set all the initial values to 0.
2. Create a set `painted` which will store the areas (integer points) that have already been painted.
3. Iterate through the given `paint` array, for each day:
   1. Extract the start and end points of the painting area.
   2. Iterate through the points between the start and end.
   3. If the point is not in the `painted` set, add it to the set and increment the counter for the current day in the `worklog` array.
4. Return the `worklog` array.

## A solution in Javascript

```javascript
function paintingPlan(paint) {
    const worklog = new Array(paint.length).fill(0);
    const painted = new Set();

    for (let i = 0; i < paint.length; i++) {
        const [start, end] = paint[i];

        for (let j = start; j < end; j++) {
            if (!painted.has(j)) {
                painted.add(j);
                worklog[i]++;
            }
        }
    }

    return worklog;
}
```
The algorithm follows these steps:
1. Create an array or vector `worklog` which will store the new painted areas on each day, and set all the initial values to 0.
2. Create a set `painted` which will store the areas (integer points) that have already been painted.
3. Iterate through the given `paint` array, for each day:
   1. Extract the start and end points of the painting area.
   2. Iterate through the points between the start and end.
   3. If the point is not in the `painted` set, add it to the set and increment the counter for the current day in the `worklog` array.
4. Return the `worklog` array.


# Minimum Sum of Four Digit Number After Splitting Digits

- slug: minimum-sum-of-four-digit-number-after-splitting-digits
- difficulty: Easy

You are given a **positive** integer `num` consisting of exactly four digits. Split `num` into two new integers `new1` and `new2` by using the **digits** found in `num`. **Leading zeros** are allowed in `new1` and `new2`, and **all** the digits found in `num` must be used.

*   For example, given `num = 2932`, you have the following digits: two `2`'s, one `9` and one `3`. Some of the possible pairs `[new1, new2]` are `[22, 93]`, `[23, 92]`, `[223, 9]` and `[2, 329]`.

Return _the **minimum** possible sum of_ `new1` _and_ `new2`.

**Example 1:**

**Input:** num = 2932
**Output:** 52
**Explanation:** Some possible pairs \[new1, new2\] are \[29, 23\], \[223, 9\], etc.
The minimum sum can be obtained by the pair \[29, 23\]: 29 + 23 = 52.

**Example 2:**

**Input:** num = 4009
**Output:** 13
**Explanation:** Some possible pairs \[new1, new2\] are \[0, 49\], \[490, 0\], etc.
The minimum sum can be obtained by the pair \[4, 9\]: 4 + 9 = 13.

**Constraints:**

*   `1000 <= num <= 9999`

## A solution in Java

```java
public int minOperations(int[][] grid, int x) {
    int minElement = Integer.MAX_VALUE;
    for (int[] row : grid) {
        for (int cell : row) {
            minElement = Math.min(minElement, cell);
        }
    }

    int minOperations = Integer.MAX_VALUE;
    for (int base = minElement; ; --base) {
        int operations = 0;
        boolean impossible = false;
        for (int[] row : grid) {
            if (impossible) break;
            for (int cell : row) {
                int diff = Math.abs(cell - base);
                if (diff % x != 0) {
                    impossible = true;
                    break;
                }
                operations += diff / x;
            }
        }
        if (impossible) break;
        minOperations = Math.min(minOperations, operations);
    }

    return minOperations == Integer.MAX_VALUE ? -1 : minOperations;
}
```
- Find the minimum element in the grid
- Initialize the minimum operations to `inf`
- Start with `base` equal to the minimum element, and decrement by 1 for each iteration
- For each possible `base`, iterate over every element in the grid and calculate the absolute difference between the current element and `base`
- If the difference can't be evenly divided by `x`, mark it as impossible and break the loop
- Otherwise, add the number of operations required (difference / x) to obtain a uni-value grid
- Update the minimum operations with the minimum of the current minimum and the calculated operations
- Return -1 if the minimum operations remain `inf`, otherwise return the minimum operations found

## A solution in C++

```cpp
#include <vector>
#include <climits>
#include <cmath>

int min_operations(std::vector<std::vector<int>>& grid, int x) {
    int min_elem = INT_MAX;
    for (const auto& row : grid) {
        for (int cell : row) {
            min_elem = std::min(min_elem, cell);
        }
    }

    int min_operations = INT_MAX;
    for (int base = min_elem;; --base) {
        int operations = 0;
        bool impossible = false;
        for (const auto& row : grid) {
            if (impossible) break;
            for (int cell : row) {
                int diff = std::abs(cell - base);
                if (diff % x != 0) {
                    impossible = true;
                    break;
                }
                operations += diff / x;
            }
        }
        if (impossible) break;
        min_operations = std::min(min_operations, operations);
    }

    return min_operations == INT_MAX ? -1 : min_operations;
}
```
- Find the minimum element in the grid
- Initialize the minimum operations to `inf`
- Start with `base` equal to the minimum element, and decrement by 1 for each iteration
- For each possible `base`, iterate over every element in the grid and calculate the absolute difference between the current element and `base`
- If the difference can't be evenly divided by `x`, mark it as impossible and break the loop
- Otherwise, add the number of operations required (difference / x) to obtain a uni-value grid
- Update the minimum operations with the minimum of the current minimum and the calculated operations
- Return -1 if the minimum operations remain `inf`, otherwise return the minimum operations found

## A solution in Python

```python
def min_operations(grid, x):
    min_element = min(min(row) for row in grid)
    min_ops = float('inf')

    base = min_element
    while True:
        operations = 0
        impossible = False
        for row in grid:
            if impossible:
                break
            for cell in row:
                diff = abs(cell - base)
                if diff % x != 0:
                    impossible = True
                    break
                operations += diff // x
        if impossible:
            break
        min_ops = min(min_ops, operations)
        base -= 1

    return -1 if min_ops == float('inf') else min_ops
```
- Find the minimum element in the grid
- Initialize the minimum operations to `inf`
- Start with `base` equal to the minimum element, and decrement by 1 for each iteration
- For each possible `base`, iterate over every element in the grid and calculate the absolute difference between the current element and `base`
- If the difference can't be evenly divided by `x`, mark it as impossible and break the loop
- Otherwise, add the number of operations required (difference / x) to obtain a uni-value grid
- Update the minimum operations with the minimum of the current minimum and the calculated operations
- Return -1 if the minimum operations remain `inf`, otherwise return the minimum operations found

## A solution in Javascript

```javascript
function minOperations(grid, x) {
  const minElement = Math.min(...grid.map(row => Math.min(...row)));
  let minOps = Infinity;

  let base = minElement;
  while (true) {
      let operations = 0;
      let impossible = false;
      for (let row of grid) {
          if (impossible) break;
          for (let cell of row) {
              const diff = Math.abs(cell - base);
              if (diff % x !== 0) {
                  impossible = true;
                  break;
              }
              operations += diff / x;
          }
      }
      if (impossible) break;
      minOps = Math.min(minOps, operations);
      base -= 1;
  }

  return minOps === Infinity ? -1 : minOps;
}
```
- Find the minimum element in the grid
- Initialize the minimum operations to `inf`
- Start with `base` equal to the minimum element, and decrement by 1 for each iteration
- For each possible `base`, iterate over every element in the grid and calculate the absolute difference between the current element and `base`
- If the difference can't be evenly divided by `x`, mark it as impossible and break the loop
- Otherwise, add the number of operations required (difference / x) to obtain a uni-value grid
- Update the minimum operations with the minimum of the current minimum and the calculated operations
- Return -1 if the minimum operations remain `inf`, otherwise return the minimum operations found


# Minimum Cost to Set Cooking Time

- slug: minimum-cost-to-set-cooking-time
- difficulty: Medium

A generic microwave supports cooking times for:

*   at least `1` second.
*   at most `99` minutes and `99` seconds.

To set the cooking time, you push **at most four digits**. The microwave normalizes what you push as four digits by **prepending zeroes**. It interprets the **first** two digits as the minutes and the **last** two digits as the seconds. It then **adds** them up as the cooking time. For example,

*   You push `9` `5` `4` (three digits). It is normalized as `0954` and interpreted as `9` minutes and `54` seconds.
*   You push `0` `0` `0` `8` (four digits). It is interpreted as `0` minutes and `8` seconds.
*   You push `8` `0` `9` `0`. It is interpreted as `80` minutes and `90` seconds.
*   You push `8` `1` `3` `0`. It is interpreted as `81` minutes and `30` seconds.

You are given integers `startAt`, `moveCost`, `pushCost`, and `targetSeconds`. **Initially**, your finger is on the digit `startAt`. Moving the finger above **any specific digit** costs `moveCost` units of fatigue. Pushing the digit below the finger **once** costs `pushCost` units of fatigue.

There can be multiple ways to set the microwave to cook for `targetSeconds` seconds but you are interested in the way with the minimum cost.

Return _the **minimum cost** to set_ `targetSeconds` _seconds of cooking time_.

Remember that one minute consists of `60` seconds.

**Example 1:**

**Input:** startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600
**Output:** 6
**Explanation:** The following are the possible ways to set the cooking time.
- 1 0 0 0, interpreted as 10 minutes and 0 seconds.
  The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1).
  The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost.
- 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds.
  The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).
  The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12.
- 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds.
  The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).
  The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9.

**Example 2:**

**Input:** startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76
**Output:** 6
**Explanation:** The optimal way is to push two digits: 7 6, interpreted as 76 seconds.
The finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6
Note other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.

**Constraints:**

*   `0 <= startAt <= 9`
*   `1 <= moveCost, pushCost <= 105`
*   `1 <= targetSeconds <= 6039`

## A solution in Java

```java
import java.util.*;

public int minPartitionDifference(int[] nums) {
    int n = nums.length / 2;
    Arrays.sort(nums);
    int firstSum = 0, secondSum = 0;
    for (int i = nums.length - 1; i >= 0; i--) {
        if (i % 2 == 0) {
            firstSum += nums[i];
        } else {
            secondSum += nums[i];
        }
    }
    return Math.abs(firstSum - secondSum);
}
```
The algorithm for this problem consists of the following steps:

1. Sort the input array, nums, in descending order.
2. Divide the sorted array, nums, into two parts of equal length (n).
3. Calculate the sum of the first half of nums.
4. Calculate the sum of the second half of nums.
5. Return the absolute difference between the sums of the two halves.

The reason why sorting the input array works is because the largest difference between two numbers can be minimized by pairing them with the smallest numbers. Sorting the array from largest to smallest ensures that the largest numbers are paired with the smallest ones. Then we divide the array into two parts and find the absolute difference between their sums. That's the minimum possible absolute difference for the given input array.

## A solution in C++

```cpp
#include <vector>
#include <algorithm>
#include <numeric>
int minPartitionDifference(std::vector<int>& nums) {
    int n = nums.size() / 2;
    sort(nums.rbegin(), nums.rend());
    return std::accumulate(nums.begin(), nums.begin() + n, 0) - std::accumulate(nums.begin() + n, nums.end(), 0);
}
```
The algorithm for this problem consists of the following steps:

1. Sort the input array, nums, in descending order.
2. Divide the sorted array, nums, into two parts of equal length (n).
3. Calculate the sum of the first half of nums.
4. Calculate the sum of the second half of nums.
5. Return the absolute difference between the sums of the two halves.

The reason why sorting the input array works is because the largest difference between two numbers can be minimized by pairing them with the smallest numbers. Sorting the array from largest to smallest ensures that the largest numbers are paired with the smallest ones. Then we divide the array into two parts and find the absolute difference between their sums. That's the minimum possible absolute difference for the given input array.

## A solution in Python

```python
def min_partition_difference(nums):
    n = len(nums) // 2
    nums.sort(reverse=True)
    return sum(nums[:n]) - sum(nums[n:])
```
The algorithm for this problem consists of the following steps:

1. Sort the input array, nums, in descending order.
2. Divide the sorted array, nums, into two parts of equal length (n).
3. Calculate the sum of the first half of nums.
4. Calculate the sum of the second half of nums.
5. Return the absolute difference between the sums of the two halves.

The reason why sorting the input array works is because the largest difference between two numbers can be minimized by pairing them with the smallest numbers. Sorting the array from largest to smallest ensures that the largest numbers are paired with the smallest ones. Then we divide the array into two parts and find the absolute difference between their sums. That's the minimum possible absolute difference for the given input array.

## A solution in Javascript

```javascript
function minPartitionDifference(nums) {
    const n = nums.length / 2;
    nums.sort((a, b) => b - a);
    const firstSum = nums.slice(0, n).reduce((a, b) => a + b, 0);
    const secondSum = nums.slice(n).reduce((a, b) => a + b, 0);
    return Math.abs(firstSum - secondSum);
}
```
The algorithm for this problem consists of the following steps:

1. Sort the input array, nums, in descending order.
2. Divide the sorted array, nums, into two parts of equal length (n).
3. Calculate the sum of the first half of nums.
4. Calculate the sum of the second half of nums.
5. Return the absolute difference between the sums of the two halves.

The reason why sorting the input array works is because the largest difference between two numbers can be minimized by pairing them with the smallest numbers. Sorting the array from largest to smallest ensures that the largest numbers are paired with the smallest ones. Then we divide the array into two parts and find the absolute difference between their sums. That's the minimum possible absolute difference for the given input array.


# Minimum Difference in Sums After Removal of Elements

- slug: minimum-difference-in-sums-after-removal-of-elements
- difficulty: Hard

You are given a **0-indexed** integer array `nums` consisting of `3 * n` elements.

You are allowed to remove any **subsequence** of elements of size **exactly** `n` from `nums`. The remaining `2 * n` elements will be divided into two **equal** parts:

*   The first `n` elements belonging to the first part and their sum is `sumfirst`.
*   The next `n` elements belonging to the second part and their sum is `sumsecond`.

The **difference in sums** of the two parts is denoted as `sumfirst - sumsecond`.

*   For example, if `sumfirst = 3` and `sumsecond = 2`, their difference is `1`.
*   Similarly, if `sumfirst = 2` and `sumsecond = 3`, their difference is `-1`.

Return _the **minimum difference** possible between the sums of the two parts after the removal of_ `n` _elements_.

**Example 1:**

**Input:** nums = \[3,1,2\]
**Output:** -1
**Explanation:** Here, nums has 3 elements, so n = 1.
Thus we have to remove 1 element from nums and divide the array into two equal parts.
- If we remove nums\[0\] = 3, the array will be \[1,2\]. The difference in sums of the two parts will be 1 - 2 = -1.
- If we remove nums\[1\] = 1, the array will be \[3,2\]. The difference in sums of the two parts will be 3 - 2 = 1.
- If we remove nums\[2\] = 2, the array will be \[3,1\]. The difference in sums of the two parts will be 3 - 1 = 2.
The minimum difference between sums of the two parts is min(-1,1,2) = -1.

**Example 2:**

**Input:** nums = \[7,9,5,8,1,3\]
**Output:** 1
**Explanation:** Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each.
If we remove nums\[2\] = 5 and nums\[3\] = 8, the resultant array will be \[7,9,1,3\]. The difference in sums will be (7+9) - (1+3) = 12.
To obtain the minimum difference, we should remove nums\[1\] = 9 and nums\[4\] = 1. The resultant array becomes \[7,5,8,3\]. The difference in sums of the two parts is (7+5) - (8+3) = 1.
It can be shown that it is not possible to obtain a difference smaller than 1.

**Constraints:**

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

## A solution in Java

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

public String kthDistinctString(String[] arr, int k) {
    Map<String, Integer> frequency = new HashMap<>();
    for (String s : arr) {
        frequency.put(s, frequency.getOrDefault(s, 0) + 1);
    }

    int count = 0;
    for (String s : arr) {
        if (frequency.get(s) == 1) {
            count++;
            if (count == k) {
                return s;
            }
        }
    }

    return "";
}
```
1. Create a hash table (unordered_map, HashMap, or dictionary, depending on the language) to store the frequency of strings in the input array.
2. Iterate over the input array and increment the frequency of each string in the hash table.
3. Initialize a count variable to keep track of the distinct strings found so far.
4. Iterate over the input array again, checking the frequency of each string in the hash table.
5. If the frequency is 1 (distinct), increment the count variable.
6. If the count reaches k, return the current string.
7. If no kth distinct string is found, return an empty string.

## A solution in C++

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

string kthDistinctString(vector<string>& arr, int k) {
    unordered_map<string, int>Frequency;
    for (const string& s : arr) {
        Frequency[s]++;
    }

    int count = 0;
    for (const string& s : arr) {
        if (Frequency[s] == 1) {
            count++;
            if (count == k) {
                return s;
            }
        }
    }

    return "";
}
```
1. Create a hash table (unordered_map, HashMap, or dictionary, depending on the language) to store the frequency of strings in the input array.
2. Iterate over the input array and increment the frequency of each string in the hash table.
3. Initialize a count variable to keep track of the distinct strings found so far.
4. Iterate over the input array again, checking the frequency of each string in the hash table.
5. If the frequency is 1 (distinct), increment the count variable.
6. If the count reaches k, return the current string.
7. If no kth distinct string is found, return an empty string.

## A solution in Python

```python
def kth_distinct_string(arr, k):
    frequency = {}
    for s in arr:
        frequency[s] = frequency.get(s, 0) + 1

    count = 0
    for s in arr:
        if frequency[s] == 1:
            count += 1
            if count == k:
                return s

    return ""
```
1. Create a hash table (unordered_map, HashMap, or dictionary, depending on the language) to store the frequency of strings in the input array.
2. Iterate over the input array and increment the frequency of each string in the hash table.
3. Initialize a count variable to keep track of the distinct strings found so far.
4. Iterate over the input array again, checking the frequency of each string in the hash table.
5. If the frequency is 1 (distinct), increment the count variable.
6. If the count reaches k, return the current string.
7. If no kth distinct string is found, return an empty string.

## A solution in Javascript

```javascript
function kthDistinctString(arr, k) {
    const frequency = {};
    for (const s of arr) {
        frequency[s] = (frequency[s] || 0) + 1;
    }

    let count = 0;
    for (const s of arr) {
        if (frequency[s] === 1) {
            count++;
            if (count === k) {
                return s;
            }
        }
    }

    return '';
}
```
1. Create a hash table (unordered_map, HashMap, or dictionary, depending on the language) to store the frequency of strings in the input array.
2. Iterate over the input array and increment the frequency of each string in the hash table.
3. Initialize a count variable to keep track of the distinct strings found so far.
4. Iterate over the input array again, checking the frequency of each string in the hash table.
5. If the frequency is 1 (distinct), increment the count variable.
6. If the count reaches k, return the current string.
7. If no kth distinct string is found, return an empty string.


# Sort Even and Odd Indices Independently

- slug: sort-even-and-odd-indices-independently
- difficulty: Easy

You are given a **0-indexed** integer array `nums`. Rearrange the values of `nums` according to the following rules:

1.  Sort the values at **odd indices** of `nums` in **non-increasing** order.
    *   For example, if `nums = [4,**1**,2,**3**]` before this step, it becomes `[4,**3**,2,**1**]` after. The values at odd indices `1` and `3` are sorted in non-increasing order.
2.  Sort the values at **even indices** of `nums` in **non-decreasing** order.
    *   For example, if `nums = [**4**,1,**2**,3]` before this step, it becomes `[**2**,1,**4**,3]` after. The values at even indices `0` and `2` are sorted in non-decreasing order.

Return _the array formed after rearranging the values of_ `nums`.

**Example 1:**

**Input:** nums = \[4,1,2,3\]
**Output:** \[2,3,4,1\]
**Explanation:**
First, we sort the values present at odd indices (1 and 3) in non-increasing order.
So, nums changes from \[4,**1**,2,**3**\] to \[4,**3**,2,**1**\].
Next, we sort the values present at even indices (0 and 2) in non-decreasing order.
So, nums changes from \[**4**,1,**2**,3\] to \[**2**,3,**4**,1\].
Thus, the array formed after rearranging the values is \[2,3,4,1\].

**Example 2:**

**Input:** nums = \[2,1\]
**Output:** \[2,1\]
**Explanation:**
Since there is exactly one odd index and one even index, no rearrangement of values takes place.
The resultant array formed is \[2,1\], which is the same as the initial array.

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int maxValue(int[][] events) {
    Arrays.sort(events, (a, b) -> Integer.compare(a[1], b[1]));

    int[] dp = new int[events.length];
    dp[0] = events[0][2];

    for (int i = 1; i < events.length; i++) {
        int lastNonConflict = -1;
        for (int j = i - 1; j >= 0; j--) {
            if (events[j][1] < events[i][0]) {
                lastNonConflict = j;
                break;
            }
        }

        int includedValue = events[i][2];
        if (lastNonConflict != -1) {
            includedValue += dp[lastNonConflict];
        }

        dp[i] = Math.max(includedValue, dp[i - 1]);
    }

    return dp[dp.length - 1];
}
```
The problem can be solved using a dynamic programming approach. We first sort the events array by the end times in ascending order. Initialize an array `dp` of the same length as the number of events, and set the first value to the value of the first sorted event. Then, for each event in the sorted array starting from the second event, perform the following:

1. Find the last non-conflicting event index (i.e., the event index with the end time less than the current event's start time) and store that as `lastNonConflict`. Start the search from the previous event and go backward.

2. Calculate the value if we include the current event, which is the current event's value and the value of lastNonConflict (if it exists) from the dp array.

3. Get the maximum value between the included value (calculated in step 2) and the value of the previous event. Update the dp array at the current index with the maximum value.

Finally, return the last value from the `dp` array as it represents the maximum sum after considering all events.

## A solution in C++

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

int maxValue(vector<vector<int>>& events) {
    sort(events.begin(), events.end(), [](const vector<int>& a, const vector<int>& b) {
        return a[1] < b[1];
    });

    vector<int> dp(events.size());
    dp[0] = events[0][2];

    for (int i = 1; i < events.size(); i++) {
        int lastNonConflict = -1;
        for (int j = i - 1; j >= 0; j--) {
            if (events[j][1] < events[i][0]) {
                lastNonConflict = j;
                break;
            }
        }

        int includedValue = events[i][2];
        if (lastNonConflict != -1) {
            includedValue += dp[lastNonConflict];
        }

        dp[i] = max(includedValue, dp[i - 1]);
    }

    return dp.back();
}
```
The problem can be solved using a dynamic programming approach. We first sort the events array by the end times in ascending order. Initialize an array `dp` of the same length as the number of events, and set the first value to the value of the first sorted event. Then, for each event in the sorted array starting from the second event, perform the following:

1. Find the last non-conflicting event index (i.e., the event index with the end time less than the current event's start time) and store that as `lastNonConflict`. Start the search from the previous event and go backward.

2. Calculate the value if we include the current event, which is the current event's value and the value of lastNonConflict (if it exists) from the dp array.

3. Get the maximum value between the included value (calculated in step 2) and the value of the previous event. Update the dp array at the current index with the maximum value.

Finally, return the last value from the `dp` array as it represents the maximum sum after considering all events.

## A solution in Python

```python
def maxValue(events):
    events.sort(key=lambda a: a[1])

    dp = [0] * len(events)
    dp[0] = events[0][2]

    for i in range(1, len(events)):
        lastNonConflict = -1
        for j in range(i - 1, -1, -1):
            if events[j][1] < events[i][0]:
                lastNonConflict = j
                break

        includedValue = events[i][2]
        if lastNonConflict != -1:
            includedValue += dp[lastNonConflict]

        dp[i] = max(includedValue, dp[i - 1])

    return dp[-1]
```
The problem can be solved using a dynamic programming approach. We first sort the events array by the end times in ascending order. Initialize an array `dp` of the same length as the number of events, and set the first value to the value of the first sorted event. Then, for each event in the sorted array starting from the second event, perform the following:

1. Find the last non-conflicting event index (i.e., the event index with the end time less than the current event's start time) and store that as `lastNonConflict`. Start the search from the previous event and go backward.

2. Calculate the value if we include the current event, which is the current event's value and the value of lastNonConflict (if it exists) from the dp array.

3. Get the maximum value between the included value (calculated in step 2) and the value of the previous event. Update the dp array at the current index with the maximum value.

Finally, return the last value from the `dp` array as it represents the maximum sum after considering all events.

## A solution in Javascript

```javascript
function maxValue(events) {
    events.sort((a, b) => a[1] - b[1]);

    let dp = new Array(events.length);
    dp[0] = events[0][2];

    for (let i = 1; i < events.length; i++) {
        let lastNonConflict = -1;
        for (let j = i - 1; j >= 0; j--) {
            if (events[j][1] < events[i][0]) {
                lastNonConflict = j;
                break;
            }
        }

        let includedValue = events[i][2];
        if (lastNonConflict !== -1) {
            includedValue += dp[lastNonConflict];
        }

        dp[i] = Math.max(includedValue, dp[i - 1]);
    }

    return dp[dp.length - 1];
}
```
The problem can be solved using a dynamic programming approach. We first sort the events array by the end times in ascending order. Initialize an array `dp` of the same length as the number of events, and set the first value to the value of the first sorted event. Then, for each event in the sorted array starting from the second event, perform the following:

1. Find the last non-conflicting event index (i.e., the event index with the end time less than the current event's start time) and store that as `lastNonConflict`. Start the search from the previous event and go backward.

2. Calculate the value if we include the current event, which is the current event's value and the value of lastNonConflict (if it exists) from the dp array.

3. Get the maximum value between the included value (calculated in step 2) and the value of the previous event. Update the dp array at the current index with the maximum value.

Finally, return the last value from the `dp` array as it represents the maximum sum after considering all events.


# Smallest Value of the Rearranged Number

- slug: smallest-value-of-the-rearranged-number
- difficulty: Medium

You are given an integer `num.` **Rearrange** the digits of `num` such that its value is **minimized** and it does not contain **any** leading zeros.

Return _the rearranged number with minimal value_.

Note that the sign of the number does not change after rearranging the digits.

**Example 1:**

**Input:** num = 310
**Output:** 103
**Explanation:** The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310.
The arrangement with the smallest value that does not contain any leading zeros is 103.

**Example 2:**

**Input:** num = -7605
**Output:** -7650
**Explanation:** Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.
The arrangement with the smallest value that does not contain any leading zeros is -7650.

**Constraints:**

*   `-1015 <= num <= 1015`

## A solution in Java

```java
import java.util.*;

class Solution {
    public List<Integer> platesBetweenCandles(String s, int[][] queries) {
        int n = s.length();
        int[] prefix = new int[n];
        int plates = 0;
        for (int i = 1; i < n; ++i) {
            prefix[i] = prefix[i - 1];
            if (s.charAt(i) == '*' && s.charAt(i - 1) == '|') {
                plates++;
            }
            prefix[i] += plates;
        }
        List<Integer> res = new ArrayList<>();
        for (int[] q : queries) {
            int left = q[0], right = q[1];
            res.add(prefix[right] - (left > 0 ? prefix[left - 1] : 0));
        }
        return res;
    }
}
```
1. Calculate the prefix sum of plates between candles for the entire string `s`. The `prefix` array will store this information.
2. Loop through `s` from the second character (i.e., index 1) to the end:
   a. Update the prefix sum for each index by adding the previous prefix sum.
   b. If the current character is a plate '*' and the previous character is a candle '|', increment the plates counter.
   c. Add the plates counter to the prefix sum.
3. Initialize an empty result array to store the answers for each query.
4. For each query, calculate the number of plates between candles in the substring by subtracting the prefix sum at index `left - 1` from the sum at index `right`. Ensure the value at `left - 1` is not negative.
5. Add the result of each query to the result array and return it.

## A solution in C++

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

std::vector<int> platesBetweenCandles(const std::string& s, const std::vector<std::vector<int>>& queries) {
    int n = s.length();
    std::vector<int> prefix(n, 0);
    int plates = 0;

    for (int i = 1; i < n; ++i) {
        prefix[i] = prefix[i - 1];
        if (s[i] == '*' && s[i - 1] == '|') plates++;
        prefix[i] += plates;
    }
    std::vector<int> res;
    for (const auto& q : queries) {
        int left = q[0], right = q[1];
        res.push_back(prefix[right] - (left > 0 ? prefix[left - 1] : 0));
    }
    return res;
}
```
1. Calculate the prefix sum of plates between candles for the entire string `s`. The `prefix` array will store this information.
2. Loop through `s` from the second character (i.e., index 1) to the end:
   a. Update the prefix sum for each index by adding the previous prefix sum.
   b. If the current character is a plate '*' and the previous character is a candle '|', increment the plates counter.
   c. Add the plates counter to the prefix sum.
3. Initialize an empty result array to store the answers for each query.
4. For each query, calculate the number of plates between candles in the substring by subtracting the prefix sum at index `left - 1` from the sum at index `right`. Ensure the value at `left - 1` is not negative.
5. Add the result of each query to the result array and return it.

## A solution in Python

```python
from typing import List, Tuple

def plates_between_candles(s: str, queries: List[Tuple[int, int]]) -> List[int]:
    n = len(s)
    prefix = [0] * n
    plates = 0

    for i in range(1, n):
        prefix[i] = prefix[i - 1]
        if s[i] == '*' and s[i - 1] == '|':
            plates += 1
        prefix[i] += plates

    res = []
    for left, right in queries:
        res.append(prefix[right] - (prefix[left - 1] if left > 0 else 0))

    return res
```
1. Calculate the prefix sum of plates between candles for the entire string `s`. The `prefix` array will store this information.
2. Loop through `s` from the second character (i.e., index 1) to the end:
   a. Update the prefix sum for each index by adding the previous prefix sum.
   b. If the current character is a plate '*' and the previous character is a candle '|', increment the plates counter.
   c. Add the plates counter to the prefix sum.
3. Initialize an empty result array to store the answers for each query.
4. For each query, calculate the number of plates between candles in the substring by subtracting the prefix sum at index `left - 1` from the sum at index `right`. Ensure the value at `left - 1` is not negative.
5. Add the result of each query to the result array and return it.

## A solution in Javascript

```javascript
function platesBetweenCandles(s, queries) {
    const n = s.length;
    const prefix = new Array(n).fill(0);
    let plates = 0;

    for (let i = 1; i < n; ++i) {
        prefix[i] = prefix[i - 1];
        if (s[i] === '*' && s[i - 1] === '|') plates++;
        prefix[i] += plates;
    }
    const res = [];

    for (const q of queries) {
        const left = q[0], right = q[1];
        res.push(prefix[right] - (left > 0 ? prefix[left - 1] : 0));
    }

    return res;
}
```
1. Calculate the prefix sum of plates between candles for the entire string `s`. The `prefix` array will store this information.
2. Loop through `s` from the second character (i.e., index 1) to the end:
   a. Update the prefix sum for each index by adding the previous prefix sum.
   b. If the current character is a plate '*' and the previous character is a candle '|', increment the plates counter.
   c. Add the plates counter to the prefix sum.
3. Initialize an empty result array to store the answers for each query.
4. For each query, calculate the number of plates between candles in the substring by subtracting the prefix sum at index `left - 1` from the sum at index `right`. Ensure the value at `left - 1` is not negative.
5. Add the result of each query to the result array and return it.