# Queries on a Permutation With Key

- slug: queries-on-a-permutation-with-key
- difficulty: Medium

Given the array `queries` of positive integers between `1` and `m`, you have to process all `queries[i]` (from `i=0` to `i=queries.length-1`) according to the following rules:

*   In the beginning, you have the permutation `P=[1,2,3,...,m]`.
*   For the current `i`, find the position of `queries[i]` in the permutation `P` (**indexing from 0**) and then move this at the beginning of the permutation `P.` Notice that the position of `queries[i]` in `P` is the result for `queries[i]`.

Return an array containing the result for the given `queries`.

**Example 1:**

**Input:** queries = \[3,1,2,1\], m = 5
**Output:** \[2,1,2,1\]
**Explanation:** The queries are processed as follow:
For i=0: queries\[i\]=3, P=\[1,2,3,4,5\], position of 3 in P is **2**, then we move 3 to the beginning of P resulting in P=\[3,1,2,4,5\].
For i=1: queries\[i\]=1, P=\[3,1,2,4,5\], position of 1 in P is **1**, then we move 1 to the beginning of P resulting in P=\[1,3,2,4,5\].
For i=2: queries\[i\]=2, P=\[1,3,2,4,5\], position of 2 in P is **2**, then we move 2 to the beginning of P resulting in P=\[2,1,3,4,5\].
For i=3: queries\[i\]=1, P=\[2,1,3,4,5\], position of 1 in P is **1**, then we move 1 to the beginning of P resulting in P=\[1,2,3,4,5\].
Therefore, the array containing the result is \[2,1,2,1\].

**Example 2:**

**Input:** queries = \[4,1,2,2\], m = 4
**Output:** \[3,1,2,0\]

**Example 3:**

**Input:** queries = \[7,5,5,8,3\], m = 8
**Output:** \[6,5,0,7,5\]

**Constraints:**

*   `1 <= m <= 10^3`
*   `1 <= queries.length <= m`
*   `1 <= queries[i] <= m`

## A solution in Java

```java
import java.util.*;

public int minNumberOfFlips(int[][] mat) {
    final int m = mat.length, n = mat[0].length;
    final int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {0, 0}};
    int steps = 0;

    while (true) {
        int flipped = 0;
        Queue<Integer> que = new LinkedList<>();

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (mat[i][j] == 1) {
                    que.offer(i * n + j);
                }
            }
        }

        while (!que.isEmpty()) {
            int cur = que.poll(), cur_i = cur / n, cur_j = cur % n;
            for (int[] dir : dirs) {
                int ni = cur_i + dir[0], nj = cur_j + dir[1];
                if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
                    mat[ni][nj] ^= 1;
                    ++flipped;
                }
            }
        }

        if (flipped == 0) {
            break;
        }
        steps += flipped;
    }

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (mat[i][j] == 1) {
                return -1;
            }
        }
    }

    return steps;
}
```
1. Initialize the step counter and the directions we need to flip.
2. Enter a loop that continues until no flipping is performed in one iteration (use a flipped counter to track flips).
3. For each 1 cell in the matrix, enqueue its encoded position `(i * n + j)` to ensure uniqueness in a queue.
4. Dequeue positions from the queue, and perform flip operations (XOR with 1) for the current cell and its neighbors.
5. Increment the step counter with the number of flipped cells in the current iteration.
6. After exiting the loop, if there are any remaining 1s in the matrix, return -1, as it's impossible to form a zero matrix. Otherwise, return the step counter.

## A solution in C++

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

int minNumberOfFlips(std::vector<std::vector<int>>& mat) {
    int m = mat.size(), n = mat[0].size();
    int steps = 0;
    int dirs[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {0, 0}};

    auto encode = [&](int i, int j) { return i * n + j; };

    while (true) {
        int flipped = 0;
        std::queue<int> que;

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (mat[i][j] == 1) {
                    que.push(encode(i, j));
                }
            }
        }

        while (!que.empty()) {
            int cur = que.front(), cur_i = cur / n, cur_j = cur % n;
            que.pop();

            for (auto dir : dirs) {
                int ni = cur_i + dir[0], nj = cur_j + dir[1];
                if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
                    mat[ni][nj] ^= 1;
                    ++flipped;
                }
            }
        }

        if (flipped == 0) {
            break;
        }
        steps += flipped;
    }

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (mat[i][j] == 1) {
                return -1;
            }
        }
    }

    return steps;
}
```
1. Initialize the step counter and the directions we need to flip.
2. Enter a loop that continues until no flipping is performed in one iteration (use a flipped counter to track flips).
3. For each 1 cell in the matrix, enqueue its encoded position `(i * n + j)` to ensure uniqueness in a queue.
4. Dequeue positions from the queue, and perform flip operations (XOR with 1) for the current cell and its neighbors.
5. Increment the step counter with the number of flipped cells in the current iteration.
6. After exiting the loop, if there are any remaining 1s in the matrix, return -1, as it's impossible to form a zero matrix. Otherwise, return the step counter.

## A solution in Python

```python
from collections import deque

def minNumberOfFlips(mat):
    m, n = len(mat), len(mat[0])
    steps = 0
    dirs = [(0, 1), (0, -1), (1, 0), (-1, 0), (0, 0)]

    def encode(i, j):
        return i * n + j

    while True:
        flipped = 0
        que = deque()

        for i in range(m):
            for j in range(n):
                if mat[i][j] == 1:
                    que.append(encode(i, j))

        while que:
            cur = que.popleft()
            cur_i, cur_j = divmod(cur, n)

            for dx, dy in dirs:
                ni, nj = cur_i + dx, cur_j + dy
                if 0 <= ni < m and 0 <= nj < n:
                    mat[ni][nj] ^= 1
                    flipped += 1

        if flipped == 0:
            break
        steps += flipped

    for row in mat:
        if any(cell == 1 for cell in row):
            return -1

    return steps
```
1. Initialize the step counter and the directions we need to flip.
2. Enter a loop that continues until no flipping is performed in one iteration (use a flipped counter to track flips).
3. For each 1 cell in the matrix, enqueue its encoded position `(i * n + j)` to ensure uniqueness in a queue.
4. Dequeue positions from the queue, and perform flip operations (XOR with 1) for the current cell and its neighbors.
5. Increment the step counter with the number of flipped cells in the current iteration.
6. After exiting the loop, if there are any remaining 1s in the matrix, return -1, as it's impossible to form a zero matrix. Otherwise, return the step counter.

## A solution in Javascript

```javascript
function minNumberOfFlips(mat) {
    const m = mat.length, n = mat[0].length;
    let steps = 0;
    const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0], [0, 0]];

    function encode(i, j) {
        return i * n + j;
    }

    while (true) {
        let flipped = 0;
        const que = [];

        for (let i = 0; i < m; ++i) {
            for (let j = 0; j < n; ++j) {
                if (mat[i][j] === 1) {
                    que.push(encode(i, j));
                }
            }
        }

        while (que.length > 0) {
            const cur = que.shift();
            const cur_i = Math.floor(cur / n), cur_j = cur % n;

            for (const dir of dirs) {
                const ni = cur_i + dir[0], nj = cur_j + dir[1];
                if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
                    mat[ni][nj] ^= 1;
                    ++flipped;
                }
            }
        }

        if (flipped === 0) {
            break;
        }
        steps += flipped;
    }

    for (const row of mat) {
        for (const cell of row) {
            if (cell === 1) {
                return -1;
            }
        }
    }

    return steps;
}
```
1. Initialize the step counter and the directions we need to flip.
2. Enter a loop that continues until no flipping is performed in one iteration (use a flipped counter to track flips).
3. For each 1 cell in the matrix, enqueue its encoded position `(i * n + j)` to ensure uniqueness in a queue.
4. Dequeue positions from the queue, and perform flip operations (XOR with 1) for the current cell and its neighbors.
5. Increment the step counter with the number of flipped cells in the current iteration.
6. After exiting the loop, if there are any remaining 1s in the matrix, return -1, as it's impossible to form a zero matrix. Otherwise, return the step counter.


# HTML Entity Parser

- slug: html-entity-parser
- difficulty: Medium

**HTML entity parser** is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.

The special characters and their entities for HTML are:

*   **Quotation Mark:** the entity is `"` and symbol character is `"`.
*   **Single Quote Mark:** the entity is `'` and symbol character is `'`.
*   **Ampersand:** the entity is `&` and symbol character is `&`.
*   **Greater Than Sign:** the entity is `>` and symbol character is `>`.
*   **Less Than Sign:** the entity is `<` and symbol character is `<`.
*   **Slash:** the entity is `⁄` and symbol character is `/`.

Given the input `text` string to the HTML parser, you have to implement the entity parser.

Return _the text after replacing the entities by the special characters_.

**Example 1:**

**Input:** text =  "& is an HTML entity but &ambassador; is not. "
**Output:**  "& is an HTML entity but &ambassador; is not. "
**Explanation:** The parser will replace the & entity by &

**Example 2:**

**Input:** text =  "and I quote: "..." "
**Output:**  "and I quote: \\ "...\\ " "

**Constraints:**

*   `1 <= text.length <= 105`
*   The string may contain any possible characters out of all the 256 ASCII characters.

## A solution in Java

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

public String entityParser(String text) {
    Map<String, String> entities = new HashMap<String, String>() {{
        put(""", "\"");
        put("'", "'");
        put("&", "&");
        put(">", ">");
        put("<", "<");
        put("⁄", "/");
    }};

    StringBuilder result = new StringBuilder();
    StringBuilder currentEntity = new StringBuilder();
    boolean inEntity = false;

    for (char c : text.toCharArray()) {
        if (inEntity) {
            currentEntity.append(c);
            if (c == ';') {
                String entity = currentEntity.toString();
                if (entities.containsKey(entity)) {
                    result.append(entities.get(entity));
                } else {
                    result.append(entity);
                }
                inEntity = false;
                currentEntity = new StringBuilder();
            }
        } else {
            if (c == '&') {
                inEntity = true;
                currentEntity.append(c);
            } else {
                result.append(c);
            }
        }
    }

    return result.toString();
}
```
The algorithm uses a hashmap to store the entities as keys and their corresponding special characters as values. It iterates through the input string and maintains a flag `inEntity`, which is set to true when the current character is an ampersand (`&`). While `inEntity` is true, the algorithm collects characters in the `currentEntity` string until it encounters a semicolon (`;`). When it encounters a semicolon, it checks if `currentEntity` is in the `entities` hashmap. If it is, it appends the corresponding character from the hashmap to the `result` string; otherwise, it appends `currentEntity` to the `result` string. In both cases, `inEntity` is set back to false, and `currentEntity` is reset. When `inEntity` is false, the algorithm simply appends characters from the input string to the `result` string.

After iterating through the entire input string, the algorithm returns the `result` string with the entities replaced by their corresponding special characters.

## A solution in C++

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

