# Design File System

- slug: design-file-system
- difficulty: Medium

You are asked to design a file system that allows you to create new paths and associate them with different values.

The format of a path is one or more concatenated strings of the form: `/` followed by one or more lowercase English letters. For example, "`/leetcode "` and "`/leetcode/problems "` are valid paths while an empty string `" "` and `"/ "` are not.

Implement the `FileSystem` class:

*   `bool createPath(string path, int value)` Creates a new `path` and associates a `value` to it if possible and returns `true`. Returns `false` if the path **already exists** or its parent path **doesn't exist**.
*   `int get(string path)` Returns the value associated with `path` or returns `-1` if the path doesn't exist.

**Example 1:**

**Input:**
\[ "FileSystem ", "createPath ", "get "\]
\[\[\],\[ "/a ",1\],\[ "/a "\]\]
**Output:**
\[null,true,1\]
**Explanation:**
FileSystem fileSystem = new FileSystem();

fileSystem.createPath( "/a ", 1); // return true
fileSystem.get( "/a "); // return 1

**Example 2:**

**Input:**
\[ "FileSystem ", "createPath ", "createPath ", "get ", "createPath ", "get "\]
\[\[\],\[ "/leet ",1\],\[ "/leet/code ",2\],\[ "/leet/code "\],\[ "/c/d ",1\],\[ "/c "\]\]
**Output:**
\[null,true,true,2,false,-1\]
**Explanation:**
FileSystem fileSystem = new FileSystem();

fileSystem.createPath( "/leet ", 1); // return true
fileSystem.createPath( "/leet/code ", 2); // return true
fileSystem.get( "/leet/code "); // return 2
fileSystem.createPath( "/c/d ", 1); // return false because the parent path  "/c " doesn't exist.
fileSystem.get( "/c "); // return -1 because this path doesn't exist.

**Constraints:**

*   `2 <= path.length <= 100`
*   `1 <= value <= 109`
*   Each `path` is **valid** and consists of lowercase English letters and `'/'`.
*   At most `104` calls **in total** will be made to `createPath` and `get`.

## A solution in Java

```java
import java.util.HashMap;

class FileSystem {
    private final HashMap<String, Integer> pathMap;

    public FileSystem() {
        pathMap = new HashMap<>();
    }

    public boolean createPath(String path, int value) {
        if (pathMap.containsKey(path)) return false;
        String parentPath = path.substring(0, path.lastIndexOf('/'));
        if (!parentPath.isEmpty() && !pathMap.containsKey(parentPath)) return false;
        pathMap.put(path, value);
        return true;
    }

    public int get(String path) {
        return pathMap.getOrDefault(path, -1);
    }
}
```
The algorithm for implementing the FileSystem class is relatively straightforward. It involves implementing a map (i.e., a HashMap, unordered_map, or a dictionary) to store the paths and their associated values. For the `createPath` method, we first check if the given path already exists in the map. If it does, then we return `false`. If it does not exist, we then extract the parent path of the input path and check if it exists in the map. If the parent path does not exist, we return `false`; otherwise, we insert the path and its associated value into the map and return `true`.

The `get` method is straightforward; we simply return the value associated with the given path from the map, or return `-1` if the path does not exist.

Both methods have time complexity O(1) because map operations (i.e., insert, find, get) take constant time on average.

## A solution in C++

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

class FileSystem {
public:
    unordered_map<string, int> pathMap;

    bool createPath(string path, int value) {
        if (pathMap.count(path) != 0) return false;
        string parentPath = path.substr(0, path.find_last_of('/'));
        if (!parentPath.empty() && pathMap.count(parentPath) == 0) return false;
        pathMap[path] = value;
        return true;
    }

    int get(string path) {
        if (pathMap.count(path) == 0) return -1;
        return pathMap[path];
    }
};
```
The algorithm for implementing the FileSystem class is relatively straightforward. It involves implementing a map (i.e., a HashMap, unordered_map, or a dictionary) to store the paths and their associated values. For the `createPath` method, we first check if the given path already exists in the map. If it does, then we return `false`. If it does not exist, we then extract the parent path of the input path and check if it exists in the map. If the parent path does not exist, we return `false`; otherwise, we insert the path and its associated value into the map and return `true`.

The `get` method is straightforward; we simply return the value associated with the given path from the map, or return `-1` if the path does not exist.

Both methods have time complexity O(1) because map operations (i.e., insert, find, get) take constant time on average.

## A solution in Python

```python
class FileSystem:
    def __init__(self):
        self.path_map = {}

    def create_path(self, path: str, value: int) -> bool:
        if path in self.path_map:
            return False
        parent_path = path[:path.rfind('/')]
        if parent_path and parent_path not in self.path_map:
            return False
        self.path_map[path] = value
        return True

    def get(self, path: str) -> int:
        return self.path_map.get(path, -1)
```
The algorithm for implementing the FileSystem class is relatively straightforward. It involves implementing a map (i.e., a HashMap, unordered_map, or a dictionary) to store the paths and their associated values. For the `createPath` method, we first check if the given path already exists in the map. If it does, then we return `false`. If it does not exist, we then extract the parent path of the input path and check if it exists in the map. If the parent path does not exist, we return `false`; otherwise, we insert the path and its associated value into the map and return `true`.

The `get` method is straightforward; we simply return the value associated with the given path from the map, or return `-1` if the path does not exist.

Both methods have time complexity O(1) because map operations (i.e., insert, find, get) take constant time on average.

## A solution in Javascript

```javascript
class FileSystem {
    constructor() {
        this.pathMap = new Map();
    }

    createPath(path, value) {
        if (this.pathMap.has(path)) return false;
        const parentPath = path.substring(0, path.lastIndexOf('/'));
        if (parentPath !== "" && !this.pathMap.has(parentPath)) return false;
        this.pathMap.set(path, value);
        return true;
    }

    get(path) {
        return this.pathMap.get(path) || -1;
    }
}
```
The algorithm for implementing the FileSystem class is relatively straightforward. It involves implementing a map (i.e., a HashMap, unordered_map, or a dictionary) to store the paths and their associated values. For the `createPath` method, we first check if the given path already exists in the map. If it does, then we return `false`. If it does not exist, we then extract the parent path of the input path and check if it exists in the map. If the parent path does not exist, we return `false`; otherwise, we insert the path and its associated value into the map and return `true`.

The `get` method is straightforward; we simply return the value associated with the given path from the map, or return `-1` if the path does not exist.

Both methods have time complexity O(1) because map operations (i.e., insert, find, get) take constant time on average.


# Minimum Cost to Connect Sticks

- slug: minimum-cost-to-connect-sticks
- difficulty: Medium

You have some number of sticks with positive integer lengths. These lengths are given as an array `sticks`, where `sticks[i]` is the length of the `ith` stick.

You can connect any two sticks of lengths `x` and `y` into one stick by paying a cost of `x + y`. You must connect all the sticks until there is only one stick remaining.

Return _the minimum cost of connecting all the given sticks into one stick in this way_.

**Example 1:**

**Input:** sticks = \[2,4,3\]
**Output:** 14
**Explanation:** You start with sticks = \[2,4,3\].
1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = \[5,4\].
2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = \[9\].
There is only one stick left, so you are done. The total cost is 5 + 9 = 14.

**Example 2:**

**Input:** sticks = \[1,8,3,5\]
**Output:** 30
**Explanation:** You start with sticks = \[1,8,3,5\].
1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = \[4,8,5\].
2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = \[9,8\].
3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = \[17\].
There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30.

**Example 3:**

**Input:** sticks = \[5\]
**Output:** 0
**Explanation:** There is only one stick, so you don't need to do anything. The total cost is 0.

**Constraints:**

*   `1 <= sticks.length <= 104`
*   `1 <= sticks[i] <= 104`

## A solution in Java

```java
import java.util.PriorityQueue;

public int connectSticks(int[] sticks) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();

    for (int stick : sticks) {
        minHeap.offer(stick);
    }

    int cost = 0;
    while (minHeap.size() > 1) {
        int first = minHeap.poll();
        int second = minHeap.poll();
        cost += first + second;
        minHeap.offer(first + second);
    }
    return cost;
}
```
The algorithm works by turning the input array `sticks` into a min heap, a data structure that allows for efficient retrieval of the smallest element in the heap. The algorithm then iterates until there is only one stick left, removing the two smallest sticks from the heap, combining them and adding their sum back into the heap. The cost of combining the two sticks is added to the total cost. After all the sticks have been combined, the function returns the total cost. The algorithm has a time complexity of O(n log n) where n is the number of elements in the input array, as each operation in the heap takes O(log n) time, and we perform about n operations.

## A solution in C++

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

int connectSticks(std::vector<int>& sticks) {
    std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap;

    for (int stick : sticks) {
        min_heap.push(stick);
    }

    int cost = 0;
    while (min_heap.size() > 1) {
        int first = min_heap.top();
        min_heap.pop();
        int second = min_heap.top();
        min_heap.pop();
        cost += first + second;
        min_heap.push(first + second);
    }
    return cost;
}
```
The algorithm works by turning the input array `sticks` into a min heap, a data structure that allows for efficient retrieval of the smallest element in the heap. The algorithm then iterates until there is only one stick left, removing the two smallest sticks from the heap, combining them and adding their sum back into the heap. The cost of combining the two sticks is added to the total cost. After all the sticks have been combined, the function returns the total cost. The algorithm has a time complexity of O(n log n) where n is the number of elements in the input array, as each operation in the heap takes O(log n) time, and we perform about n operations.

## A solution in Python

```python
import heapq

def connectSticks(sticks):
    heapq.heapify(sticks)
    cost = 0
    while len(sticks) > 1:
        first = heapq.heappop(sticks)
        second = heapq.heappop(sticks)
        cost += first + second
        heapq.heappush(sticks, first + second)
    return cost
```
The algorithm works by turning the input array `sticks` into a min heap, a data structure that allows for efficient retrieval of the smallest element in the heap. The algorithm then iterates until there is only one stick left, removing the two smallest sticks from the heap, combining them and adding their sum back into the heap. The cost of combining the two sticks is added to the total cost. After all the sticks have been combined, the function returns the total cost. The algorithm has a time complexity of O(n log n) where n is the number of elements in the input array, as each operation in the heap takes O(log n) time, and we perform about n operations.