std::string entityParser(std::string text) {
    std::unordered_map<std::string, std::string> entities = {
        {""", "\""},
        {"'", "'"},
        {"&", "&"},
        {">", ">"},
        {"<", "<"},
        {"⁄", "/"},
    };

    std::string result;
    std::string current_entity;
    bool in_entity = false;

    for (char c : text) {
        if (in_entity) {
            current_entity.push_back(c);
            if (c == ';') {
                if (entities.find(current_entity) != entities.end()) {
                    result += entities[current_entity];
                } else {
                    result += current_entity;
                }
                in_entity = false;
                current_entity.clear();
            }
        } else {
            if (c == '&') {
                in_entity = true;
                current_entity.push_back(c);
            } else {
                result.push_back(c);
            }
        }
    }

    return result;
}
```
The algorithm uses a hashmap to store the entities as keys and their corresponding special characters as values. It iterates through the input string and maintains a flag `inEntity`, which is set to true when the current character is an ampersand (`&`). While `inEntity` is true, the algorithm collects characters in the `currentEntity` string until it encounters a semicolon (`;`). When it encounters a semicolon, it checks if `currentEntity` is in the `entities` hashmap. If it is, it appends the corresponding character from the hashmap to the `result` string; otherwise, it appends `currentEntity` to the `result` string. In both cases, `inEntity` is set back to false, and `currentEntity` is reset. When `inEntity` is false, the algorithm simply appends characters from the input string to the `result` string.

After iterating through the entire input string, the algorithm returns the `result` string with the entities replaced by their corresponding special characters.

## A solution in Python

```python
def entity_parser(text: str) -> str:
    entities = {
        """: "\"",
        "'": "'",
        "&": "&",
        ">": ">",
        "<": "<",
        "⁄": "/",
    }

    result = []
    current_entity = []
    in_entity = False

    for c in text:
        if in_entity:
            current_entity.append(c)
            if c == ';':
                entity = ''.join(current_entity)
                if entity in entities:
                    result.append(entities[entity])
                else:
                    result.extend(current_entity)
                in_entity = False
                current_entity.clear()
        else:
            if c == '&':
                in_entity = True
                current_entity.append(c)
            else:
                result.append(c)

    return ''.join(result)
```
The algorithm uses a hashmap to store the entities as keys and their corresponding special characters as values. It iterates through the input string and maintains a flag `inEntity`, which is set to true when the current character is an ampersand (`&`). While `inEntity` is true, the algorithm collects characters in the `currentEntity` string until it encounters a semicolon (`;`). When it encounters a semicolon, it checks if `currentEntity` is in the `entities` hashmap. If it is, it appends the corresponding character from the hashmap to the `result` string; otherwise, it appends `currentEntity` to the `result` string. In both cases, `inEntity` is set back to false, and `currentEntity` is reset. When `inEntity` is false, the algorithm simply appends characters from the input string to the `result` string.

After iterating through the entire input string, the algorithm returns the `result` string with the entities replaced by their corresponding special characters.

## A solution in Javascript

```javascript
function entityParser(text) {
    const entities = {
        """: "\"",
        "'": "\'",
        "&": "&",
        ">": ">",
        "<": "<",
        "⁄": "/",
    };

    let result = '';
    let currentEntity = '';
    let inEntity = false;

    for (const c of text) {
        if (inEntity) {
            currentEntity += c;
            if (c === ';') {
                if (entities.hasOwnProperty(currentEntity)) {
                    result += entities[currentEntity];
                } else {
                    result += currentEntity;
                }
                inEntity = false;
                currentEntity = '';
            }
        } else {
            if (c === '&') {
                inEntity = true;
                currentEntity += c;
            } else {
                result += c;
            }
        }
    }

    return result;
}
```
The algorithm uses a hashmap to store the entities as keys and their corresponding special characters as values. It iterates through the input string and maintains a flag `inEntity`, which is set to true when the current character is an ampersand (`&`). While `inEntity` is true, the algorithm collects characters in the `currentEntity` string until it encounters a semicolon (`;`). When it encounters a semicolon, it checks if `currentEntity` is in the `entities` hashmap. If it is, it appends the corresponding character from the hashmap to the `result` string; otherwise, it appends `currentEntity` to the `result` string. In both cases, `inEntity` is set back to false, and `currentEntity` is reset. When `inEntity` is false, the algorithm simply appends characters from the input string to the `result` string.

After iterating through the entire input string, the algorithm returns the `result` string with the entities replaced by their corresponding special characters.


# Number of Ways to Paint N × 3 Grid

- slug: number-of-ways-to-paint-n-3-grid
- difficulty: Hard

You have a `grid` of size `n x 3` and you want to paint each cell of the grid with exactly one of the three colors: **Red**, **Yellow,** or **Green** while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).

Given `n` the number of rows of the grid, return _the number of ways_ you can paint this `grid`. As the answer may grow large, the answer **must be** computed modulo `109 + 7`.

**Example 1:**

**Input:** n = 1
**Output:** 12
**Explanation:** There are 12 possible way to paint the grid as shown.

**Example 2:**

**Input:** n = 5000
**Output:** 30228214

**Constraints:**

*   `n == grid.length`
*   `1 <= n <= 5000`

## A solution in Java

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

public int getDecimalValue(ListNode head) {
    int num = 0;
    while (head != null) {
        num = (num << 1) | head.val;
        head = head.next;
    }
    return num;
}
```
The algorithm iterates through the singly-linked list, starting at the head node. The binary number represented by the linked list is constructed by shifting the current value of `num` one bit to the left and performing a bitwise OR operation with the value of the current node. This process continues until the end of the linked list is reached. After the last node, `num` contains the decimal representation of the binary number, so the function returns it.

## A solution in C++

```cpp
class ListNode {
public:
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

int getDecimalValue(ListNode* head) {
    int num = 0;
    while (head) {
        num = (num << 1) | head->val;
        head = head->next;
    }
    return num;
}
```
The algorithm iterates through the singly-linked list, starting at the head node. The binary number represented by the linked list is constructed by shifting the current value of `num` one bit to the left and performing a bitwise OR operation with the value of the current node. This process continues until the end of the linked list is reached. After the last node, `num` contains the decimal representation of the binary number, so the function returns it.

## A solution in Python

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

def getDecimalValue(head: ListNode) -> int:
    num = 0
    while head:
        num = (num << 1) | head.val
        head = head.next
    return num
```
The algorithm iterates through the singly-linked list, starting at the head node. The binary number represented by the linked list is constructed by shifting the current value of `num` one bit to the left and performing a bitwise OR operation with the value of the current node. This process continues until the end of the linked list is reached. After the last node, `num` contains the decimal representation of the binary number, so the function returns it.

## A solution in Javascript

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

function getDecimalValue(head) {
    let num = 0;
    while (head) {
        num = (num << 1) | head.val;
        head = head.next;
    }
    return num;
}
```
The algorithm iterates through the singly-linked list, starting at the head node. The binary number represented by the linked list is constructed by shifting the current value of `num` one bit to the left and performing a bitwise OR operation with the value of the current node. This process continues until the end of the linked list is reached. After the last node, `num` contains the decimal representation of the binary number, so the function returns it.


# Minimum Value to Get Positive Step by Step Sum

- slug: minimum-value-to-get-positive-step-by-step-sum
- difficulty: Easy

Given an array of integers `nums`, you start with an initial **positive** value _startValue__._

In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right).

Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1.

**Example 1:**

**Input:** nums = \[-3,2,-3,4,2\]
**Output:** 5
**Explanation:** If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
**step by step sum**
**startValue = 4 | startValue = 5 | nums**
  (4 **\-3** ) = 1  | (5 **\-3** ) = 2    |  -3
  (1 **+2** ) = 3  | (2 **+2** ) = 4    |   2
  (3 **\-3** ) = 0  | (4 **\-3** ) = 1    |  -3
  (0 **+4** ) = 4  | (1 **+4** ) = 5    |   4
  (4 **+2** ) = 6  | (5 **+2** ) = 7    |   2

**Example 2:**

**Input:** nums = \[1,2\]
**Output:** 1
**Explanation:** Minimum start value should be positive.

**Example 3:**

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

**Constraints:**

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

## A solution in Java

```java
public int maxSideLength(int[][] mat, int threshold) {
    int m = mat.length;
    int n = mat[0].length;
    int[][] dp = new int[m + 1][n + 1];
    int ans = 0;

    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            dp[i][j] = mat[i - 1][j - 1] + dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1];
            int k = ans + 1;
            if (i >= k && j >= k && dp[i][j] - dp[i][j - k] - dp[i - k][j] + dp[i - k][j - k] <= threshold) {
                ans++;
            }
        }
    }
    return ans;
}
```
We use dynamic programming to solve this problem. First, we create a 2D dp array of size (m+1) x (n+1) initialized with 0. The dp array stores the sum of all elements above and left of the current cell, including the current cell. Then, we iterate through each cell in the input matrix, and compute the sums for the dp array.

At each cell, we check if there is a possibility of extending the side length of the square. We do this by checking if the current cell's row and column are greater than or equal to the side length we are checking for (ans + 1). If true, we check if the sum of the square with side length (ans + 1) is less than or equal to the threshold. The sum is computed using the dp array's values by adding the top-left and bottom-right corners and subtracting the bottom-left and top-right corners. If the sum is within the threshold, we increment the ans variable.

Finally, we return the ans variable which stores the maximum side-length of a square with sum less than or equal to the threshold.

## A solution in C++

```cpp
int maxSideLength(vector<vector<int>>& mat, int threshold) {
    int m = mat.size();
    int n = mat[0].size();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
    int ans = 0;

    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            dp[i][j] = mat[i-1][j-1] + dp[i][j-1] + dp[i-1][j] - dp[i-1][j-1];
            int k = ans + 1;
            if (i >= k && j >= k && dp[i][j] - dp[i][j-k] - dp[i-k][j] + dp[i-k][j-k] <= threshold) {
                ans++;
            }
        }
    }
    return ans;
}
```
We use dynamic programming to solve this problem. First, we create a 2D dp array of size (m+1) x (n+1) initialized with 0. The dp array stores the sum of all elements above and left of the current cell, including the current cell. Then, we iterate through each cell in the input matrix, and compute the sums for the dp array.

At each cell, we check if there is a possibility of extending the side length of the square. We do this by checking if the current cell's row and column are greater than or equal to the side length we are checking for (ans + 1). If true, we check if the sum of the square with side length (ans + 1) is less than or equal to the threshold. The sum is computed using the dp array's values by adding the top-left and bottom-right corners and subtracting the bottom-left and top-right corners. If the sum is within the threshold, we increment the ans variable.

Finally, we return the ans variable which stores the maximum side-length of a square with sum less than or equal to the threshold.

## A solution in Python

```python
def maxSideLength(mat, threshold):
    m, n = len(mat), len(mat[0])
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    ans = 0

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            dp[i][j] = mat[i - 1][j - 1] + dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1]
            k = ans + 1
            if i >= k and j >= k and dp[i][j] - dp[i][j - k] - dp[i - k][j] + dp[i - k][j - k] <= threshold:
                ans += 1

    return ans
```
We use dynamic programming to solve this problem. First, we create a 2D dp array of size (m+1) x (n+1) initialized with 0. The dp array stores the sum of all elements above and left of the current cell, including the current cell. Then, we iterate through each cell in the input matrix, and compute the sums for the dp array.

At each cell, we check if there is a possibility of extending the side length of the square. We do this by checking if the current cell's row and column are greater than or equal to the side length we are checking for (ans + 1). If true, we check if the sum of the square with side length (ans + 1) is less than or equal to the threshold. The sum is computed using the dp array's values by adding the top-left and bottom-right corners and subtracting the bottom-left and top-right corners. If the sum is within the threshold, we increment the ans variable.

Finally, we return the ans variable which stores the maximum side-length of a square with sum less than or equal to the threshold.

## A solution in Javascript

```javascript
function maxSideLength(mat, threshold) {
    const m = mat.length;
    const n = mat[0].length;
    const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
    let ans = 0;

    for (let i = 1; i <= m; i++) {
        for (let j = 1; j <= n; j++) {
            dp[i][j] = mat[i - 1][j - 1] + dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1];
            const k = ans + 1;
            if (i >= k && j >= k && dp[i][j] - dp[i][j - k] - dp[i - k][j] + dp[i - k][j - k] <= threshold) {
                ans++;
            }
        }
    }
    return ans;
}
```
We use dynamic programming to solve this problem. First, we create a 2D dp array of size (m+1) x (n+1) initialized with 0. The dp array stores the sum of all elements above and left of the current cell, including the current cell. Then, we iterate through each cell in the input matrix, and compute the sums for the dp array.

At each cell, we check if there is a possibility of extending the side length of the square. We do this by checking if the current cell's row and column are greater than or equal to the side length we are checking for (ans + 1). If true, we check if the sum of the square with side length (ans + 1) is less than or equal to the threshold. The sum is computed using the dp array's values by adding the top-left and bottom-right corners and subtracting the bottom-left and top-right corners. If the sum is within the threshold, we increment the ans variable.

Finally, we return the ans variable which stores the maximum side-length of a square with sum less than or equal to the threshold.


# Find the Minimum Number of Fibonacci Numbers Whose Sum Is K

- slug: find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k
- difficulty: Medium

Given an integer `k`, _return the minimum number of Fibonacci numbers whose sum is equal to_ `k`. The same Fibonacci number can be used multiple times.

The Fibonacci numbers are defined as:

*   `F1 = 1`
*   `F2 = 1`
*   `Fn = Fn-1 + Fn-2` for `n > 2.`

It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to `k`.

**Example 1:**

**Input:** k = 7
**Output:** 2
**Explanation:** The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.

**Example 2:**

**Input:** k = 10
**Output:** 2
**Explanation:** For k = 10 we can use 2 + 8 = 10.

**Example 3:**

**Input:** k = 19
**Output:** 3
**Explanation:** For k = 19 we can use 1 + 5 + 13 = 19.

**Constraints:**

*   `1 <= k <= 109`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int shortestPath(int[][] grid, int k) {
        int m = grid.length;
        int n = grid[0].length;
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0, 0, k});
        boolean[][][] visited = new boolean[m][n][k + 1];

        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int x = current[0];
            int y = current[1];
            int step = current[2];
            int remainingK = current[3];

            if (x == m - 1 && y == n - 1) return step;
            if (visited[x][y][remainingK]) continue;
            visited[x][y][remainingK] = true;

            int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

            for (int[] dir : directions) {
                int nx = x + dir[0];
                int ny = y + dir[1];

                if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
                    if (grid[nx][ny] == 1 && remainingK > 0) {
                        queue.offer(new int[]{nx, ny, step + 1, remainingK - 1});
                    } else if (grid[nx][ny] == 0) {
                        queue.offer(new int[]{nx, ny, step + 1, remainingK});
                    }
                }
            }
        }

        return -1;
    }
}
```
We use Breadth-First Search (BFS) algorithm to explore the grid. We maintain a queue to store the current status of the cell (x, y, step) as well as the remaining obstacles that we can eliminate (remaining_k). We initialize the queue with (0, 0, 0, k).

We then iterate through the queue until it's empty, in each iteration we pop the front element and check if we reach the bottom-right corner (m-1, n-1). If yes, we return the number of steps. If not, we mark the cell as visited and try to explore the neighbors in all four directions (up, down, left, right). If the neighbor cell has an obstacle and we have remaining_k > 0, we can eliminate the obstacle and add the neighbor cell into the queue with its new status. If the neighbor cell has no obstacle, we can simply add it to the queue.

After the iteration through the queue, if we haven't found a valid path to (m-1, n-1), we return -1.

The time complexity of this algorithm is O(m * n * k) because we potentially need to traverse all m * n cells, multiplied by k because we are keeping track of k states at each cell.

## A solution in C++

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

int shortestPath(std::vector<std::vector<int>>& grid, int k) {
    int m = grid.size();
    int n = grid[0].size();
    std::queue<std::tuple<int, int, int, int>> q;
    q.push({0, 0, 0, k});
    std::vector<std::vector<std::vector<int>>> visited(m, std::vector<std::vector<int>>(n, std::vector<int>(k + 1, false)));

    while (!q.empty()) {
        auto [x, y, step, remain_k] = q.front();
        q.pop();

        if (x == m - 1 && y == n - 1) return step;
        if (visited[x][y][remain_k]) continue;
        visited[x][y][remain_k] = true;

        std::vector<std::vector<int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        for (const auto &dir : directions) {
            int nx = x + dir[0];
            int ny = y + dir[1];

            if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
                if (grid[nx][ny] == 1 && remain_k > 0) {
                    q.push({nx, ny, step + 1, remain_k - 1});
                } else if (grid[nx][ny] == 0) {
                    q.push({nx, ny, step + 1, remain_k});
                }
            }
        }
    }

    return -1;
}
```
We use Breadth-First Search (BFS) algorithm to explore the grid. We maintain a queue to store the current status of the cell (x, y, step) as well as the remaining obstacles that we can eliminate (remaining_k). We initialize the queue with (0, 0, 0, k).

We then iterate through the queue until it's empty, in each iteration we pop the front element and check if we reach the bottom-right corner (m-1, n-1). If yes, we return the number of steps. If not, we mark the cell as visited and try to explore the neighbors in all four directions (up, down, left, right). If the neighbor cell has an obstacle and we have remaining_k > 0, we can eliminate the obstacle and add the neighbor cell into the queue with its new status. If the neighbor cell has no obstacle, we can simply add it to the queue.

After the iteration through the queue, if we haven't found a valid path to (m-1, n-1), we return -1.

The time complexity of this algorithm is O(m * n * k) because we potentially need to traverse all m * n cells, multiplied by k because we are keeping track of k states at each cell.

## A solution in Python

```python
from collections import deque

def shortestPath(grid, k):
    m, n = len(grid), len(grid[0])
    queue = deque([(0, 0, 0, k)])
    visited = [[[False] * (k + 1) for _ in range(n)] for _ in range(m)]

    while queue:
        x, y, step, remaining_k = queue.popleft()

        if x == m - 1 and y == n - 1:
            return step
        if visited[x][y][remaining_k]:
            continue
        visited[x][y][remaining_k] = True

        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

        for dx, dy in directions:
            nx, ny = x + dx, y + dy

            if 0 <= nx < m and 0 <= ny < n:
                if grid[nx][ny] == 1 and remaining_k > 0:
                    queue.append((nx, ny, step + 1, remaining_k - 1))
                elif grid[nx][ny] == 0:
                    queue.append((nx, ny, step + 1, remaining_k))

    return -1
```
We use Breadth-First Search (BFS) algorithm to explore the grid. We maintain a queue to store the current status of the cell (x, y, step) as well as the remaining obstacles that we can eliminate (remaining_k). We initialize the queue with (0, 0, 0, k).

We then iterate through the queue until it's empty, in each iteration we pop the front element and check if we reach the bottom-right corner (m-1, n-1). If yes, we return the number of steps. If not, we mark the cell as visited and try to explore the neighbors in all four directions (up, down, left, right). If the neighbor cell has an obstacle and we have remaining_k > 0, we can eliminate the obstacle and add the neighbor cell into the queue with its new status. If the neighbor cell has no obstacle, we can simply add it to the queue.

After the iteration through the queue, if we haven't found a valid path to (m-1, n-1), we return -1.

The time complexity of this algorithm is O(m * n * k) because we potentially need to traverse all m * n cells, multiplied by k because we are keeping track of k states at each cell.

## A solution in Javascript

```javascript
function shortestPath(grid, k) {
    const m = grid.length;
    const n = grid[0].length;
    const queue = [[0, 0, 0, k]];
    const visited = new Array(m).fill(null).map(() => new Array(n).fill(null).map(() => new Array(k + 1).fill(false)));

    while (queue.length) {
        const [x, y, step, remainingK] = queue.shift();

        if (x === m - 1 && y === n - 1) return step;
        if (visited[x][y][remainingK]) continue;
        visited[x][y][remainingK] = true;

        const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];

        for (const [dx, dy] of directions) {
            const nx = x + dx;
            const ny = y + dy;

            if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
                if (grid[nx][ny] === 1 && remainingK > 0) {
                    queue.push([nx, ny, step + 1, remainingK - 1]);
                } else if (grid[nx][ny] === 0) {
                    queue.push([nx, ny, step + 1, remainingK]);
                }
            }
        }
    }

    return -1;
}
```
We use Breadth-First Search (BFS) algorithm to explore the grid. We maintain a queue to store the current status of the cell (x, y, step) as well as the remaining obstacles that we can eliminate (remaining_k). We initialize the queue with (0, 0, 0, k).

We then iterate through the queue until it's empty, in each iteration we pop the front element and check if we reach the bottom-right corner (m-1, n-1). If yes, we return the number of steps. If not, we mark the cell as visited and try to explore the neighbors in all four directions (up, down, left, right). If the neighbor cell has an obstacle and we have remaining_k > 0, we can eliminate the obstacle and add the neighbor cell into the queue with its new status. If the neighbor cell has no obstacle, we can simply add it to the queue.

After the iteration through the queue, if we haven't found a valid path to (m-1, n-1), we return -1.

The time complexity of this algorithm is O(m * n * k) because we potentially need to traverse all m * n cells, multiplied by k because we are keeping track of k states at each cell.


# The k-th Lexicographical String of All Happy Strings of Length n

- slug: the-k-th-lexicographical-string-of-all-happy-strings-of-length-n
- difficulty: Medium

A **happy string** is a string that:

*   consists only of letters of the set `['a', 'b', 'c']`.
*   `s[i] != s[i + 1]` for all values of `i` from `1` to `s.length - 1` (string is 1-indexed).

For example, strings **"abc ", "ac ", "b "** and **"abcbabcbcb "** are all happy strings and strings **"aa ", "baa "** and **"ababbc "** are not happy strings.

Given two integers `n` and `k`, consider a list of all happy strings of length `n` sorted in lexicographical order.

Return _the kth string_ of this list or return an **empty string** if there are less than `k` happy strings of length `n`.

**Example 1:**

**Input:** n = 1, k = 3
**Output:**  "c "
**Explanation:** The list \[ "a ",  "b ",  "c "\] contains all happy strings of length 1. The third string is  "c ".

**Example 2:**

**Input:** n = 1, k = 4
**Output:**  " "
**Explanation:** There are only 3 happy strings of length 1.

**Example 3:**

**Input:** n = 3, k = 9
**Output:**  "cab "
**Explanation:** There are 12 different happy string of length 3 \[ "aba ",  "abc ",  "aca ",  "acb ",  "bab ",  "bac ",  "bca ",  "bcb ",  "cab ",  "cac ",  "cba ",  "cbc "\]. You will find the 9th string =  "cab "

**Constraints:**

*   `1 <= n <= 10`
*   `1 <= k <= 100`

## A solution in Java

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

class Solution {
    public void generateStrings(int n, StringBuilder current, List<String> strings) {
        if (n == 0) {
            strings.add(current.toString());
            return;
        }
        for (char c = 'a'; c <= 'c'; ++c) {
            if (current.length() == 0 || current.charAt(current.length() - 1) != c) {
                current.append(c);
                generateStrings(n - 1, current, strings);
                current.deleteCharAt(current.length() - 1);
            }
        }
    }

    public String getHappyString(int n, int k) {
        List<String> strings = new ArrayList<>();
        StringBuilder current = new StringBuilder();
        generateStrings(n, current, strings);
        return k <= strings.size() ? strings.get(k - 1) : "";
    }
}
```
We can create all the happy strings of length `n` by iterating through `'a'`, `'b'`, and `'c'`, and recursively generating the happy strings for the remaining length. During the process, we can ensure that the string remains valid by checking that the last letter appended does not equal the one being appended. Once our recursion reaches length 0, push this valid string into a list of strings.

Finally, after generating all possible happy strings, we simply need to find the kth string in the list. If `k` is larger than the list's length, we return an empty string.

This algorithm will work for the given constraint where n is at most 10.

## A solution in C++

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

using namespace std;

class Solution {
public:
    void generate_strings(int n, string& current, vector<string>& strings) {
        if (n == 0) {
            strings.push_back(current);
            return;
        }
        for (char c = 'a'; c <= 'c'; ++c) {
            if (current.empty() || current.back() != c) {
                current.push_back(c);
                generate_strings(n - 1, current, strings);
                current.pop_back();
            }
        }
    }

    string getHappyString(int n, int k) {
        vector<string> strings;
        string current = "";
        generate_strings(n, current, strings);
        return k <= strings.size() ? strings[k - 1] : "";
    }
};
```
We can create all the happy strings of length `n` by iterating through `'a'`, `'b'`, and `'c'`, and recursively generating the happy strings for the remaining length. During the process, we can ensure that the string remains valid by checking that the last letter appended does not equal the one being appended. Once our recursion reaches length 0, push this valid string into a list of strings.

Finally, after generating all possible happy strings, we simply need to find the kth string in the list. If `k` is larger than the list's length, we return an empty string.

This algorithm will work for the given constraint where n is at most 10.

## A solution in Python

```python
class Solution:
    def generate_strings(self, n: int, current: str, strings: list) -> None:
        if n == 0:
            strings.append(current)
            return
        for c in "abc":
            if not current or current[-1] != c:
                self.generate_strings(n - 1, current + c, strings)

    def getHappyString(self, n: int, k: int) -> str:
        strings = []
        self.generate_strings(n, "", strings)
        return strings[k - 1] if k <= len(strings) else ""
```
We can create all the happy strings of length `n` by iterating through `'a'`, `'b'`, and `'c'`, and recursively generating the happy strings for the remaining length. During the process, we can ensure that the string remains valid by checking that the last letter appended does not equal the one being appended. Once our recursion reaches length 0, push this valid string into a list of strings.

Finally, after generating all possible happy strings, we simply need to find the kth string in the list. If `k` is larger than the list's length, we return an empty string.

This algorithm will work for the given constraint where n is at most 10.

## A solution in Javascript

```javascript
class Solution {
    generateStrings(n, current, strings) {
        if (n === 0) {
            strings.push(current);
            return;
        }
        for (let c of 'abc') {
            if (!current || current[current.length - 1] !== c) {
                this.generateStrings(n - 1, current + c, strings);
            }
        }
    }

    getHappyString(n, k) {
        let strings = [];
        this.generateStrings(n, '', strings);
        return k <= strings.length ? strings[k - 1] : '';
    }
}
```
We can create all the happy strings of length `n` by iterating through `'a'`, `'b'`, and `'c'`, and recursively generating the happy strings for the remaining length. During the process, we can ensure that the string remains valid by checking that the last letter appended does not equal the one being appended. Once our recursion reaches length 0, push this valid string into a list of strings.

Finally, after generating all possible happy strings, we simply need to find the kth string in the list. If `k` is larger than the list's length, we return an empty string.

This algorithm will work for the given constraint where n is at most 10.


# Restore The Array

- slug: restore-the-array
- difficulty: Hard

A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits `s` and all we know is that all integers in the array were in the range `[1, k]` and there are no leading zeros in the array.

Given the string `s` and the integer `k`, return _the number of the possible arrays that can be printed as_ `s` _using the mentioned program_. Since the answer may be very large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** s =  "1000 ", k = 10000
**Output:** 1
**Explanation:** The only possible array is \[1000\]

**Example 2:**

**Input:** s =  "1000 ", k = 10
**Output:** 0
**Explanation:** There cannot be an array that was printed this way and has all integer >= 1 and <= 10.

**Example 3:**

**Input:** s =  "1317 ", k = 2000
**Output:** 8
**Explanation:** Possible arrays are \[1317\],\[131,7\],\[13,17\],\[1,317\],\[13,1,7\],\[1,31,7\],\[1,3,17\],\[1,3,1,7\]

**Constraints:**

*   `1 <= s.length <= 105`
*   `s` consists of only digits and does not contain leading zeros.
*   `1 <= k <= 109`

## A solution in Java

```java
public int numDecodings(String s, int k) {
    int n = s.length();
    int[] dp = new int[n + 1];
    dp[n] = 1;
    int MOD = 1000000007;

    for (int i = n - 1; i >= 0; i--) {
        long num = 0;
        for (int j = i; j < n && num <= k; j++) {
            num = num * 10 + s.charAt(j) - '0';
            if (num >= 1 && num <= k) {
                dp[i] = (dp[i] + dp[j + 1]) % MOD;
            }
        }
    }
    return dp[0];
}
```
The algorithm uses dynamic programming approach to solve the problem. We define a `dp` array of length `n + 1`, where `n` is the length of the input string `s`. The last element `dp[n]` is set to 1. Then we move backwards through the `s` string, and for each digit, calculate the possible number of decodings.

We iterate from position `i` to `j`, creating a number using the digits from `i` to `j`. If the number falls within the range `[1, k]`, it is a valid number and we add the number of ways of decoding the string from position `j+1` to the current numDecodings count for position `i`. If the number becomes greater than `k`, we break the inner loop.

Finally, the first element of the `dp` array (`dp[0]`) contains the result, which is the number of possible arrays that can be printed from string `s`.

## A solution in C++

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

const int MOD = 1e9 + 7;

int numDecodings(std::string s, int k) {
    int n = s.size();
    std::vector<int> dp(n + 1, 0);
    dp[n] = 1;

    for (int i = n - 1; i >= 0; i--) {
        long num = 0;
        for (int j = i; j < n && num <= k; j++) {
            num = num * 10 + s[j] - '0';
            if (num >= 1 && num <= k) {
                dp[i] = (dp[i] + dp[j + 1]) % MOD;
            }
        }
    }
    return dp[0];
}
```
The algorithm uses dynamic programming approach to solve the problem. We define a `dp` array of length `n + 1`, where `n` is the length of the input string `s`. The last element `dp[n]` is set to 1. Then we move backwards through the `s` string, and for each digit, calculate the possible number of decodings.

We iterate from position `i` to `j`, creating a number using the digits from `i` to `j`. If the number falls within the range `[1, k]`, it is a valid number and we add the number of ways of decoding the string from position `j+1` to the current numDecodings count for position `i`. If the number becomes greater than `k`, we break the inner loop.

Finally, the first element of the `dp` array (`dp[0]`) contains the result, which is the number of possible arrays that can be printed from string `s`.

## A solution in Python

```python
def numDecodings(s: str, k: int) -> int:
    n = len(s)
    dp = [0] * (n + 1)
    dp[n] = 1
    MOD = 1000000007

    for i in range(n - 1, -1, -1):
        num = 0
        for j in range(i, n):
            num = num * 10 + int(s[j])
            if num >= 1 and num <= k:
                dp[i] = (dp[i] + dp[j + 1]) % MOD
            if num > k:
                break

    return dp[0]
```
The algorithm uses dynamic programming approach to solve the problem. We define a `dp` array of length `n + 1`, where `n` is the length of the input string `s`. The last element `dp[n]` is set to 1. Then we move backwards through the `s` string, and for each digit, calculate the possible number of decodings.

We iterate from position `i` to `j`, creating a number using the digits from `i` to `j`. If the number falls within the range `[1, k]`, it is a valid number and we add the number of ways of decoding the string from position `j+1` to the current numDecodings count for position `i`. If the number becomes greater than `k`, we break the inner loop.

Finally, the first element of the `dp` array (`dp[0]`) contains the result, which is the number of possible arrays that can be printed from string `s`.

## A solution in Javascript

```javascript
function numDecodings(s, k) {
    const n = s.length;
    const dp = new Array(n + 1).fill(0);
    dp[n] = 1;
    const MOD = 1000000007;

    for (let i = n - 1; i >= 0; i--) {
        let num = 0;
        for (let j = i; j < n && num <= k; j++) {
            num = num * 10 + parseInt(s[j]);
            if (num >= 1 && num <= k) {
                dp[i] = (dp[i] + dp[j + 1]) % MOD;
            }
        }
    }

    return dp[0];
}
```
The algorithm uses dynamic programming approach to solve the problem. We define a `dp` array of length `n + 1`, where `n` is the length of the input string `s`. The last element `dp[n]` is set to 1. Then we move backwards through the `s` string, and for each digit, calculate the possible number of decodings.

We iterate from position `i` to `j`, creating a number using the digits from `i` to `j`. If the number falls within the range `[1, k]`, it is a valid number and we add the number of ways of decoding the string from position `j+1` to the current numDecodings count for position `i`. If the number becomes greater than `k`, we break the inner loop.

Finally, the first element of the `dp` array (`dp[0]`) contains the result, which is the number of possible arrays that can be printed from string `s`.


# Reformat The String

- slug: reformat-the-string
- difficulty: Easy

You are given an alphanumeric string `s`. (**Alphanumeric string** is a string consisting of lowercase English letters and digits).

You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.

Return _the reformatted string_ or return **an empty string** if it is impossible to reformat the string.

**Example 1:**

**Input:** s =  "a0b1c2 "
**Output:**  "0a1b2c "
**Explanation:** No two adjacent characters have the same type in  "0a1b2c ".  "a0b1c2 ",  "0a1b2c ",  "0c2a1b " are also valid permutations.

**Example 2:**

**Input:** s =  "leetcode "
**Output:**  " "
**Explanation:**  "leetcode " has only characters so we cannot separate them by digits.

**Example 3:**

**Input:** s =  "1229857369 "
**Output:**  " "
**Explanation:**  "1229857369 " has only digits so we cannot separate them by characters.

**Constraints:**

*   `1 <= s.length <= 500`
*   `s` consists of only lowercase English letters and/or digits.

## A solution in Java

```java
import java.util.LinkedList;
import java.util.Queue;

public String reformat(String s) {
    Queue<Character> letters = new LinkedList<>();
    Queue<Character> digits = new LinkedList<>();

    for (char c : s.toCharArray()) {
        if (Character.isLetter(c)) letters.add(c);
        else digits.add(c);
    }

    if (Math.abs(letters.size() - digits.size()) > 1) return "";

    StringBuilder result = new StringBuilder();
    boolean useLetter = letters.size() > digits.size();

    while (!letters.isEmpty() || !digits.isEmpty()) {
        if (useLetter) {
            result.append(letters.poll());
        } else {
            result.append(digits.poll());
        }
        useLetter = !useLetter;
    }

    return result.toString();
}
```
The algorithm first separates the input string `s` into two queues, `letters` and `digits`. This can be done by iterating through the input string `s` and checking if each character is a letter or digit. Then it checks if the difference between the number of letters and digits is greater than 1. If so, it returns an empty string as it is impossible to reformat the string with no two adjacent characters having the same type.

If the difference is not greater than 1, the algorithm initializes an empty result string or list. Then, it checks which type (letter or digit) has more elements, and iterates through the queues, alternating between types (letters and digits) and inserting the next character of the current type into the result. This ensures no two adjacent characters have the same type. Finally, the algorithm returns the result in the appropriate type (string or list, depending on the language).

The algorithm's complexity is O(n), where n is the length of the input string `s`.

## A solution in C++

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

std::string reformat(std::string s) {
    std::queue<char> letters, digits;

    for (char c : s) {
        if (isalpha(c)) letters.push(c);
        else digits.push(c);
    }

    if (abs((int)(letters.size() - digits.size())) > 1) return "";

    std::string result = "";
    bool use_letter = letters.size() > digits.size();

    while (!letters.empty() || !digits.empty()) {
        if (use_letter) {
            result += letters.front();
            letters.pop();
        } else {
            result += digits.front();
            digits.pop();
        }
        use_letter = !use_letter;
    }

    return result;
}
```
The algorithm first separates the input string `s` into two queues, `letters` and `digits`. This can be done by iterating through the input string `s` and checking if each character is a letter or digit. Then it checks if the difference between the number of letters and digits is greater than 1. If so, it returns an empty string as it is impossible to reformat the string with no two adjacent characters having the same type.

If the difference is not greater than 1, the algorithm initializes an empty result string or list. Then, it checks which type (letter or digit) has more elements, and iterates through the queues, alternating between types (letters and digits) and inserting the next character of the current type into the result. This ensures no two adjacent characters have the same type. Finally, the algorithm returns the result in the appropriate type (string or list, depending on the language).

The algorithm's complexity is O(n), where n is the length of the input string `s`.

## A solution in Python

```python
from collections import deque

def reformat(s: str) -> str:
    letters, digits = deque(), deque()

    for c in s:
        if c.isalpha():
            letters.append(c)
        else:
            digits.append(c)

    if abs(len(letters) - len(digits)) > 1:
        return ""

    result = []
    use_letter = len(letters) > len(digits)

    while letters or digits:
        if use_letter:
            result.append(letters.popleft())
        else:
            result.append(digits.popleft())
        use_letter = not use_letter

    return ''.join(result)
```
The algorithm first separates the input string `s` into two queues, `letters` and `digits`. This can be done by iterating through the input string `s` and checking if each character is a letter or digit. Then it checks if the difference between the number of letters and digits is greater than 1. If so, it returns an empty string as it is impossible to reformat the string with no two adjacent characters having the same type.

If the difference is not greater than 1, the algorithm initializes an empty result string or list. Then, it checks which type (letter or digit) has more elements, and iterates through the queues, alternating between types (letters and digits) and inserting the next character of the current type into the result. This ensures no two adjacent characters have the same type. Finally, the algorithm returns the result in the appropriate type (string or list, depending on the language).

The algorithm's complexity is O(n), where n is the length of the input string `s`.

## A solution in Javascript

```javascript
function reformat(s) {
    const letters = [], digits = [];

    for (const c of s) {
        if (c.charCodeAt(0) > 57) letters.push(c);
        else digits.push(c);
    }

    if (Math.abs(letters.length - digits.length) > 1) return "";

    let result = "";
    let useLetter = letters.length > digits.length;

    while (letters.length || digits.length) {
        if (useLetter) {
            result += letters.shift();
        } else {
            result += digits.shift();
        }
        useLetter = !useLetter;
    }

    return result;
}
```
The algorithm first separates the input string `s` into two queues, `letters` and `digits`. This can be done by iterating through the input string `s` and checking if each character is a letter or digit. Then it checks if the difference between the number of letters and digits is greater than 1. If so, it returns an empty string as it is impossible to reformat the string with no two adjacent characters having the same type.

If the difference is not greater than 1, the algorithm initializes an empty result string or list. Then, it checks which type (letter or digit) has more elements, and iterates through the queues, alternating between types (letters and digits) and inserting the next character of the current type into the result. This ensures no two adjacent characters have the same type. Finally, the algorithm returns the result in the appropriate type (string or list, depending on the language).

The algorithm's complexity is O(n), where n is the length of the input string `s`.


# Display Table of Food Orders in a Restaurant

- slug: display-table-of-food-orders-in-a-restaurant
- difficulty: Medium

Given the array `orders`, which represents the orders that customers have done in a restaurant. More specifically `orders[i]=[customerNamei,tableNumberi,foodItemi]` where `customerNamei` is the name of the customer, `tableNumberi` is the table customer sit at, and `foodItemi` is the item customer orders.

_Return the restaurant's "**display table**"_. The "**display table**" is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is "Table", followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.

**Example 1:**

**Input:** orders = \[\[ "David ", "3 ", "Ceviche "\],\[ "Corina ", "10 ", "Beef Burrito "\],\[ "David ", "3 ", "Fried Chicken "\],\[ "Carla ", "5 ", "Water "\],\[ "Carla ", "5 ", "Ceviche "\],\[ "Rous ", "3 ", "Ceviche "\]\]
**Output:** \[\[ "Table ", "Beef Burrito ", "Ceviche ", "Fried Chicken ", "Water "\],\[ "3 ", "0 ", "2 ", "1 ", "0 "\],\[ "5 ", "0 ", "1 ", "0 ", "1 "\],\[ "10 ", "1 ", "0 ", "0 ", "0 "\]\]
**Explanation:**
The displaying table looks like:
**Table,Beef Burrito,Ceviche,Fried Chicken,Water**
3    ,0           ,2      ,1            ,0
5    ,0           ,1      ,0            ,1
10   ,1           ,0      ,0            ,0
For the table 3: David orders  "Ceviche " and  "Fried Chicken ", and Rous orders  "Ceviche ".
For the table 5: Carla orders  "Water " and  "Ceviche ".
For the table 10: Corina orders  "Beef Burrito ".

**Example 2:**

**Input:** orders = \[\[ "James ", "12 ", "Fried Chicken "\],\[ "Ratesh ", "12 ", "Fried Chicken "\],\[ "Amadeus ", "12 ", "Fried Chicken "\],\[ "Adam ", "1 ", "Canadian Waffles "\],\[ "Brianna ", "1 ", "Canadian Waffles "\]\]
**Output:** \[\[ "Table ", "Canadian Waffles ", "Fried Chicken "\],\[ "1 ", "2 ", "0 "\],\[ "12 ", "0 ", "3 "\]\]
**Explanation:**
For the table 1: Adam and Brianna order  "Canadian Waffles ".
For the table 12: James, Ratesh and Amadeus order  "Fried Chicken ".

**Example 3:**

**Input:** orders = \[\[ "Laura ", "2 ", "Bean Burrito "\],\[ "Jhon ", "2 ", "Beef Burrito "\],\[ "Melissa ", "2 ", "Soda "\]\]
**Output:** \[\[ "Table ", "Bean Burrito ", "Beef Burrito ", "Soda "\],\[ "2 ", "1 ", "1 ", "1 "\]\]

**Constraints:**

*   `1 <= orders.length <= 5 * 10^4`
*   `orders[i].length == 3`
*   `1 <= customerNamei.length, foodItemi.length <= 20`
*   `customerNamei` and `foodItemi` consist of lowercase and uppercase English letters and the space character.
*   `tableNumberi` is a valid integer between `1` and `500`.

## A solution in Java

```java
import java.util.*;

public List<List<String>> displayTable(List<List<String>> orders) {
    TreeMap<Integer, TreeMap<String, Integer>> tables = new TreeMap<>();
    TreeSet<String> foodSet = new TreeSet<>();

    for (List<String> order : orders) {
        int tableNumber = Integer.parseInt(order.get(1));
        String foodItem = order.get(2);
        tables.putIfAbsent(tableNumber, new TreeMap<>());
        tables.get(tableNumber).put(foodItem, tables.get(tableNumber).getOrDefault(foodItem, 0) + 1);
        foodSet.add(foodItem);
    }

    List<List<String>> result = new ArrayList<>();
    List<String> header = new ArrayList<>();
    header.add("Table");
    header.addAll(foodSet);
    result.add(header);

    for (Map.Entry<Integer, TreeMap<String, Integer>> table : tables.entrySet()) {
        List<String> row = new ArrayList<>();
        row.add(Integer.toString(table.getKey()));
        for (String foodItem : foodSet) {
            row.add(Integer.toString(table.getValue().getOrDefault(foodItem, 0)));
        }
        result.add(row);
    }

    return result;
}
```
1. Create a nested dictionary/map for each table and a set to store unique food items.
2. Loop through each order, store the count of the food item in the nested dictionary/map and update foodSet with foodItem.
3. Sort the foodSet and create the header row.
4. For each table, create a row with tableNumber and food items count.
5. Append the row to the result list.
6. Return the result list.

## A solution in C++

```cpp
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>

std::vector<std::vector<std::string>> displayTable(std::vector<std::vector<std::string>>& orders) {
    std::map<int, std::map<std::string, int>> tables;
    std::set<std::string> foodSet;

    for (auto& order : orders) {
        int tableNumber = std::stoi(order[1]);
        std::string foodItem = order[2];
        tables[tableNumber][foodItem]++;
        foodSet.insert(foodItem);
    }

    std::vector<std::vector<std::string>> result;
    std::vector<std::string> header = {"Table"};
    header.insert(header.end(), foodSet.begin(), foodSet.end());
    result.push_back(header);

    for (auto& table : tables) {
        std::vector<std::string> row = {std::to_string(table.first)};
        for (const auto& foodItem : foodSet) {
            row.push_back(std::to_string(table.second[foodItem]));
        }
        result.push_back(row);
    }

    return result;
}
```
1. Create a nested dictionary/map for each table and a set to store unique food items.
2. Loop through each order, store the count of the food item in the nested dictionary/map and update foodSet with foodItem.
3. Sort the foodSet and create the header row.
4. For each table, create a row with tableNumber and food items count.
5. Append the row to the result list.
6. Return the result list.

## A solution in Python

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

def displayTable(orders: List[List[str]]) -> List[List[str]]:
    tables = defaultdict(lambda: defaultdict(int))
    foodSet = set()

    for order in orders:
        tableNumber = int(order[1])
        foodItem = order[2]
        tables[tableNumber][foodItem] += 1
        foodSet.add(foodItem)

    foodList = sorted(foodSet)
    result = [["Table"] + foodList]

    for tableNumber, table in sorted(tables.items()):
        row = [str(tableNumber)]
        row.extend(str(table[foodItem]) for foodItem in foodList)
        result.append(row)

    return result
```
1. Create a nested dictionary/map for each table and a set to store unique food items.
2. Loop through each order, store the count of the food item in the nested dictionary/map and update foodSet with foodItem.
3. Sort the foodSet and create the header row.
4. For each table, create a row with tableNumber and food items count.
5. Append the row to the result list.
6. Return the result list.

## A solution in Javascript

```javascript
function displayTable(orders) {
    const tables = new Map();
    const foodSet = new Set();

    for (const order of orders) {
        const tableNumber = parseInt(order[1]);
        const foodItem = order[2];
        if (!tables.has(tableNumber)) tables.set(tableNumber, new Map());
        const table = tables.get(tableNumber);
        table.set(foodItem, (table.get(foodItem) || 0) + 1);
        foodSet.add(foodItem);
    }

    const foodList = [...foodSet].sort();
    const result = [["Table", ...foodList]];

    for (const [tableNumber, table] of [...tables.entries()].sort((a, b) => a[0] - b[0])) {
        const row = [tableNumber.toString()];
        row.push(...foodList.map(foodItem => (table.get(foodItem) || 0).toString()));
        result.push(row);
    }

    return result;
}
```
1. Create a nested dictionary/map for each table and a set to store unique food items.
2. Loop through each order, store the count of the food item in the nested dictionary/map and update foodSet with foodItem.
3. Sort the foodSet and create the header row.
4. For each table, create a row with tableNumber and food items count.
5. Append the row to the result list.
6. Return the result list.


# Minimum Number of Frogs Croaking

- slug: minimum-number-of-frogs-croaking
- difficulty: Medium

You are given the string `croakOfFrogs`, which represents a combination of the string `"croak "` from different frogs, that is, multiple frogs can croak at the same time, so multiple `"croak "` are mixed.

_Return the minimum number of_ different _frogs to finish all the croaks in the given string._

A valid `"croak "` means a frog is printing five letters `'c'`, `'r'`, `'o'`, `'a'`, and `'k'` **sequentially**. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid `"croak "` return `-1`.

**Example 1:**

**Input:** croakOfFrogs =  "croakcroak "
**Output:** 1
**Explanation:** One frog yelling  "croak **"** twice.

**Example 2:**

**Input:** croakOfFrogs =  "crcoakroak "
**Output:** 2
**Explanation:** The minimum number of frogs is two.
The first frog could yell  "**cr**c**oak**roak ".
The second frog could yell later  "cr**c**oak**roak** ".

**Example 3:**

**Input:** croakOfFrogs =  "croakcrook "
**Output:** -1
**Explanation:** The given string is an invalid combination of  "croak **"** from different frogs.

**Constraints:**

*   `1 <= croakOfFrogs.length <= 105`
*   `croakOfFrogs` is either `'c'`, `'r'`, `'o'`, `'a'`, or `'k'`.

## A solution in Java

```java
public int minNumberOfFrogs(String croakOfFrogs) {
    int[] counter = new int[5];
    int frogs = 0, max_frogs = 0;
    for (char ch : croakOfFrogs.toCharArray()) {
        int idx = "croak".indexOf(ch);
        counter[idx]++;
        if (idx == 0) {
            max_frogs = Math.max(max_frogs, ++frogs);
        } else if (--counter[idx - 1] < 0) {
            return -1;
        } else if (idx == 4) {
            frogs--;
        }
    }
    return (counter[0] == counter[1] && counter[1] == counter[2] && counter[2] == counter[3] && counter[3] == counter[4]) ? max_frogs : -1;
}
```
We create an array called `counter` to keep track of the count of each character 'c', 'r', 'o', 'a', and 'k' in the given `croakOfFrogs` string. Initialize `frogs` and `max_frogs` to 0. We loop through each character in `croakOfFrogs`, find its index in the string "croak", and increment the corresponding index in the `counter` array.

If the character index is 0 (meaning it's 'c'), we increment the number of `frogs` and update `max_frogs`. If the character index is not 0, we decrement the previous index count in `counter`. If the decremented value is less than 0, that means the given sequence is not a valid "croak", and we return -1. If the character index is 4 (meaning it's 'k'), we decrement the number of `frogs` as the frog has finished croaking.

Finally, after the loop, if all the counts in `counter` are equal, it means the sequence in `croakOfFrogs` is a valid combination of multiple "croak" sequences, and we can return the value of `max_frogs`. Otherwise, we return -1 as the sequence is invalid.

## A solution in C++

```cpp
int minNumberOfFrogs(string croakOfFrogs) {
    int counter[5] = {0};
    int frogs = 0, max_frogs = 0;
    for (char ch : croakOfFrogs) {
        int idx = string("croak").find(ch);
        counter[idx]++;
        if (idx == 0) {
            max_frogs = max(max_frogs, ++frogs);
        } else if (--counter[idx - 1] < 0) {
            return -1;
        } else if (idx == 4) {
            frogs--;
        }
    }
    return (counter[0] == counter[1] && counter[1] == counter[2] && counter[2] == counter[3] && counter[3] == counter[4]) ? max_frogs : -1;
}
```
We create an array called `counter` to keep track of the count of each character 'c', 'r', 'o', 'a', and 'k' in the given `croakOfFrogs` string. Initialize `frogs` and `max_frogs` to 0. We loop through each character in `croakOfFrogs`, find its index in the string "croak", and increment the corresponding index in the `counter` array.

If the character index is 0 (meaning it's 'c'), we increment the number of `frogs` and update `max_frogs`. If the character index is not 0, we decrement the previous index count in `counter`. If the decremented value is less than 0, that means the given sequence is not a valid "croak", and we return -1. If the character index is 4 (meaning it's 'k'), we decrement the number of `frogs` as the frog has finished croaking.

Finally, after the loop, if all the counts in `counter` are equal, it means the sequence in `croakOfFrogs` is a valid combination of multiple "croak" sequences, and we can return the value of `max_frogs`. Otherwise, we return -1 as the sequence is invalid.

## A solution in Python

```python
def minNumberOfFrogs(croakOfFrogs: str) -> int:
    counter = [0] * 5
    frogs = max_frogs = 0
    for ch in croakOfFrogs:
        idx = 'croak'.index(ch)
        counter[idx] += 1
        if idx == 0:
            max_frogs = max(max_frogs, frogs + 1)
            frogs += 1
        else:
            counter[idx - 1] -= 1
            if counter[idx - 1] < 0:
                return -1
            if idx == 4:
                frogs -= 1
    return max_frogs if all(count == counter[0] for count in counter) else -1
```
We create an array called `counter` to keep track of the count of each character 'c', 'r', 'o', 'a', and 'k' in the given `croakOfFrogs` string. Initialize `frogs` and `max_frogs` to 0. We loop through each character in `croakOfFrogs`, find its index in the string "croak", and increment the corresponding index in the `counter` array.

If the character index is 0 (meaning it's 'c'), we increment the number of `frogs` and update `max_frogs`. If the character index is not 0, we decrement the previous index count in `counter`. If the decremented value is less than 0, that means the given sequence is not a valid "croak", and we return -1. If the character index is 4 (meaning it's 'k'), we decrement the number of `frogs` as the frog has finished croaking.

Finally, after the loop, if all the counts in `counter` are equal, it means the sequence in `croakOfFrogs` is a valid combination of multiple "croak" sequences, and we can return the value of `max_frogs`. Otherwise, we return -1 as the sequence is invalid.

## A solution in Javascript

```javascript
var minNumberOfFrogs = function(croakOfFrogs) {
    let counter = new Array(5).fill(0);
    let frogs = 0, max_frogs = 0;
    for (const ch of croakOfFrogs) {
        let idx = "croak".indexOf(ch);
        counter[idx]++;
        if (idx === 0) {
            max_frogs = Math.max(max_frogs, ++frogs);
        } else if (--counter[idx - 1] < 0) {
            return -1;
        } else if (idx === 4) {
            frogs--;
        }
    }
    return (counter[0] === counter[1] && counter[1] === counter[2] && counter[2] === counter[3] && counter[3] === counter[4]) ? max_frogs : -1;
};
```
We create an array called `counter` to keep track of the count of each character 'c', 'r', 'o', 'a', and 'k' in the given `croakOfFrogs` string. Initialize `frogs` and `max_frogs` to 0. We loop through each character in `croakOfFrogs`, find its index in the string "croak", and increment the corresponding index in the `counter` array.

If the character index is 0 (meaning it's 'c'), we increment the number of `frogs` and update `max_frogs`. If the character index is not 0, we decrement the previous index count in `counter`. If the decremented value is less than 0, that means the given sequence is not a valid "croak", and we return -1. If the character index is 4 (meaning it's 'k'), we decrement the number of `frogs` as the frog has finished croaking.

Finally, after the loop, if all the counts in `counter` are equal, it means the sequence in `croakOfFrogs` is a valid combination of multiple "croak" sequences, and we can return the value of `max_frogs`. Otherwise, we return -1 as the sequence is invalid.


# Build Array Where You Can Find The Maximum Exactly K Comparisons

- slug: build-array-where-you-can-find-the-maximum-exactly-k-comparisons
- difficulty: Hard

You are given three integers `n`, `m` and `k`. Consider the following algorithm to find the maximum element of an array of positive integers:

You should build the array arr which has the following properties:

*   `arr` has exactly `n` integers.
*   `1 <= arr[i] <= m` where `(0 <= i < n)`.
*   After applying the mentioned algorithm to `arr`, the value `search_cost` is equal to `k`.

Return _the number of ways_ to build the array `arr` under the mentioned conditions. As the answer may grow large, the answer **must be** computed modulo `109 + 7`.

**Example 1:**

**Input:** n = 2, m = 3, k = 1
**Output:** 6
**Explanation:** The possible arrays are \[1, 1\], \[2, 1\], \[2, 2\], \[3, 1\], \[3, 2\] \[3, 3\]

**Example 2:**

**Input:** n = 5, m = 2, k = 3
**Output:** 0
**Explanation:** There are no possible arrays that satisify the mentioned conditions.

**Example 3:**

**Input:** n = 9, m = 1, k = 1
**Output:** 1
**Explanation:** The only possible array is \[1, 1, 1, 1, 1, 1, 1, 1, 1\]

**Constraints:**

*   `1 <= n <= 50`
*   `1 <= m <= 100`
*   `0 <= k <= n`

## A solution in Java

```java
public int waysToBuildArray(int n, int m, int k) {
    final int mod = 1000000007;
    int[][] dp = new int[n+1][k+1];
    dp[0][0] = 1;
    for (int i = 1; i <= n; ++i) {
        for (int j = 0; j <= k; ++j) {
            for (int x = 1; x <= m; ++x) {
                if (j < i * (x-1)) {
                    dp[i][j] = (dp[i][j] + dp[i-1][j-(i-1)*(x-1)]) % mod;
                }
            }
        }
    }
    return dp[n][k];
}
```
The goal is to find the number of ways to build an array with n elements that satisfy the given conditions.

Create an `n+1` by `k+1` 2D array named `dp`, and initializing `dp[0][0] = 1`.

Then, loop through `i` (1 to n) and `j` (0 to k) and for each `i` and `j`, loop through `x` (1 to m). For each `x`, if `j < i * (x-1)`, then update `dp[i][j]` as `(dp[i][j] + dp[i-1][j-(i-1)*(x-1)])` modulo the given constant (1e9 + 7).

At the end, return `dp[n][k]` as the result.

This will give you the number of ways to build the array with n elements while satisfying the given conditions.

## A solution in C++

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

int waysToBuildArray(int n, int m, int k) {
    const int mod = 1e9 + 7;
    vector<vector<int>> dp(n+1, vector<int>(k+1, 0));
    dp[0][0] = 1;
    for (int i = 1; i <= n; ++i) {
        for (int j = 0; j <= k; ++j) {
            for (int x = 1; x <= m; ++x) {
                if (j < i * (x-1)) {
                    dp[i][j] = (dp[i][j] + dp[i-1][j-(i-1)*(x-1)]) % mod;
                }
            }
        }
    }
    return dp[n][k];
}
```
The goal is to find the number of ways to build an array with n elements that satisfy the given conditions.

Create an `n+1` by `k+1` 2D array named `dp`, and initializing `dp[0][0] = 1`.

Then, loop through `i` (1 to n) and `j` (0 to k) and for each `i` and `j`, loop through `x` (1 to m). For each `x`, if `j < i * (x-1)`, then update `dp[i][j]` as `(dp[i][j] + dp[i-1][j-(i-1)*(x-1)])` modulo the given constant (1e9 + 7).

At the end, return `dp[n][k]` as the result.

This will give you the number of ways to build the array with n elements while satisfying the given conditions.

## A solution in Python

```python
def waysToBuildArray(n, m, k):
    mod = 10**9 + 7
    dp = [[0] * (k+1) for _ in range(n+1)]
    dp[0][0] = 1
    for i in range(1, n+1):
        for j in range(k+1):
            for x in range(1, m+1):
                if j < i * (x-1):
                    dp[i][j] = (dp[i][j] + dp[i-1][j-(i-1)*(x-1)]) % mod
    return dp[n][k]
```
The goal is to find the number of ways to build an array with n elements that satisfy the given conditions.

Create an `n+1` by `k+1` 2D array named `dp`, and initializing `dp[0][0] = 1`.

Then, loop through `i` (1 to n) and `j` (0 to k) and for each `i` and `j`, loop through `x` (1 to m). For each `x`, if `j < i * (x-1)`, then update `dp[i][j]` as `(dp[i][j] + dp[i-1][j-(i-1)*(x-1)])` modulo the given constant (1e9 + 7).

At the end, return `dp[n][k]` as the result.

This will give you the number of ways to build the array with n elements while satisfying the given conditions.

## A solution in Javascript

```javascript
function waysToBuildArray(n, m, k) {
    const mod = 1e9 + 7;
    const dp = Array.from({ length: n+1 }, () => Array(k+1).fill(0));
    dp[0][0] = 1;
    for (let i = 1; i <= n; ++i) {
        for (let j = 0; j <= k; ++j) {
            for (let x = 1; x <= m; ++x) {
                if (j < i * (x-1)) {
                    dp[i][j] = (dp[i][j] + dp[i-1][j-(i-1)*(x-1)]) % mod;
                }
            }
        }
    }
    return dp[n][k];
}
```
The goal is to find the number of ways to build an array with n elements that satisfy the given conditions.

Create an `n+1` by `k+1` 2D array named `dp`, and initializing `dp[0][0] = 1`.

Then, loop through `i` (1 to n) and `j` (0 to k) and for each `i` and `j`, loop through `x` (1 to m). For each `x`, if `j < i * (x-1)`, then update `dp[i][j]` as `(dp[i][j] + dp[i-1][j-(i-1)*(x-1)])` modulo the given constant (1e9 + 7).

At the end, return `dp[n][k]` as the result.

This will give you the number of ways to build the array with n elements while satisfying the given conditions.


# Maximum Score After Splitting a String

- slug: maximum-score-after-splitting-a-string
- difficulty: Easy

Given a string `s` of zeros and ones, _return the maximum score after splitting the string into two **non-empty** substrings_ (i.e. **left** substring and **right** substring).

The score after splitting a string is the number of **zeros** in the **left** substring plus the number of **ones** in the **right** substring.

**Example 1:**

**Input:** s =  "011101 "
**Output:** 5
**Explanation:**
All possible ways of splitting s into two non-empty substrings are:
left =  "0 " and right =  "11101 ", score = 1 + 4 = 5
left =  "01 " and right =  "1101 ", score = 1 + 3 = 4
left =  "011 " and right =  "101 ", score = 1 + 2 = 3
left =  "0111 " and right =  "01 ", score = 1 + 1 = 2
left =  "01110 " and right =  "1 ", score = 2 + 1 = 3

**Example 2:**

**Input:** s =  "00111 "
**Output:** 5
**Explanation:** When left =  "00 " and right =  "111 ", we get the maximum score = 2 + 3 = 5

**Example 3:**

**Input:** s =  "1111 "
**Output:** 3

**Constraints:**

*   `2 <= s.length <= 500`
*   The string `s` consists of characters `'0'` and `'1'` only.

## A solution in Java

```java
import java.util.TreeMap;

public boolean isPossibleDivide(int[] nums, int k) {
    TreeMap<Integer, Integer> counts = new TreeMap<>();
    for (int num : nums) counts.put(num, counts.getOrDefault(num, 0) + 1);

    for (int key : counts.keySet()) {
        if (counts.get(key) > 0) {
            for (int i = k - 1; i >= 0; --i) {
                if (!counts.containsKey(key + i) || counts.get(key + i) < counts.get(key)) return false;
                counts.put(key + i, counts.get(key + i) - counts.get(key));
            }
        }
    }

    return true;
}
```
1. Create a count map that counts the occurrences of each integer in the input array.
2. Iterate through the keys in ascending order.
3. For each key, if its value is greater than 0, try to find k-1 integers that are consecutive to the current integer.
4. While iterating the keys, check if the occurrences of all consecutive integers are equal to or greater than the occurrences of the current integer. If not, return false as it isn't possible to divide the array into sets of k consecutive numbers. If everything passes through, return true.

## A solution in C++

```cpp
#include <map>

bool isPossibleDivide(std::vector<int>& nums, int k) {
    std::map<int, int> counts;
    for (int num : nums) counts[num]++;

    for (auto it = counts.begin(); it != counts.end(); ++it) {
        if (it->second > 0) {
            for (int i = k - 1; i >= 0; --i) {
                if ((counts[it->first + i] -= it->second) < 0) return false;
            }
        }
    }

    return true;
}
```
1. Create a count map that counts the occurrences of each integer in the input array.
2. Iterate through the keys in ascending order.
3. For each key, if its value is greater than 0, try to find k-1 integers that are consecutive to the current integer.
4. While iterating the keys, check if the occurrences of all consecutive integers are equal to or greater than the occurrences of the current integer. If not, return false as it isn't possible to divide the array into sets of k consecutive numbers. If everything passes through, return true.

## A solution in Python

```python
from collections import Counter

def is_possible_divide(nums: List[int], k: int) -> bool:
    counts = Counter(nums)

    for key in sorted(counts):
        if counts[key] > 0:
            for i in range(k-1, -1, -1):
                if counts[key+i] < counts[key]:
                    return False
                counts[key+i] -= counts[key]

    return True
```
1. Create a count map that counts the occurrences of each integer in the input array.
2. Iterate through the keys in ascending order.
3. For each key, if its value is greater than 0, try to find k-1 integers that are consecutive to the current integer.
4. While iterating the keys, check if the occurrences of all consecutive integers are equal to or greater than the occurrences of the current integer. If not, return false as it isn't possible to divide the array into sets of k consecutive numbers. If everything passes through, return true.

## A solution in Javascript

```javascript
function isPossibleDivide(nums, k) {
    const counts = new Map();
    for (const num of nums) counts.set(num, (counts.get(num) || 0) + 1);

    for (const [key, value] of [...counts.entries()].sort((a, b) => a[0] - b[0])) {
        if (value > 0) {
            for (let i = k - 1; i >= 0; --i) {
                if ((counts.get(key + i) || 0) < value) return false;
                counts.set(key + i, counts.get(key + i) - value);
            }
        }
    }

    return true;
}
```
1. Create a count map that counts the occurrences of each integer in the input array.
2. Iterate through the keys in ascending order.
3. For each key, if its value is greater than 0, try to find k-1 integers that are consecutive to the current integer.
4. While iterating the keys, check if the occurrences of all consecutive integers are equal to or greater than the occurrences of the current integer. If not, return false as it isn't possible to divide the array into sets of k consecutive numbers. If everything passes through, return true.


# Maximum Points You Can Obtain from Cards

- slug: maximum-points-you-can-obtain-from-cards
- difficulty: Medium

There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.

In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.

Your score is the sum of the points of the cards you have taken.

Given the integer array `cardPoints` and the integer `k`, return the _maximum score_ you can obtain.

**Example 1:**

**Input:** cardPoints = \[1,2,3,4,5,6,1\], k = 3
**Output:** 12
**Explanation:** After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.

**Example 2:**

**Input:** cardPoints = \[2,2,2\], k = 2
**Output:** 4
**Explanation:** Regardless of which two cards you take, your score will always be 4.

**Example 3:**

**Input:** cardPoints = \[9,7,7,9,7,7,9\], k = 7
**Output:** 55
**Explanation:** You have to take all the cards. Your score is the sum of points of all cards.

**Constraints:**

*   `1 <= cardPoints.length <= 105`
*   `1 <= cardPoints[i] <= 104`
*   `1 <= k <= cardPoints.length`

1\. The number of unique characters in the substring must not exceed k. 2. The substring must not contain more than one instance of the same character. 3. The length of the substring must not exceed the length of the original string.

## A solution in Java

```java
import java.util.HashMap;

public int maxSubstringOccurrences(String s, int k) {
    int n = s.length(), res = 0;
    HashMap<Character, Integer> freq = new HashMap<>();
    for (int i = 0; i < n; ++i) {
        freq.put(s.charAt(i), freq.getOrDefault(s.charAt(i), 0) + 1);
        if (freq.size() <= k) {
            res = Math.max(res, freq.get(s.charAt(i)));
        }
    }
    return (freq.size() > k) ? 0 : res;
}
```
We iterate through the given string `s`. As we iterate, we maintain a frequency map `freq` of each character seen so far. At each step, we check if the size of `freq` is less than or equal to k. If it is, we update the result with the maximum frequency seen so far.

After the loop, if the size of freq is greater than k, we return 0; otherwise, we return the result.

## A solution in C++

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

int maxSubstringOccurrences(const string &s, int k) {
    int n = s.length(), res = 0;
    unordered_map<char, int> freq;
    for (int i = 0; i < n; ++i) {
        freq[s[i]]++;
        if (freq.size() <= k) {
            res = max(res, freq[s[i]]);
        }
    }
    return (freq.size() > k) ? 0 : res;
}
```
We iterate through the given string `s`. As we iterate, we maintain a frequency map `freq` of each character seen so far. At each step, we check if the size of `freq` is less than or equal to k. If it is, we update the result with the maximum frequency seen so far.

After the loop, if the size of freq is greater than k, we return 0; otherwise, we return the result.

## A solution in Python

```python
def max_substring_occurrences(s: str, k: int) -> int:
    freq = {}
    res = 0
    for c in s:
        freq[c] = freq.get(c, 0) + 1
        if len(freq) <= k:
            res = max(res, freq[c])
    return 0 if len(freq) > k else res
```
We iterate through the given string `s`. As we iterate, we maintain a frequency map `freq` of each character seen so far. At each step, we check if the size of `freq` is less than or equal to k. If it is, we update the result with the maximum frequency seen so far.

After the loop, if the size of freq is greater than k, we return 0; otherwise, we return the result.

## A solution in Javascript

```javascript
function maxSubstringOccurrences(s, k) {
    const n = s.length;
    let res = 0;
    const freq = new Map();
    for (let i = 0; i < n; ++i) {
        const c = s.charAt(i);
        freq.set(c, (freq.get(c) || 0) + 1);
        if (freq.size <= k) {
            res = Math.max(res, freq.get(c));
        }
    }
    return (freq.size > k) ? 0 : res;
}
```
We iterate through the given string `s`. As we iterate, we maintain a frequency map `freq` of each character seen so far. At each step, we check if the size of `freq` is less than or equal to k. If it is, we update the result with the maximum frequency seen so far.

After the loop, if the size of freq is greater than k, we return 0; otherwise, we return the result.


# Diagonal Traverse II

- slug: diagonal-traverse-ii
- difficulty: Medium

Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.

**Example 1:**

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

**Example 2:**

**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Output:** \[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16\]

**Constraints:**

*   `1 <= nums.length <= 105`
*   `1 <= nums[i].length <= 105`
*   `1 <= sum(nums[i].length) <= 105`
*   `1 <= nums[i][j] <= 105`

## A solution in Java

```java
import java.util.*;

public int maxCandies(int[] status, int[] candies, List<List<Integer>> keys, List<List<Integer>> containedBoxes, int[] initialBoxes) {
    int maxCandies = 0;
    Set<Integer> visited = new HashSet<>();
    Queue<Integer> toProcess = new LinkedList<>();

    for (int box : initialBoxes) {
        toProcess.offer(box);
    }

    while (!toProcess.isEmpty()) {
        int box = toProcess.poll();

        if (visited.contains(box)) {
            continue;
        }

        visited.add(box);

        if (status[box] == 1) {
            maxCandies += candies[box];
            for (int key : keys.get(box)) {
                status[key] = 1;
                if (visited.contains(key)) {
                    toProcess.offer(key);
                }
            }
            for (int contained : containedBoxes.get(box)) {
                toProcess.offer(contained);
            }
        } else {
            toProcess.offer(box);
        }
    }

    return maxCandies;
}
```
We solve this problem using a Breadth-First Search (BFS) approach.
1. Create a queue (`to_process`) to keep track of boxes we have to process, adding all the initial boxes in it.
2. Iterate while there are more boxes to process:
   1. Take the next box from the queue.
   2. If the box is already visited, continue to the next iteration.
   3. Add the current box to the visited set.
   4. If the box is open (status is equal to 1):
      1. Add the candies from the current box to the `max_candies`.
      2. Iterate through each key this box contains, change its status as open, and if it is visited, add it to the queue (`to_process`).
      3. Iterate through each box this box contains, and add it to the queue (`to_process`).
   5. If the box is closed (status is not equal to 1), push the box back into the queue so that it can be opened later when a key is found.
3. Return the `max_candies`.

This way, we open boxes using the found keys and keep adding the candies as the boxes become open.

## A solution in C++

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

int maxCandies(std::vector<int>& status, std::vector<int>& candies, std::vector<std::vector<int>>& keys, std::vector<std::vector<int>>& containedBoxes, std::vector<int>& initialBoxes) {
    int max_candies = 0;
    std::unordered_set<int> visited;
    std::queue<int> to_process;

    for (int box : initialBoxes) {
        to_process.push(box);
    }

    while (!to_process.empty()) {
        int box = to_process.front();
        to_process.pop();

        if (visited.count(box)) {
            continue;
        }

        visited.insert(box);

        if (status[box] == 1) {
            max_candies += candies[box];
            for (int key : keys[box]) {
                status[key] = 1;
                if (visited.count(key)) {
                    to_process.push(key);
                }
            }
            for (int contained : containedBoxes[box]) {
                to_process.push(contained);
            }
        } else {
            to_process.push(box);
        }
    }

    return max_candies;
}
```
We solve this problem using a Breadth-First Search (BFS) approach.
1. Create a queue (`to_process`) to keep track of boxes we have to process, adding all the initial boxes in it.
2. Iterate while there are more boxes to process:
   1. Take the next box from the queue.
   2. If the box is already visited, continue to the next iteration.
   3. Add the current box to the visited set.
   4. If the box is open (status is equal to 1):
      1. Add the candies from the current box to the `max_candies`.
      2. Iterate through each key this box contains, change its status as open, and if it is visited, add it to the queue (`to_process`).
      3. Iterate through each box this box contains, and add it to the queue (`to_process`).
   5. If the box is closed (status is not equal to 1), push the box back into the queue so that it can be opened later when a key is found.
3. Return the `max_candies`.

This way, we open boxes using the found keys and keep adding the candies as the boxes become open.

## A solution in Python

```python
from collections import deque

def maxCandies(status, candies, keys, containedBoxes, initialBoxes):
    max_candies = 0
    visited = set()
    to_process = deque(initialBoxes)

    while to_process:
        box = to_process.popleft()

        if box in visited:
            continue

        visited.add(box)

        if status[box]:
            max_candies += candies[box]
            for key in keys[box]:
                status[key] = 1
                if key in visited:
                    to_process.append(key)
            for contained in containedBoxes[box]:
                to_process.append(contained)
        else:
            to_process.append(box)

    return max_candies
```
We solve this problem using a Breadth-First Search (BFS) approach.
1. Create a queue (`to_process`) to keep track of boxes we have to process, adding all the initial boxes in it.
2. Iterate while there are more boxes to process:
   1. Take the next box from the queue.
   2. If the box is already visited, continue to the next iteration.
   3. Add the current box to the visited set.
   4. If the box is open (status is equal to 1):
      1. Add the candies from the current box to the `max_candies`.
      2. Iterate through each key this box contains, change its status as open, and if it is visited, add it to the queue (`to_process`).
      3. Iterate through each box this box contains, and add it to the queue (`to_process`).
   5. If the box is closed (status is not equal to 1), push the box back into the queue so that it can be opened later when a key is found.
3. Return the `max_candies`.

This way, we open boxes using the found keys and keep adding the candies as the boxes become open.

## A solution in Javascript

```javascript
function maxCandies(status, candies, keys, containedBoxes, initialBoxes) {
    let maxCandies = 0;
    let visited = new Set();
    let toProcess = initialBoxes.slice();

    while (toProcess.length > 0) {
        let box = toProcess.shift();

        if (visited.has(box)) {
            continue;
        }

        visited.add(box);

        if (status[box]) {
            maxCandies += candies[box];
            for (let key of keys[box]) {
                status[key] = 1;
                if (visited.has(key)) {
                    toProcess.push(key);
                }
            }
            for (let contained of containedBoxes[box]) {
                toProcess.push(contained);
            }
        } else {
            toProcess.push(box);
        }
    }

    return maxCandies;
}
```
We solve this problem using a Breadth-First Search (BFS) approach.
1. Create a queue (`to_process`) to keep track of boxes we have to process, adding all the initial boxes in it.
2. Iterate while there are more boxes to process:
   1. Take the next box from the queue.
   2. If the box is already visited, continue to the next iteration.
   3. Add the current box to the visited set.
   4. If the box is open (status is equal to 1):
      1. Add the candies from the current box to the `max_candies`.
      2. Iterate through each key this box contains, change its status as open, and if it is visited, add it to the queue (`to_process`).
      3. Iterate through each box this box contains, and add it to the queue (`to_process`).
   5. If the box is closed (status is not equal to 1), push the box back into the queue so that it can be opened later when a key is found.
3. Return the `max_candies`.

This way, we open boxes using the found keys and keep adding the candies as the boxes become open.