## A solution in Javascript

```javascript
function connectSticks(sticks) {
    const minHeap = new MinHeap(sticks);

    let cost = 0;
    while (minHeap.size() > 1) {
        const first = minHeap.poll();
        const second = minHeap.poll();
        cost += first + second;
        minHeap.offer(first + second);
    }
    return cost;
}

class MinHeap {
    constructor(items) {
        this.heap = [];
        for (const item of items) {
            this.offer(item);
        }
    }

    offer(value) {
        this.heap.push(value);
        this.bubbleUp(this.heap.length - 1);
    }

    poll() {
        const min = this.heap[0];
        this.heap[0] = this.heap.pop();
        this.bubbleDown(0);
        return min;
    }

    size() {
        return this.heap.length;
    }

    bubbleUp(index) {
        if (index === 0) return;
        const parentIndex = Math.floor((index - 1) / 2);
        if (this.heap[parentIndex] > this.heap[index]) {
            [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
            this.bubbleUp(parentIndex);
        }
    }

    bubbleDown(index) {
        const leftChildIndex = 2 * index + 1;
        const rightChildIndex = 2 * index + 2;

        let minIndex = index;
        if (leftChildIndex < this.heap.length && this.heap[leftChildIndex] < this.heap[minIndex]) {
            minIndex = leftChildIndex;
        }

        if (rightChildIndex < this.heap.length && this.heap[rightChildIndex] < this.heap[minIndex]) {
            minIndex = rightChildIndex;
        }

        if (minIndex !== index) {
            [this.heap[minIndex], this.heap[index]] = [this.heap[index], this.heap[minIndex]];
            this.bubbleDown(minIndex);
        }
    }
}
```
The algorithm works by turning the input array `sticks` into a min heap, a data structure that allows for efficient retrieval of the smallest element in the heap. The algorithm then iterates until there is only one stick left, removing the two smallest sticks from the heap, combining them and adding their sum back into the heap. The cost of combining the two sticks is added to the total cost. After all the sticks have been combined, the function returns the total cost. The algorithm has a time complexity of O(n log n) where n is the number of elements in the input array, as each operation in the heap takes O(log n) time, and we perform about n operations.


# Optimize Water Distribution in a Village

- slug: optimize-water-distribution-in-a-village
- difficulty: Hard

There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes.

For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs.

Return _the minimum total cost to supply water to all houses_.

**Example 1:**

**Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\]
**Output:** 3
**Explanation:** The image shows the costs of connecting houses using pipes.
The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3.

**Example 2:**

**Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\]
**Output:** 2
**Explanation:** We can supply water with cost two using one of the three options:
Option 1:
  - Build a well inside house 1 with cost 1.
  - Build a well inside house 2 with cost 1.
The total cost will be 2.
Option 2:
  - Build a well inside house 1 with cost 1.
  - Connect house 2 with house 1 with cost 1.
The total cost will be 2.
Option 3:
  - Build a well inside house 2 with cost 1.
  - Connect house 1 with house 2 with cost 1.
The total cost will be 2.
Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**.

**Constraints:**

*   `2 <= n <= 104`
*   `wells.length == n`
*   `0 <= wells[i] <= 105`
*   `1 <= pipes.length <= 104`
*   `pipes[j].length == 3`
*   `1 <= house1j, house2j <= n`
*   `0 <= costj <= 105`
*   `house1j != house2j`

## A solution in Java

```java
public void duplicateZeros(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] == 0) {
            for (int j = n - 2; j > i; j--) {
                arr[j + 1] = arr[j];
            }
            arr[i + 1] = 0;
            i++;
        }
    }
}
```
The algorithm iterates through the input array from left to right. Whenever a zero is found, it shifts all the elements after that zero one position to the right, starting from the second-to-last element, up to the element that is right after the zero. Then, it sets the next array index (i+1) to zero, effectively duplicating the zero, and increments i by one to skip the duplicated zero. This process repeats for each zero found in the array, until the end is reached.

## A solution in C++

```cpp
void duplicateZeros(vector<int>& arr) {
    int n = arr.size();
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] == 0) {
            for (int j = n - 2; j > i; j--) {
                arr[j + 1] = arr[j];
            }
            arr[i + 1] = 0;
            i++;
        }
    }
}
```
The algorithm iterates through the input array from left to right. Whenever a zero is found, it shifts all the elements after that zero one position to the right, starting from the second-to-last element, up to the element that is right after the zero. Then, it sets the next array index (i+1) to zero, effectively duplicating the zero, and increments i by one to skip the duplicated zero. This process repeats for each zero found in the array, until the end is reached.

## A solution in Python

```python
def duplicateZeros(arr):
    n = len(arr)
    i = 0
    while i < n - 1:
        if arr[i] == 0:
            for j in range(n - 2, i, -1):
                arr[j + 1] = arr[j]
            arr[i + 1] = 0
            i += 2
        else:
            i += 1
```
The algorithm iterates through the input array from left to right. Whenever a zero is found, it shifts all the elements after that zero one position to the right, starting from the second-to-last element, up to the element that is right after the zero. Then, it sets the next array index (i+1) to zero, effectively duplicating the zero, and increments i by one to skip the duplicated zero. This process repeats for each zero found in the array, until the end is reached.

## A solution in Javascript

```javascript
function duplicateZeros(arr) {
    let n = arr.length;
    for (let i = 0; i < n - 1; i++) {
        if (arr[i] === 0) {
            for (let j = n - 2; j > i; j--) {
                arr[j + 1] = arr[j];
            }
            arr[i + 1] = 0;
            i++;
        }
    }
}
```
The algorithm iterates through the input array from left to right. Whenever a zero is found, it shifts all the elements after that zero one position to the right, starting from the second-to-last element, up to the element that is right after the zero. Then, it sets the next array index (i+1) to zero, effectively duplicating the zero, and increments i by one to skip the duplicated zero. This process repeats for each zero found in the array, until the end is reached.


# Invalid Transactions

- slug: invalid-transactions
- difficulty: Medium

A transaction is possibly invalid if:

*   the amount exceeds `$1000`, or;
*   if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.

You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.

Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**.

**Example 1:**

**Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\]
**Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\]
**Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.

**Example 2:**

**Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\]
**Output:** \[ "alice,50,1200,mtv "\]

**Example 3:**

**Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\]
**Output:** \[ "bob,50,1200,mtv "\]

**Constraints:**

*   `transactions.length <= 1000`
*   Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "`
*   Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`.
*   Each `{time}` consist of digits, and represent an integer between `0` and `1000`.
*   Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.

## A solution in Java

```java
import java.util.*;

class Solution {
    public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {
        List<Item> items = new ArrayList<>();
        for (int i = 0; i < values.length; i++) {
            items.add(new Item(values[i], labels[i]));
        }
        Collections.sort(items, Collections.reverseOrder());

        Map<Integer, Integer> labelCount = new HashMap<>();
        int result = 0;
        for (Item item : items) {
            if (!labelCount.containsKey(item.label)) {
                labelCount.put(item.label, 0);
            }
            if (labelCount.get(item.label) < useLimit && numWanted > 0) {
                result += item.value;
                labelCount.put(item.label, labelCount.get(item.label) + 1);
                numWanted--;
            }
        }

        return result;
    }

    private static class Item implements Comparable<Item> {
        int value;
        int label;

        Item(int value, int label) {
            this.value = value;
            this.label = label;
        }

        @Override
        public int compareTo(Item o) {
            return Integer.compare(this.value, o.value);
        }
    }
}
```
The algorithm first creates a list of tuples/pairs of the given values and labels, then sorts the list in decreasing order based on the value. It initializes an empty dictionary `labelCount` to store the count of chosen items for each label. Then, it iterates through the sorted list of items. If there are still items that can be chosen (`numWanted` > 0) and the current item's label count is less than the `useLimit`, add the current item's value to the result, update the `labelCount` for its label, and decrease the `numWanted`. Finally, return the result as the maximum score.

The function implementations for each language are consistent with the same algorithm approach. They may differ in the syntax and usage of the data structures to accomplish the goal of the algorithm, but they perform similarly overall.

## A solution in C++

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

int largestValsFromLabels(std::vector<int>& values, std::vector<int>& labels, int numWanted, int useLimit) {
    std::vector<std::pair<int, int>> items;
    for (int i = 0; i < values.size(); ++i) {
        items.emplace_back(values[i], labels[i]);
    }
    std::sort(items.rbegin(), items.rend());

    std::unordered_map<int, int> labelCount;
    int result = 0;
    for (const auto& [value, label] : items) {
        if (labelCount[label] < useLimit && numWanted > 0) {
            result += value;
            labelCount[label]++;
            numWanted--;
        }
    }

    return result;
}
```
The algorithm first creates a list of tuples/pairs of the given values and labels, then sorts the list in decreasing order based on the value. It initializes an empty dictionary `labelCount` to store the count of chosen items for each label. Then, it iterates through the sorted list of items. If there are still items that can be chosen (`numWanted` > 0) and the current item's label count is less than the `useLimit`, add the current item's value to the result, update the `labelCount` for its label, and decrease the `numWanted`. Finally, return the result as the maximum score.

The function implementations for each language are consistent with the same algorithm approach. They may differ in the syntax and usage of the data structures to accomplish the goal of the algorithm, but they perform similarly overall.

## A solution in Python

```python
from typing import List

def largestValsFromLabels(values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:
    items = sorted(zip(values, labels), reverse=True)
    label_count = {}
    result = 0

    for value, label in items:
        if numWanted > 0 and label_count.get(label, 0) < useLimit:
            result += value
            label_count[label] = label_count.get(label, 0) + 1
            numWanted -= 1

    return result
```
The algorithm first creates a list of tuples/pairs of the given values and labels, then sorts the list in decreasing order based on the value. It initializes an empty dictionary `labelCount` to store the count of chosen items for each label. Then, it iterates through the sorted list of items. If there are still items that can be chosen (`numWanted` > 0) and the current item's label count is less than the `useLimit`, add the current item's value to the result, update the `labelCount` for its label, and decrease the `numWanted`. Finally, return the result as the maximum score.

The function implementations for each language are consistent with the same algorithm approach. They may differ in the syntax and usage of the data structures to accomplish the goal of the algorithm, but they perform similarly overall.

## A solution in Javascript

```javascript
function largestValsFromLabels(values, labels, numWanted, useLimit) {
    const items = values.map((value, index) => [value, labels[index]]);
    items.sort((a, b) => b[0] - a[0]);

    const labelCount = new Map();
    let result = 0;
    for (const [value, label] of items) {
        if (numWanted > 0 && (!labelCount.has(label) || labelCount.get(label) < useLimit)) {
            result += value;
            labelCount.set(label, (labelCount.get(label) || 0) + 1);
            numWanted--;
        }
    }

    return result;
}
```
The algorithm first creates a list of tuples/pairs of the given values and labels, then sorts the list in decreasing order based on the value. It initializes an empty dictionary `labelCount` to store the count of chosen items for each label. Then, it iterates through the sorted list of items. If there are still items that can be chosen (`numWanted` > 0) and the current item's label count is less than the `useLimit`, add the current item's value to the result, update the `labelCount` for its label, and decrease the `numWanted`. Finally, return the result as the maximum score.

The function implementations for each language are consistent with the same algorithm approach. They may differ in the syntax and usage of the data structures to accomplish the goal of the algorithm, but they perform similarly overall.


# Compare Strings by Frequency of the Smallest Character

- slug: compare-strings-by-frequency-of-the-smallest-character
- difficulty: Medium

Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.

You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`.

Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_.

**Example 1:**

**Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\]
**Output:** \[1\]
**Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz ").

**Example 2:**

**Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\]
**Output:** \[1,2\]
**Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc ").

**Constraints:**

*   `1 <= queries.length <= 2000`
*   `1 <= words.length <= 2000`
*   `1 <= queries[i].length, words[i].length <= 10`
*   `queries[i][j]`, `words[i][j]` consist of lowercase English letters.

## A solution in Java

```java
public class Main {
    public static String shortestCommonSupersequence(String str1, String str2) {
        int m = str1.length();
        int n = str2.length();
        int[][] dp = new int[m + 1][n + 1];

        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0) {
                    dp[i][j] = j;
                } else if (j == 0) {
                    dp[i][j] = i;
                } else if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                    dp[i][j] = 1 + dp[i - 1][j - 1];
                } else {
                    dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }

        int i = m, j = n;
        StringBuilder result = new StringBuilder();

        while (i > 0 && j > 0) {
            if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                result.append(str1.charAt(i - 1));
                i--;
                j--;
            } else if (dp[i - 1][j] > dp[i][j - 1]) {
                j--;
                result.append(str2.charAt(j));
            } else {
                i--;
                result.append(str1.charAt(i));
            }
        }

        while (i > 0) {
            result.append(str1.charAt(i - 1));
            i--;
        }

        while (j > 0) {
            result.append(str2.charAt(j - 1));
            j--;
        }

        return result.reverse().toString();
    }
}
```
We use dynamic programming to find the shortest common supersequence.
1. Create a 2D array `dp` of size `(m+1) x (n+1)` where m and n are the lengths of str1 and str2 respectively. The element dp[i][j] represents the length of the shortest common supersequence for the first i characters of str1 and the first j characters of str2.
2. Initialize the first row and the first column of the 2D array by filling with their respective indices.
3. Iterate through the remaining elements of the 2D array, comparing the characters from str1 and str2. If they're equal, set dp[i][j] to 1 + dp[i-1][j-1]; otherwise, set dp[i][j] to 1 + min(dp[i-1][j], dp[i][j-1]).
4. Traverse the 2D array from the bottom-right corner to the top-left corner, constructing the resulting supersequence in a reversed manner. If str1[i-1] == str2[j-1], include this character in the result, else include the character from the string that has the greater value in the dp array. Move to the previous row or column accordingly.
5. Add the remaining characters from str1 and str2 in the result as needed.
6. Reverse the resulting string before returning (if applicable depending on the language).

## A solution in C++

```cpp
#include <iostream>
#include <vector>

std::string shortest_common_supersequence(std::string str1, std::string str2) {
    int m = str1.length();
    int n = str2.length();
    std::vector<std::vector<int>> dp(m + 1, std::vector<int>(n + 1));

    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0) {
                dp[i][j] = j;
            }
            else if (j == 0) {
                dp[i][j] = i;
            }
            else if (str1[i - 1] == str2[j - 1]) {
                dp[i][j] = 1 + dp[i - 1][j - 1];
            }
            else {
                dp[i][j] = 1 + std::min(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }

    int i = m, j = n;
    std::string result;

    while (i > 0 && j > 0) {
        if (str1[i - 1] == str2[j - 1]) {
            result.push_back(str1[i - 1]);
            i--;
            j--;
        }
        else if (dp[i - 1][j] > dp[i][j - 1]) {
            j--;
            result.push_back(str2[j]);
        }
        else {
            i--;
            result.push_back(str1[i]);
        }
    }

    while (i > 0) {
        result.push_back(str1[i - 1]);
        i--;
    }

    while (j > 0) {
        result.push_back(str2[j - 1]);
        j--;
    }

    std::reverse(result.begin(), result.end());
    return result;
}
```
We use dynamic programming to find the shortest common supersequence.
1. Create a 2D array `dp` of size `(m+1) x (n+1)` where m and n are the lengths of str1 and str2 respectively. The element dp[i][j] represents the length of the shortest common supersequence for the first i characters of str1 and the first j characters of str2.
2. Initialize the first row and the first column of the 2D array by filling with their respective indices.
3. Iterate through the remaining elements of the 2D array, comparing the characters from str1 and str2. If they're equal, set dp[i][j] to 1 + dp[i-1][j-1]; otherwise, set dp[i][j] to 1 + min(dp[i-1][j], dp[i][j-1]).
4. Traverse the 2D array from the bottom-right corner to the top-left corner, constructing the resulting supersequence in a reversed manner. If str1[i-1] == str2[j-1], include this character in the result, else include the character from the string that has the greater value in the dp array. Move to the previous row or column accordingly.
5. Add the remaining characters from str1 and str2 in the result as needed.
6. Reverse the resulting string before returning (if applicable depending on the language).

## A solution in Python

```python
def shortest_common_supersequence(str1, str2):
    m, n = len(str1), len(str2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(m + 1):
        for j in range(n + 1):
            if i == 0:
                dp[i][j] = j
            elif j == 0:
                dp[i][j] = i
            elif str1[i - 1] == str2[j - 1]:
                dp[i][j] = 1 + dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1])

    i, j = m, n
    result = []

    while i > 0 and j > 0:
        if str1[i - 1] == str2[j - 1]:
            result.append(str1[i - 1])
            i -= 1
            j -= 1
        elif dp[i - 1][j] > dp[i][j - 1]:
            j -= 1
            result.append(str2[j])
        else:
            i -= 1
            result.append(str1[i])

    while i > 0:
        i -= 1
        result.append(str1[i])

    while j > 0:
        j -= 1
        result.append(str2[j])

    return "".join(result[::-1])
```
We use dynamic programming to find the shortest common supersequence.
1. Create a 2D array `dp` of size `(m+1) x (n+1)` where m and n are the lengths of str1 and str2 respectively. The element dp[i][j] represents the length of the shortest common supersequence for the first i characters of str1 and the first j characters of str2.
2. Initialize the first row and the first column of the 2D array by filling with their respective indices.
3. Iterate through the remaining elements of the 2D array, comparing the characters from str1 and str2. If they're equal, set dp[i][j] to 1 + dp[i-1][j-1]; otherwise, set dp[i][j] to 1 + min(dp[i-1][j], dp[i][j-1]).
4. Traverse the 2D array from the bottom-right corner to the top-left corner, constructing the resulting supersequence in a reversed manner. If str1[i-1] == str2[j-1], include this character in the result, else include the character from the string that has the greater value in the dp array. Move to the previous row or column accordingly.
5. Add the remaining characters from str1 and str2 in the result as needed.
6. Reverse the resulting string before returning (if applicable depending on the language).

## A solution in Javascript

```javascript
function shortestCommonSupersequence(str1, str2) {
    const m = str1.length;
    const n = str2.length;
    const dp = Array.from({length: m + 1}, () => Array(n + 1).fill(0));

    for (let i = 0; i <= m; i++) {
        for (let j = 0; j <= n; j++) {
            if (i === 0) {
                dp[i][j] = j;
            } else if (j === 0) {
                dp[i][j] = i;
            } else if (str1[i - 1] === str2[j - 1]) {
                dp[i][j] = 1 + dp[i - 1][j - 1];
            } else {
                dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }

    let i = m, j = n;
    let result = "";

    while (i > 0 && j > 0) {
        if (str1[i - 1] === str2[j - 1]) {
            result = str1[i - 1] + result;
            i--;
            j--;
        } else if (dp[i - 1][j] > dp[i][j - 1]) {
            j--;
            result = str2[j] + result;
        } else {
            i--;
            result = str1[i] + result;
        }
    }

    while (i > 0) {
        i--;
        result = str1[i] + result;
    }

    while (j > 0) {
        j--;
        result = str2[j] + result;
    }

    return result;
}
```
We use dynamic programming to find the shortest common supersequence.
1. Create a 2D array `dp` of size `(m+1) x (n+1)` where m and n are the lengths of str1 and str2 respectively. The element dp[i][j] represents the length of the shortest common supersequence for the first i characters of str1 and the first j characters of str2.
2. Initialize the first row and the first column of the 2D array by filling with their respective indices.
3. Iterate through the remaining elements of the 2D array, comparing the characters from str1 and str2. If they're equal, set dp[i][j] to 1 + dp[i-1][j-1]; otherwise, set dp[i][j] to 1 + min(dp[i-1][j], dp[i][j-1]).
4. Traverse the 2D array from the bottom-right corner to the top-left corner, constructing the resulting supersequence in a reversed manner. If str1[i-1] == str2[j-1], include this character in the result, else include the character from the string that has the greater value in the dp array. Move to the previous row or column accordingly.
5. Add the remaining characters from str1 and str2 in the result as needed.
6. Reverse the resulting string before returning (if applicable depending on the language).


# Remove Zero Sum Consecutive Nodes from Linked List

- slug: remove-zero-sum-consecutive-nodes-from-linked-list
- difficulty: Medium

Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.

After doing so, return the head of the final linked list. You may return any such answer.

(Note that in the examples below, all sequences are serializations of `ListNode` objects.)

**Example 1:**

**Input:** head = \[1,2,-3,3,1\]
**Output:** \[3,1\]
**Note:** The answer \[1,2,1\] would also be accepted.

**Example 2:**

**Input:** head = \[1,2,3,-3,4\]
**Output:** \[1,2,4\]

**Example 3:**

**Input:** head = \[1,2,3,-3,-2\]
**Output:** \[1\]

**Constraints:**

*   The given linked list will contain between `1` and `1000` nodes.
*   Each node in the linked list has `-1000 <= node.val <= 1000`.

## A solution in Java

```java
import java.util.*;

public int shortestPathBinaryMatrix(int[][] grid) {
    int n = grid.length;
    if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
    Queue<int[]> q = new LinkedList<>();
    int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
    q.offer(new int[]{0, 0});
    grid[0][0] = 1;
    int steps = 1;

    while (!q.isEmpty()) {
        int size = q.size();
        for (int i = 0; i < size; ++i) {
            int[] cell = q.poll();
            int x = cell[0];
            int y = cell[1];

            if (x == n - 1 && y == n - 1) return steps;

            for (int[] dir : dirs) {
                int newX = x + dir[0];
                int newY = y + dir[1];

                if (newX >= 0 && newX < n && newY >= 0 && newY < n && grid[newX][newY] == 0) {
                    q.offer(new int[]{newX, newY});
                    grid[newX][newY] = 1;
                }
            }
        }
        steps++;
    }

    return -1;
}
```
1. Check if start or end cell is blocked (has value 1), if yes return -1.
2. Initialize a queue and add the start cell (0, 0) to it along with initializing the step counter to 1.
3. Define all 8 directions in the form of row, column offsets in a matrix (`dirs`).
4. While the queue is not empty, process the current level of cells as follows:
   - For each cell, if it is the bottom-right cell (n-1, n-1), return the current step counter.
   - For each possible direction from the current cell, calculate the new cell coordinates.
   - If the new cell is within the matrix bounds and has a value of 0, add it to the queue and set its value to 1 (i.e., mark it as visited).
   - After processing all cells, increment the step counter by 1.
5. If the algorithm exits the loop, no clear path is found, and return -1.

## A solution in C++

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

using namespace std;

int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
    int n = grid.size();
    if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
    queue<pair<int, int>> q;
    vector<vector<int>> dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
    q.push({0, 0});
    grid[0][0] = 1;
    int steps = 1;

    while (!q.empty()) {
        int size = q.size();
        for (int i = 0; i < size; ++i) {
            int x = q.front().first;
            int y = q.front().second;
            q.pop();

            if (x == n - 1 && y == n - 1) return steps;

            for (vector<int> dir : dirs) {
                int newX = x + dir[0];
                int newY = y + dir[1];

                if (newX >= 0 && newX < n && newY >= 0 && newY < n && grid[newX][newY] == 0) {
                    q.push({newX, newY});
                    grid[newX][newY] = 1;
                }
            }
        }
        steps++;
    }

    return -1;
}
```
1. Check if start or end cell is blocked (has value 1), if yes return -1.
2. Initialize a queue and add the start cell (0, 0) to it along with initializing the step counter to 1.
3. Define all 8 directions in the form of row, column offsets in a matrix (`dirs`).
4. While the queue is not empty, process the current level of cells as follows:
   - For each cell, if it is the bottom-right cell (n-1, n-1), return the current step counter.
   - For each possible direction from the current cell, calculate the new cell coordinates.
   - If the new cell is within the matrix bounds and has a value of 0, add it to the queue and set its value to 1 (i.e., mark it as visited).
   - After processing all cells, increment the step counter by 1.
5. If the algorithm exits the loop, no clear path is found, and return -1.

## A solution in Python

```python
from collections import deque

def shortestPathBinaryMatrix(grid):
    n = len(grid)
    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:
        return -1
    q = deque([(0, 0)])
    dirs = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
    grid[0][0] = 1
    steps = 1

    while q:
        size = len(q)
        for _ in range(size):
            x, y = q.popleft()

            if x == n - 1 and y == n - 1:
                return steps

            for dx, dy in dirs:
                newX, newY = x + dx, y + dy

                if 0 <= newX < n and 0 <= newY < n and grid[newX][newY] == 0:
                    q.append((newX, newY))
                    grid[newX][newY] = 1

        steps += 1

    return -1
```
1. Check if start or end cell is blocked (has value 1), if yes return -1.
2. Initialize a queue and add the start cell (0, 0) to it along with initializing the step counter to 1.
3. Define all 8 directions in the form of row, column offsets in a matrix (`dirs`).
4. While the queue is not empty, process the current level of cells as follows:
   - For each cell, if it is the bottom-right cell (n-1, n-1), return the current step counter.
   - For each possible direction from the current cell, calculate the new cell coordinates.
   - If the new cell is within the matrix bounds and has a value of 0, add it to the queue and set its value to 1 (i.e., mark it as visited).
   - After processing all cells, increment the step counter by 1.
5. If the algorithm exits the loop, no clear path is found, and return -1.

## A solution in Javascript

```javascript
function shortestPathBinaryMatrix(grid) {
    const n = grid.length;
    if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
    const q = [[0, 0]];
    const dirs = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
    grid[0][0] = 1;
    let steps = 1;

    while (q.length !== 0) {
        const size = q.length;
        for (let i = 0; i < size; ++i) {
            const [x, y] = q.shift();

            if (x === n - 1 && y === n - 1) return steps;

            for (const [dx, dy] of dirs) {
                const newX = x + dx;
                const newY = y + dy;

                if (newX >= 0 && newX < n && newY >= 0 && newY < n && grid[newX][newY] === 0) {
                    q.push([newX, newY]);
                    grid[newX][newY] = 1;
                }
            }
        }
        steps++;
    }

    return -1;
}
```
1. Check if start or end cell is blocked (has value 1), if yes return -1.
2. Initialize a queue and add the start cell (0, 0) to it along with initializing the step counter to 1.
3. Define all 8 directions in the form of row, column offsets in a matrix (`dirs`).
4. While the queue is not empty, process the current level of cells as follows:
   - For each cell, if it is the bottom-right cell (n-1, n-1), return the current step counter.
   - For each possible direction from the current cell, calculate the new cell coordinates.
   - If the new cell is within the matrix bounds and has a value of 0, add it to the queue and set its value to 1 (i.e., mark it as visited).
   - After processing all cells, increment the step counter by 1.
5. If the algorithm exits the loop, no clear path is found, and return -1.


# Dinner Plate Stacks

- slug: dinner-plate-stacks
- difficulty: Hard

You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity.

Implement the `DinnerPlates` class:

*   `DinnerPlates(int capacity)` Initializes the object with the maximum capacity of the stacks `capacity`.
*   `void push(int val)` Pushes the given integer `val` into the leftmost stack with a size less than `capacity`.
*   `int pop()` Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns `-1` if all the stacks are empty.
*   `int popAtStack(int index)` Returns the value at the top of the stack with the given index `index` and removes it from that stack or returns `-1` if the stack with that given index is empty.

**Example 1:**

**Input**
\[ "DinnerPlates ",  "push ",  "push ",  "push ",  "push ",  "push ",  "popAtStack ",  "push ",  "push ",  "popAtStack ",  "popAtStack ",  "pop ",  "pop ",  "pop ",  "pop ",  "pop "\]
\[\[2\], \[1\], \[2\], \[3\], \[4\], \[5\], \[0\], \[20\], \[21\], \[0\], \[2\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1\]

**Explanation:**
DinnerPlates D = DinnerPlates(2);  // Initialize with capacity = 2
D.push(1);
D.push(2);
D.push(3);
D.push(4);
D.push(5);         // The stacks are now:  2  4
                                           1  3  5
                                           ﹈ ﹈ ﹈
D.popAtStack(0);   // Returns 2.  The stacks are now:     4
                                                       1  3  5
                                                       ﹈ ﹈ ﹈
D.push(20);        // The stacks are now: 20  4
                                           1  3  5
                                           ﹈ ﹈ ﹈
D.push(21);        // The stacks are now: 20  4 21
                                           1  3  5
                                           ﹈ ﹈ ﹈
D.popAtStack(0);   // Returns 20.  The stacks are now:     4 21
                                                        1  3  5
                                                        ﹈ ﹈ ﹈
D.popAtStack(2);   // Returns 21.  The stacks are now:     4
                                                        1  3  5
                                                        ﹈ ﹈ ﹈
D.pop()            // Returns 5.  The stacks are now:      4
                                                        1  3
                                                        ﹈ ﹈
D.pop()            // Returns 4.  The stacks are now:   1  3
                                                        ﹈ ﹈
D.pop()            // Returns 3.  The stacks are now:   1
                                                        ﹈
D.pop()            // Returns 1.  There are no stacks.
D.pop()            // Returns -1.  There are still no stacks.

**Constraints:**

*   `1 <= capacity <= 2 * 104`
*   `1 <= val <= 2 * 104`
*   `0 <= index <= 105`
*   At most `2 * 105` calls will be made to `push`, `pop`, and `popAtStack`.

## A solution in Java

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

class DinnerPlates {
    int capacity;
    List<List<Integer>> stacks;

    public DinnerPlates(int capacity) {
        this.capacity = capacity;
        stacks = new ArrayList<>();
    }

    public void push(int val) {
        for (List<Integer> stack : stacks) {
            if (stack.size() < capacity) {
                stack.add(val);
                return;
            }
        }
        stacks.add(new ArrayList<>(List.of(val)));
    }

    public int pop() {
        while (!stacks.isEmpty() && stacks.get(stacks.size() - 1).isEmpty()) {
            stacks.remove(stacks.size() - 1);
        }
        if (stacks.isEmpty()) return -1;
        List<Integer> lastStack = stacks.get(stacks.size() - 1);
        int result = lastStack.get(lastStack.size() - 1);
        lastStack.remove(lastStack.size() - 1);
        return result;
    }

    public int popAtStack(int index) {
        if (index >= stacks.size() || stacks.get(index).isEmpty()) {
            return -1;
        }
        List<Integer> stack = stacks.get(index);
        int result = stack.get(stack.size() - 1);
        stack.remove(stack.size() - 1);
        return result;
    }
}
```
The algorithm uses a 2D array named "stacks", where each inner array represents a stack. Initially, "stacks" is empty. When "push" is called, it checks for the first stack where the size is smaller than capacity and pushes the value to that stack. If none are found, create a new stack with the value.

To perform "pop", we first check and remove any empty stacks from the right of our "stacks" array, then perform the pop operation on the right-most stack if it exists, or return -1 if there are no stacks.

In the "popAtStack" function, it checks if the given index exists and if the stack at that index is not empty. If so, return the popped value from that stack, otherwise, return -1.

## A solution in C++

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

class DinnerPlates {
public:
    int capacity;
    vector<vector<int>> stacks;

    DinnerPlates(int capacity) {
        this->capacity = capacity;
    }

    void push(int val) {
        for (auto &s : stacks) {
            if (s.size() < capacity) {
                s.push_back(val);
                return;
            }
        }
        stacks.push_back({val});
    }

    int pop() {
        while (!stacks.empty() && stacks.back().empty()) {
            stacks.pop_back();
        }
        if (stacks.empty()) return -1;
        int result = stacks.back().back();
        stacks.back().pop_back();
        return result;
    }

    int popAtStack(int index) {
        if (index >= stacks.size() || stacks[index].empty()) {
            return -1;
        }
        int result = stacks[index].back();
        stacks[index].pop_back();
        return result;
    }
};
```
The algorithm uses a 2D array named "stacks", where each inner array represents a stack. Initially, "stacks" is empty. When "push" is called, it checks for the first stack where the size is smaller than capacity and pushes the value to that stack. If none are found, create a new stack with the value.

To perform "pop", we first check and remove any empty stacks from the right of our "stacks" array, then perform the pop operation on the right-most stack if it exists, or return -1 if there are no stacks.

In the "popAtStack" function, it checks if the given index exists and if the stack at that index is not empty. If so, return the popped value from that stack, otherwise, return -1.

## A solution in Python

```python
class DinnerPlates:

    def __init__(self, capacity: int):
        self.capacity = capacity
        self.stacks = []

    def push(self, val: int) -> None:
        for stack in self.stacks:
            if len(stack) < self.capacity:
                stack.append(val)
                return
        self.stacks.append([val])

    def pop(self) -> int:
        while self.stacks and not self.stacks[-1]:
            self.stacks.pop()
        if not self.stacks:
            return -1
        return self.stacks[-1].pop()

    def popAtStack(self, index: int) -> int:
        if index >= len(self.stacks) or not self.stacks[index]:
            return -1
        return self.stacks[index].pop()
```
The algorithm uses a 2D array named "stacks", where each inner array represents a stack. Initially, "stacks" is empty. When "push" is called, it checks for the first stack where the size is smaller than capacity and pushes the value to that stack. If none are found, create a new stack with the value.

To perform "pop", we first check and remove any empty stacks from the right of our "stacks" array, then perform the pop operation on the right-most stack if it exists, or return -1 if there are no stacks.

In the "popAtStack" function, it checks if the given index exists and if the stack at that index is not empty. If so, return the popped value from that stack, otherwise, return -1.

## A solution in Javascript

```javascript
class DinnerPlates {
    constructor(capacity) {
        this.capacity = capacity;
        this.stacks = [];
    }

    push(val) {
        for (const stack of this.stacks) {
            if (stack.length < this.capacity) {
                stack.push(val);
                return;
            }
        }
        this.stacks.push([val]);
    }

    pop() {
        while (this.stacks.length && !this.stacks[this.stacks.length - 1].length) {
            this.stacks.pop();
        }
        if (!this.stacks.length) return -1;
        return this.stacks[this.stacks.length - 1].pop();
    }

    popAtStack(index) {
        if (index >= this.stacks.length || !this.stacks[index].length) {
            return -1;
        }
        return this.stacks[index].pop();
    }
}
```
The algorithm uses a 2D array named "stacks", where each inner array represents a stack. Initially, "stacks" is empty. When "push" is called, it checks for the first stack where the size is smaller than capacity and pushes the value to that stack. If none are found, create a new stack with the value.

To perform "pop", we first check and remove any empty stacks from the right of our "stacks" array, then perform the pop operation on the right-most stack if it exists, or return -1 if there are no stacks.

In the "popAtStack" function, it checks if the given index exists and if the stack at that index is not empty. If so, return the popped value from that stack, otherwise, return -1.


# Prime Arrangements

- slug: prime-arrangements
- difficulty: Easy

Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)

_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_

Since the answer may be large, return the answer **modulo `10^9 + 7`**.

**Example 1:**

**Input:** n = 5
**Output:** 12
**Explanation:** For example \[1,2,5,4,3\] is a valid permutation, but \[5,2,3,4,1\] is not because the prime number 5 is at index 1.

**Example 2:**

**Input:** n = 100
**Output:** 682289015

**Constraints:**

*   `1 <= n <= 100`

## A solution in Java

```java
public int numPrimeArrangements(int n) {
    boolean[] isPrime = new boolean[n + 1];
    Arrays.fill(isPrime, true);
    isPrime[0] = false;
    isPrime[1] = false;
    for (int i = 2; i * i <= n; i++) {
        if (isPrime[i]) {
            for (int j = i * i; j <= n; j += i) {
                isPrime[j] = false;
            }
        }
    }

    int primeCount = 0;
    for (int i = 2; i <= n; i++) {
        if (isPrime[i]) primeCount++;
    }
    int compositeCount = n - primeCount;

    long res = 1;
    int MOD = 1000000007;
    for (int i = 1; i <= primeCount; i++) {
        res = res * i % MOD;
    }
    for (int i = 1; i <= compositeCount; i++) {
        res = res * i % MOD;
    }
    return (int) res;
}
```
The algorithm calculates the total number of primes and composites up to the given integer n. Then, it multiplies the factorials of the two counts (mod 10^9 + 7), eventually returning the result as the number of permutations of 1 to n where prime numbers are at the prime indices.

## A solution in C++

```cpp
#include <vector>
using namespace std;
const int MOD = 1e9 + 7;

int numPrimeArrangements(int n) {
    vector<bool> is_prime(n + 1, true);
    is_prime[0] = false;
    is_prime[1] = false;
    for (int i = 2; i * i <= n; i++) {
        if (is_prime[i]) {
            for (int j = i * i; j <= n; j += i) {
                is_prime[j] = false;
            }
        }
    }

    int prime_count = 0;
    for (int i = 2; i <= n; i++) {
        if (is_prime[i]) prime_count++;
    }
    int composite_count = n - prime_count;

    long long res = 1;
    for (int i = 1; i <= prime_count; i++) {
        res = res * i % MOD;
    }
    for (int i = 1; i <= composite_count; i++) {
        res = res * i % MOD;
    }
    return res;
}
```
The algorithm calculates the total number of primes and composites up to the given integer n. Then, it multiplies the factorials of the two counts (mod 10^9 + 7), eventually returning the result as the number of permutations of 1 to n where prime numbers are at the prime indices.

## A solution in Python

```python
def numPrimeArrangements(n: int) -> int:
    def is_prime(num):
        if num < 2:
            return False
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                return False
        return True

    prime_count = sum(1 for i in range(2, n + 1) if is_prime(i))
    composite_count = n - prime_count

    MOD = 10**9 + 7
    res = 1
    for i in range(1, prime_count + 1):
        res = res * i % MOD
    for i in range(1, composite_count + 1):
        res = res * i % MOD

    return res
```
The algorithm calculates the total number of primes and composites up to the given integer n. Then, it multiplies the factorials of the two counts (mod 10^9 + 7), eventually returning the result as the number of permutations of 1 to n where prime numbers are at the prime indices.

## A solution in Javascript

```javascript
function numPrimeArrangements(n) {
    function isPrime(num) {
        if (num < 2) return false;
        for (let i = 2; i * i <= num; i++) {
            if (num % i === 0) return false;
        }
        return true;
    }

    let primeCount = 0;
    for (let i = 2; i <= n; i++) {
        if (isPrime(i)) primeCount++;
    }
    let compositeCount = n - primeCount;

    const MOD = 10**9 + 7;
    let res = 1;
    for (let i = 1; i <= primeCount; i++) {
        res = res * i % MOD;
    }
    for (let i = 1; i <= compositeCount; i++) {
        res = res * i % MOD;
    }

    return res;
}
```
The algorithm calculates the total number of primes and composites up to the given integer n. Then, it multiplies the factorials of the two counts (mod 10^9 + 7), eventually returning the result as the number of permutations of 1 to n where prime numbers are at the prime indices.


# Diet Plan Performance

- slug: diet-plan-performance
- difficulty: Easy

A dieter consumes `calories[i]` calories on the `i`\-th day.

Given an integer `k`, for **every** consecutive sequence of `k` days (`calories[i], calories[i+1], ..., calories[i+k-1]` for all `0 <= i <= n-k`), they look at _T_, the total calories consumed during that sequence of `k` days (`calories[i] + calories[i+1] + ... + calories[i+k-1]`):

*   If `T < lower`, they performed poorly on their diet and lose 1 point;
*   If `T > upper`, they performed well on their diet and gain 1 point;
*   Otherwise, they performed normally and there is no change in points.

Initially, the dieter has zero points. Return the total number of points the dieter has after dieting for `calories.length` days.

Note that the total points can be negative.

**Example 1:**

**Input:** calories = \[1,2,3,4,5\], k = 1, lower = 3, upper = 3
**Output:** 0
**Explanation**: Since k = 1, we consider each element of the array separately and compare it to lower and upper.
calories\[0\] and calories\[1\] are less than lower so 2 points are lost.
calories\[3\] and calories\[4\] are greater than upper so 2 points are gained.

**Example 2:**

**Input:** calories = \[3,2\], k = 2, lower = 0, upper = 1
**Output:** 1
**Explanation**: Since k = 2, we consider subarrays of length 2.
calories\[0\] + calories\[1\] > upper so 1 point is gained.

**Example 3:**

**Input:** calories = \[6,5,0,0\], k = 2, lower = 1, upper = 5
**Output:** 0
**Explanation**:
calories\[0\] + calories\[1\] > upper so 1 point is gained.
lower <= calories\[1\] + calories\[2\] <= upper so no change in points.
calories\[2\] + calories\[3\] < lower so 1 point is lost.

**Constraints:**

*   `1 <= k <= calories.length <= 10^5`
*   `0 <= calories[i] <= 20000`
*   `0 <= lower <= upper`

## A solution in Java

```java
public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
    int points = 0;
    int T = 0;

    for(int i = 0; i < calories.length; i++) {
        T += calories[i];
        if(i >= k) {
            T -= calories[i-k];
        }
        if(i >= k-1) {
            if(T < lower) points--;
            if(T > upper) points++;
        }
    }

    return points;
}
```
1. Initialize the points and total calories `T` to 0.
2. Iterate through the given calories list.
3. Add the current day calories to `T`.
4. Check if the current index position is greater than or equal to `k`. If so, subtract the calories of the first day of the previous window from `T`.
5. Check if we have formed a window of size `k`. If so, perform the point calculation:
   1. If `T` is less than `lower`, decrement the points.
   2. If `T` is greater than `upper`, increment the points.
6. Return the total number of points.

## A solution in C++

```cpp
int dietPlanPerformance(vector<int>& calories, int k, int lower, int upper) {
    int points = 0;
    int T = 0;

    for(int i = 0; i < calories.size(); i++) {
        T += calories[i];
        if(i >= k) {
            T -= calories[i-k];
        }
        if(i >= k-1) {
            if(T < lower) points--;
            if(T > upper) points++;
        }
    }

    return points;
}
```
1. Initialize the points and total calories `T` to 0.
2. Iterate through the given calories list.
3. Add the current day calories to `T`.
4. Check if the current index position is greater than or equal to `k`. If so, subtract the calories of the first day of the previous window from `T`.
5. Check if we have formed a window of size `k`. If so, perform the point calculation:
   1. If `T` is less than `lower`, decrement the points.
   2. If `T` is greater than `upper`, increment the points.
6. Return the total number of points.

## A solution in Python

```python
def dietPlanPerformance(calories, k, lower, upper):
    points = 0
    T = 0

    for i in range(len(calories)):
        T += calories[i]
        if i >= k:
            T -= calories[i-k]
        if i >= k-1:
            if T < lower: points -= 1
            if T > upper: points += 1

    return points
```
1. Initialize the points and total calories `T` to 0.
2. Iterate through the given calories list.
3. Add the current day calories to `T`.
4. Check if the current index position is greater than or equal to `k`. If so, subtract the calories of the first day of the previous window from `T`.
5. Check if we have formed a window of size `k`. If so, perform the point calculation:
   1. If `T` is less than `lower`, decrement the points.
   2. If `T` is greater than `upper`, increment the points.
6. Return the total number of points.

## A solution in Javascript

```javascript
function dietPlanPerformance(calories, k, lower, upper) {
    let points = 0;
    let T = 0;

    for(let i = 0; i < calories.length; i++) {
        T += calories[i];
        if(i >= k) {
            T -= calories[i-k];
        }
        if(i >= k-1) {
            if(T < lower) points--;
            if(T > upper) points++;
        }
    }

    return points;
}
```
1. Initialize the points and total calories `T` to 0.
2. Iterate through the given calories list.
3. Add the current day calories to `T`.
4. Check if the current index position is greater than or equal to `k`. If so, subtract the calories of the first day of the previous window from `T`.
5. Check if we have formed a window of size `k`. If so, perform the point calculation:
   1. If `T` is less than `lower`, decrement the points.
   2. If `T` is greater than `upper`, increment the points.
6. Return the total number of points.


# Can Make Palindrome from Substring

- slug: can-make-palindrome-from-substring
- difficulty: Medium

You are given a string `s` and array `queries` where `queries[i] = [lefti, righti, ki]`. We may rearrange the substring `s[lefti...righti]` for each query and then choose up to `ki` of them to replace with any lowercase English letter.

If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`. Otherwise, the result is `false`.

Return a boolean array `answer` where `answer[i]` is the result of the `ith` query `queries[i]`.

Note that each letter is counted individually for replacement, so if, for example `s[lefti...righti] = "aaa "`, and `ki = 2`, we can only replace two of the letters. Also, note that no query modifies the initial string `s`.

**Example :**

**Input:** s =  "abcda ", queries = \[\[3,3,0\],\[1,2,0\],\[0,3,1\],\[0,3,2\],\[0,4,1\]\]
**Output:** \[true,false,false,true,true\]
**Explanation:**
queries\[0\]: substring =  "d ", is palidrome.
queries\[1\]: substring =  "bc ", is not palidrome.
queries\[2\]: substring =  "abcd ", is not palidrome after replacing only 1 character.
queries\[3\]: substring =  "abcd ", could be changed to  "abba " which is palidrome. Also this can be changed to  "baab " first rearrange it  "bacd " then replace  "cd " with  "ab ".
queries\[4\]: substring =  "abcda ", could be changed to  "abcba " which is palidrome.

**Example 2:**

**Input:** s =  "lyb ", queries = \[\[0,1,0\],\[2,2,1\]\]
**Output:** \[false,true\]

**Constraints:**

*   `1 <= s.length, queries.length <= 105`
*   `0 <= lefti <= righti < s.length`
*   `0 <= ki <= s.length`
*   `s` consists of lowercase English letters.

## A solution in Java

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

public List<Boolean> canMakePaliQueries(String s, int[][] queries) {
    List<Boolean> answer = new ArrayList<>();
    int[] prefixSum = new int[s.length() + 1];

    for (int i = 0; i < s.length(); ++i) {
        prefixSum[i + 1] = prefixSum[i] ^ (1 << (s.charAt(i) - 'a'));
    }

    for (int[] query : queries) {
        int left = query[0], right = query[1], k = query[2];
        int diffCount = Integer.bitCount(prefixSum[right + 1] ^ prefixSum[left]);
        answer.add((diffCount / 2) <= k);
    }

    return answer;
}
```
For each query, we want to know how many different characters we have in our substring. We can do this using a bitwise XOR operation, where each change of character will change a bit value in our integer value.

We then create a prefixSum array. The prefixSum array is a collection of integers at each index representing the appearance of characters from index `0` to `i` in the string `s`.

For each query, we find the difference between the prefixSum of right+1 and left (using the XOR) to get the appearance of characters between the left and right indices. Then using popcount (or equivalent) to count the number of set bits to get the count of different characters in the substring.

Finally, we divide the different characters by 2 to get the number of characters we need to change to make it a palindrome. If this value is less than or equal to `k` provided in the query, then it's possible, and we push `true` to the answer array. Otherwise, we push `false`.

Note : In python, `bin(number).count('1')` is an alternative to having popcount function.

## A solution in C++

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

std::vector<bool> canMakePaliQueries(std::string s, std::vector<std::vector<int>>& queries) {
    std::vector<bool> answer;
    std::vector<int> prefixSum(s.length() + 1);

    for (int i = 0; i < s.length(); ++i) {
        prefixSum[i + 1] = prefixSum[i] ^ (1 << (s[i] - 'a'));
    }

    for (auto &query : queries) {
        int left = query[0], right = query[1], k = query[2];
        int diffCount = __builtin_popcount(prefixSum[right + 1] ^ prefixSum[left]);
        answer.push_back((diffCount / 2) <= k);
    }

    return answer;
}
```
For each query, we want to know how many different characters we have in our substring. We can do this using a bitwise XOR operation, where each change of character will change a bit value in our integer value.

We then create a prefixSum array. The prefixSum array is a collection of integers at each index representing the appearance of characters from index `0` to `i` in the string `s`.

For each query, we find the difference between the prefixSum of right+1 and left (using the XOR) to get the appearance of characters between the left and right indices. Then using popcount (or equivalent) to count the number of set bits to get the count of different characters in the substring.

Finally, we divide the different characters by 2 to get the number of characters we need to change to make it a palindrome. If this value is less than or equal to `k` provided in the query, then it's possible, and we push `true` to the answer array. Otherwise, we push `false`.

Note : In python, `bin(number).count('1')` is an alternative to having popcount function.

## A solution in Python

```python
def canMakePaliQueries(s, queries):
    answer = []
    prefixSum = [0] * (len(s) + 1)

    for i in range(len(s)):
        prefixSum[i + 1] = prefixSum[i] ^ (1 << (ord(s[i]) - ord('a')))

    for query in queries:
        left, right, k = query
        diffCount = bin(prefixSum[right + 1] ^ prefixSum[left]).count('1')
        answer.append((diffCount // 2) <= k)

    return answer
```
For each query, we want to know how many different characters we have in our substring. We can do this using a bitwise XOR operation, where each change of character will change a bit value in our integer value.

We then create a prefixSum array. The prefixSum array is a collection of integers at each index representing the appearance of characters from index `0` to `i` in the string `s`.

For each query, we find the difference between the prefixSum of right+1 and left (using the XOR) to get the appearance of characters between the left and right indices. Then using popcount (or equivalent) to count the number of set bits to get the count of different characters in the substring.

Finally, we divide the different characters by 2 to get the number of characters we need to change to make it a palindrome. If this value is less than or equal to `k` provided in the query, then it's possible, and we push `true` to the answer array. Otherwise, we push `false`.

Note : In python, `bin(number).count('1')` is an alternative to having popcount function.

## A solution in Javascript

```javascript
function canMakePaliQueries(s, queries) {
    const answer = [];
    const prefixSum = new Array(s.length + 1).fill(0);

    for (let i = 0; i < s.length; ++i) {
        prefixSum[i + 1] = prefixSum[i] ^ (1 << (s.charCodeAt(i) - 'a'.charCodeAt(0)));
    }

    for (const query of queries) {
        const left = query[0], right = query[1], k = query[2];
        const diffCount = (prefixSum[right + 1] ^ prefixSum[left]).toString(2).split('0').length - 1;
        answer.push((diffCount / 2) <= k);
    }

    return answer;
}
```
For each query, we want to know how many different characters we have in our substring. We can do this using a bitwise XOR operation, where each change of character will change a bit value in our integer value.

We then create a prefixSum array. The prefixSum array is a collection of integers at each index representing the appearance of characters from index `0` to `i` in the string `s`.

For each query, we find the difference between the prefixSum of right+1 and left (using the XOR) to get the appearance of characters between the left and right indices. Then using popcount (or equivalent) to count the number of set bits to get the count of different characters in the substring.

Finally, we divide the different characters by 2 to get the number of characters we need to change to make it a palindrome. If this value is less than or equal to `k` provided in the query, then it's possible, and we push `true` to the answer array. Otherwise, we push `false`.

Note : In python, `bin(number).count('1')` is an alternative to having popcount function.


# Number of Valid Words for Each Puzzle

- slug: number-of-valid-words-for-each-puzzle
- difficulty: Hard

With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied:

*   `word` contains the first letter of `puzzle`.
*   For each letter in `word`, that letter is in `puzzle`.
    *   For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while
    *   invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle).

Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`.

**Example 1:**

**Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\]
**Output:** \[1,1,3,2,4,0\]
**Explanation:**
1 valid word for  "aboveyz " :  "aaaa "
1 valid word for  "abrodyz " :  "aaaa "
3 valid words for  "abslute " :  "aaaa ",  "asas ",  "able "
2 valid words for  "absoryz " :  "aaaa ",  "asas "
4 valid words for  "actresz " :  "aaaa ",  "asas ",  "actt ",  "access "
There are no valid words for  "gaswxyz " cause none of the words in the list contains letter 'g'.

**Example 2:**

**Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\]
**Output:** \[0,1,3,2,0\]

**Constraints:**

*   `1 <= words.length <= 105`
*   `4 <= words[i].length <= 50`
*   `1 <= puzzles.length <= 104`
*   `puzzles[i].length == 7`
*   `words[i]` and `puzzles[i]` consist of lowercase English letters.
*   Each `puzzles[i]` does not contain repeated characters.

## A solution in Java

```java
import java.util.*;

public List<Integer> findNumOfValidWords(String[] words, String[] puzzles) {
    List<Integer> result = new ArrayList<>();
    for (String puzzle : puzzles) {
        int count = 0;
        Set<Character> puzzleSet = new HashSet<>();
        for (char c : puzzle.toCharArray()) {
            puzzleSet.add(c);
        }
        for (String word : words) {
            if (word.indexOf(puzzle.charAt(0)) >= 0) {
                if (word.chars().allMatch(c -> puzzleSet.contains((char) c))) {
                    count++;
                }
            }
        }
        result.add(count);
    }
    return result;
}
```
We iterate through each puzzle in the given puzzles array. Then, we create a set containing all the unique characters of the current puzzle, which will be used later for checking if a word is valid with respect to the puzzle. Afterward, for each word in the words array, we check if the first letter of the puzzle is in this word. If it is, we check if all the characters in the word are present in the puzzle set. If they are, we increment the count of the valid words for the current puzzle. Finally, we append the count to our result list and move on to the next puzzle. We do this for all the puzzles, and the result list is returned.

## A solution in C++

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

std::vector<int> findNumOfValidWords(std::vector<std::string>& words, std::vector<std::string>& puzzles) {
    std::vector<int> result;
    for (const std::string& puzzle : puzzles) {
        int count = 0;
        std::unordered_set<char> puzzleSet(puzzle.begin(), puzzle.end());
        for (const std::string& word : words) {
            if (word.find(puzzle[0]) != std::string::npos) {
                if (std::all_of(word.begin(), word.end(), [&](char c) { return puzzleSet.count(c) > 0; })) {
                    count++;
                }
            }
        }
        result.push_back(count);
    }
    return result;
}
```
We iterate through each puzzle in the given puzzles array. Then, we create a set containing all the unique characters of the current puzzle, which will be used later for checking if a word is valid with respect to the puzzle. Afterward, for each word in the words array, we check if the first letter of the puzzle is in this word. If it is, we check if all the characters in the word are present in the puzzle set. If they are, we increment the count of the valid words for the current puzzle. Finally, we append the count to our result list and move on to the next puzzle. We do this for all the puzzles, and the result list is returned.

## A solution in Python

```python
def find_num_of_valid_words(words, puzzles):
    result = []
    for puzzle in puzzles:
        count = 0
        puzzle_set = set(puzzle)
        for word in words:
            if puzzle[0] in word:
                if all(c in puzzle_set for c in word):
                    count += 1
        result.append(count)
    return result
```
We iterate through each puzzle in the given puzzles array. Then, we create a set containing all the unique characters of the current puzzle, which will be used later for checking if a word is valid with respect to the puzzle. Afterward, for each word in the words array, we check if the first letter of the puzzle is in this word. If it is, we check if all the characters in the word are present in the puzzle set. If they are, we increment the count of the valid words for the current puzzle. Finally, we append the count to our result list and move on to the next puzzle. We do this for all the puzzles, and the result list is returned.

## A solution in Javascript

```javascript
function findNumOfValidWords(words, puzzles) {
    const result = [];
    for (const puzzle of puzzles) {
        let count = 0;
        const puzzleSet = new Set(puzzle);
        for (const word of words) {
            if (word.includes(puzzle[0])) {
                if (Array.from(word).every(c => puzzleSet.has(c))) {
                    count++;
                }
            }
        }
        result.push(count);
    }
    return result;
}
```
We iterate through each puzzle in the given puzzles array. Then, we create a set containing all the unique characters of the current puzzle, which will be used later for checking if a word is valid with respect to the puzzle. Afterward, for each word in the words array, we check if the first letter of the puzzle is in this word. If it is, we check if all the characters in the word are present in the puzzle set. If they are, we increment the count of the valid words for the current puzzle. Finally, we append the count to our result list and move on to the next puzzle. We do this for all the puzzles, and the result list is returned.


# Count Substrings with Only One Distinct Letter

- slug: count-substrings-with-only-one-distinct-letter
- difficulty: Easy

Given a string `s`, return _the number of substrings that have only **one distinct** letter_.

**Example 1:**

**Input:** s =  "aaaba "
**Output:** 8
**Explanation:** The substrings with one distinct letter are  "aaa ",  "aa ",  "a ",  "b ".
 "aaa " occurs 1 time.
 "aa " occurs 2 times.
 "a " occurs 4 times.
 "b " occurs 1 time.
So the answer is 1 + 2 + 4 + 1 = 8.

**Example 2:**

**Input:** s =  "aaaaaaaaaa "
**Output:** 55

**Constraints:**

*   `1 <= s.length <= 1000`
*   `s[i]` consists of only lowercase English letters.

## A solution in Java

```java
public int countLetters(String s) {
    int count = 0, current = 1;

    for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == s.charAt(i - 1)) {
            current++;
        } else {
            count += (current * (current + 1)) / 2;
            current = 1;
        }
    }

    count += (current * (current + 1)) / 2;
    return count;
}
```
The algorithm iterates through the string `s` and checks if the current character is same as the previous character. If yes, it increments the `current` counter. When it finds a different character, it calculates the count of distinct single-letter substrings ending prior to that character and adds the count to the `count` variable. The formula `(current * (current + 1)) / 2` is the sum of the first `current` positive integers, which is the number of substrings that can be formed with the same character. This process is repeated for each character in the string. Finally, the total count of substrings is returned.

## A solution in C++

```cpp
int countLetters(string s) {
    int count = 0, current = 1;

    for (int i = 1; i < s.length(); i++) {
        if (s[i] == s[i - 1]) {
            current++;
        } else {
            count += (current * (current + 1)) / 2;
            current = 1;
        }
    }

    count += (current * (current + 1)) / 2;
    return count;
}
```
The algorithm iterates through the string `s` and checks if the current character is same as the previous character. If yes, it increments the `current` counter. When it finds a different character, it calculates the count of distinct single-letter substrings ending prior to that character and adds the count to the `count` variable. The formula `(current * (current + 1)) / 2` is the sum of the first `current` positive integers, which is the number of substrings that can be formed with the same character. This process is repeated for each character in the string. Finally, the total count of substrings is returned.

## A solution in Python

```python
def count_letters(s: str) -> int:
    count = 0
    current = 1

    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            current += 1
        else:
            count += (current * (current + 1)) // 2
            current = 1

    count += (current * (current + 1)) // 2
    return count
```
The algorithm iterates through the string `s` and checks if the current character is same as the previous character. If yes, it increments the `current` counter. When it finds a different character, it calculates the count of distinct single-letter substrings ending prior to that character and adds the count to the `count` variable. The formula `(current * (current + 1)) / 2` is the sum of the first `current` positive integers, which is the number of substrings that can be formed with the same character. This process is repeated for each character in the string. Finally, the total count of substrings is returned.

## A solution in Javascript

```javascript
function countLetters(s) {
    let count = 0;
    let current = 1;

    for (let i = 1; i < s.length; i++) {
        if (s[i] === s[i - 1]) {
            current++;
        } else {
            count += (current * (current + 1)) / 2;
            current = 1;
        }
    }

    count += (current * (current + 1)) / 2;
    return count;
}
```
The algorithm iterates through the string `s` and checks if the current character is same as the previous character. If yes, it increments the `current` counter. When it finds a different character, it calculates the count of distinct single-letter substrings ending prior to that character and adds the count to the `count` variable. The formula `(current * (current + 1)) / 2` is the sum of the first `current` positive integers, which is the number of substrings that can be formed with the same character. This process is repeated for each character in the string. Finally, the total count of substrings is returned.


# Before and After Puzzle

- slug: before-and-after-puzzle
- difficulty: Medium

Given a list of `phrases`, generate a list of Before and After puzzles.

A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.

_Before and After puzzles_ are phrases that are formed by merging two phrases where the **last word of the first phrase** is the same as the **first word of the second phrase**.

Return the Before and After puzzles that can be formed by every two phrases `phrases[i]` and `phrases[j]` where `i != j`. Note that the order of matching two phrases matters, we want to consider both orders.

You should return a list of **distinct** strings **sorted lexicographically**.

**Example 1:**

**Input:** phrases = \[ "writing code ", "code rocks "\]
**Output:** \[ "writing code rocks "\]

**Example 2:**

**Input:** phrases = \[ "mission statement ",
                   "a quick bite to eat ",
                   "a chip off the old block ",
                   "chocolate bar ",
                   "mission impossible ",
                   "a man on a mission ",
                   "block party ",
                   "eat my words ",
                   "bar of soap "\]
**Output:** \[ "a chip off the old block party ",
          "a man on a mission impossible ",
          "a man on a mission statement ",
          "a quick bite to eat my words ",
          "chocolate bar of soap "\]

**Example 3:**

**Input:** phrases = \[ "a ", "b ", "a "\]
**Output:** \[ "a "\]

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

public List<String> beforeAndAfterPuzzles(String[] phrases) {
    Map<String, Set<String>> firstWordMap = new HashMap<>();
    Set<String> result = new TreeSet<>();

    for (String phrase : phrases) {
        String firstWord = phrase.substring(0, phrase.indexOf(' '));
        firstWordMap.putIfAbsent(firstWord, new HashSet<>());
        firstWordMap.get(firstWord).add(phrase);
    }

    for (String phrase : phrases) {
        String lastWord = phrase.substring(phrase.lastIndexOf(' ') + 1);
        if (firstWordMap.containsKey(lastWord)) {
            for (String curPhrase : firstWordMap.get(lastWord)) {
                if (!phrase.equals(curPhrase)) {
                    result.add(phrase + curPhrase.substring(curPhrase.indexOf(' ')));
                }
            }
        }
    }

    return new ArrayList<>(result);
}
```
1. Create a mapping of first words to their corresponding phrases.
2. For each phrase, check if the last word is a key in the mapping, then iterate through the phrases that have the last word as their first word.
3. If the current phrase and the original phrase are not the same, merge the phrases to create a puzzle and add it to the result set.
4. Convert the result set to a list/array, sort it and return it.

## A solution in C++

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

std::vector<std::string> beforeAndAfterPuzzles(std::vector<std::string>& phrases) {
    std::unordered_map<std::string, std::set<std::string>> firstWordMap;
    std::set<std::string> result;

    for (const std::string& phrase : phrases) {
        std::string firstWord = phrase.substr(0, phrase.find(' '));
        if (firstWordMap.find(firstWord) != firstWordMap.end()) {
            firstWordMap[firstWord].insert(phrase);
        } else {
            firstWordMap[firstWord] = {phrase};
        }
    }

    for (const std::string& phrase : phrases) {
        std::string lastWord = phrase.substr(phrase.rfind(' ') + 1);
        if (firstWordMap.find(lastWord) != firstWordMap.end()) {
            for (const std::string& curPhrase : firstWordMap[lastWord]) {
                if (phrase != curPhrase) {
                    result.insert(phrase + curPhrase.substr(curPhrase.find(' ')));
                }
            }
        }
    }

    return std::vector<std::string>(result.begin(), result.end());
}
```
1. Create a mapping of first words to their corresponding phrases.
2. For each phrase, check if the last word is a key in the mapping, then iterate through the phrases that have the last word as their first word.
3. If the current phrase and the original phrase are not the same, merge the phrases to create a puzzle and add it to the result set.
4. Convert the result set to a list/array, sort it and return it.

## A solution in Python

```python
from collections import defaultdict

def beforeAndAfterPuzzles(phrases):
    first_word_map = defaultdict(set)
    result = set()

    for phrase in phrases:
        first_word = phrase.split(' ')[0]
        first_word_map[first_word].add(phrase)

    for phrase in phrases:
        last_word = phrase.split(' ')[-1]
        if last_word in first_word_map:
            for cur_phrase in first_word_map[last_word]:
                if phrase != cur_phrase:
                    result.add(phrase + cur_phrase[cur_phrase.index(' '):])

    return sorted(list(result))
```
1. Create a mapping of first words to their corresponding phrases.
2. For each phrase, check if the last word is a key in the mapping, then iterate through the phrases that have the last word as their first word.
3. If the current phrase and the original phrase are not the same, merge the phrases to create a puzzle and add it to the result set.
4. Convert the result set to a list/array, sort it and return it.

## A solution in Javascript

```javascript
function beforeAndAfterPuzzles(phrases) {
    const firstWordMap = new Map();
    const result = new Set();

    for (const phrase of phrases) {
        const firstWord = phrase.split(' ')[0];
        if (!firstWordMap.has(firstWord)) {
            firstWordMap.set(firstWord, new Set());
        }
        firstWordMap.get(firstWord).add(phrase);
    }

    for (const phrase of phrases) {
        const lastWord = phrase.split(' ').pop();
        if (firstWordMap.has(lastWord)) {
            for (const curPhrase of firstWordMap.get(lastWord)) {
                if (phrase !== curPhrase) {
                    result.add(phrase + curPhrase.slice(curPhrase.indexOf(' ')));
                }
            }
        }
    }

    return Array.from(result).sort();
}
```
1. Create a mapping of first words to their corresponding phrases.
2. For each phrase, check if the last word is a key in the mapping, then iterate through the phrases that have the last word as their first word.
3. If the current phrase and the original phrase are not the same, merge the phrases to create a puzzle and add it to the result set.
4. Convert the result set to a list/array, sort it and return it.


# Shortest Distance to Target Color

- slug: shortest-distance-to-target-color
- difficulty: Medium

You are given an array `colors`, in which there are three colors: `1`, `2` and `3`.

You are also given some queries. Each query consists of two integers `i` and `c`, return the shortest distance between the given index `i` and the target color `c`. If there is no solution return `-1`.

**Example 1:**

**Input:** colors = \[1,1,2,1,3,2,2,3,3\], queries = \[\[1,3\],\[2,2\],\[6,1\]\]
**Output:** \[3,0,3\]
**Explanation:**
The nearest 3 from index 1 is at index 4 (3 steps away).
The nearest 2 from index 2 is at index 2 itself (0 steps away).
The nearest 1 from index 6 is at index 3 (3 steps away).

**Example 2:**

**Input:** colors = \[1,2\], queries = \[\[0,3\]\]
**Output:** \[-1\]
**Explanation:** There is no 3 in the array.

**Constraints:**

*   `1 <= colors.length <= 5*10^4`
*   `1 <= colors[i] <= 3`
*   `1 <= queries.length <= 5*10^4`
*   `queries[i].length == 2`
*   `0 <= queries[i][0] < colors.length`
*   `1 <= queries[i][1] <= 3`

## A solution in Java

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

public List<Integer> shortestDistance(int[] colors, int[][] queries) {
    List<Integer> result = new ArrayList<>();
    List<List<Integer>> positions = new ArrayList<>(3);

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

    for (int i = 0; i < colors.length; i++) {
        positions.get(colors[i] - 1).add(i);
    }

    for (int[] query : queries) {
        List<Integer> indexPositions = positions.get(query[1] - 1);

        if (indexPositions.isEmpty()) {
            result.add(-1);
        } else {
            int dist = Integer.MAX_VALUE;

            for (int pos : indexPositions) {
                dist = Math.min(dist, Math.abs(pos - query[0]));
            }

            result.add(dist);
        }
    }

    return result;
}
```
The algorithm maintains a list with 3 inner lists (named `positions`), representing the positions where each color (`1`, `2`, or `3`) appear in the input list `colors`.

For each query, we get the index positions of the target color (query[1]) from the `positions` list. If there are no index positions, we append `-1` to our `result` list. Otherwise, we calculate the distance between each target color position and the index `i` given in the query by finding the absolute difference of their indices. We keep the minimum distance found, and append it to our `result` list.

Finally, we return the `result` list containing the shortest distances for each query.

## A solution in C++

```cpp
#include<vector>

std::vector<int> shortestDistance(std::vector<int>& colors, std::vector<std::vector<int>>& queries) {
    std::vector<int> result;
    std::vector<std::vector<int>> positions(3);

    for(int i = 0; i < colors.size(); i++) {
        positions[colors[i] - 1].push_back(i);
    }

    for(auto &query : queries) {
        auto &index_positions = positions[query[1] - 1];

        if (index_positions.empty()) {
            result.push_back(-1);
        } else {
            int dist = INT_MAX;

            for (auto pos : index_positions) {
                dist = std::min(dist, std::abs(pos - query[0]));
            }

            result.push_back(dist);
        }
    }

    return result;
}
```
The algorithm maintains a list with 3 inner lists (named `positions`), representing the positions where each color (`1`, `2`, or `3`) appear in the input list `colors`.

For each query, we get the index positions of the target color (query[1]) from the `positions` list. If there are no index positions, we append `-1` to our `result` list. Otherwise, we calculate the distance between each target color position and the index `i` given in the query by finding the absolute difference of their indices. We keep the minimum distance found, and append it to our `result` list.

Finally, we return the `result` list containing the shortest distances for each query.

## A solution in Python

```python
def shortestDistance(colors, queries):
    result = []
    positions = [[] for _ in range(3)]

    for i, color in enumerate(colors):
        positions[color - 1].append(i)

    for query in queries:
        index_positions = positions[query[1] - 1]

        if not index_positions:
            result.append(-1)
        else:
            dist = float('inf')

            for pos in index_positions:
                dist = min(dist, abs(pos - query[0]))

            result.append(dist)

    return result
```
The algorithm maintains a list with 3 inner lists (named `positions`), representing the positions where each color (`1`, `2`, or `3`) appear in the input list `colors`.

For each query, we get the index positions of the target color (query[1]) from the `positions` list. If there are no index positions, we append `-1` to our `result` list. Otherwise, we calculate the distance between each target color position and the index `i` given in the query by finding the absolute difference of their indices. We keep the minimum distance found, and append it to our `result` list.

Finally, we return the `result` list containing the shortest distances for each query.

## A solution in Javascript

```javascript
function shortestDistance(colors, queries) {
    const result = [];
    const positions = [[], [], []];

    colors.forEach((color, i) => {
        positions[color - 1].push(i);
    });

    queries.forEach(query => {
        const indexPositions = positions[query[1] - 1];

        if (!indexPositions.length) {
            result.push(-1);
        } else {
            let dist = Infinity;

            indexPositions.forEach(pos => {
                dist = Math.min(dist, Math.abs(pos - query[0]));
            });

            result.push(dist);
        }
    });

    return result;
}
```
The algorithm maintains a list with 3 inner lists (named `positions`), representing the positions where each color (`1`, `2`, or `3`) appear in the input list `colors`.

For each query, we get the index positions of the target color (query[1]) from the `positions` list. If there are no index positions, we append `-1` to our `result` list. Otherwise, we calculate the distance between each target color position and the index `i` given in the query by finding the absolute difference of their indices. We keep the minimum distance found, and append it to our `result` list.

Finally, we return the `result` list containing the shortest distances for each query.