# Print Binary Tree

- slug: print-binary-tree
- difficulty: Medium

Given the `root` of a binary tree, construct a **0-indexed** `m x n` string matrix `res` that represents a **formatted layout** of the tree. The formatted layout matrix should be constructed using the following rules:

*   The **height** of the tree is `height` and the number of rows `m` should be equal to `height + 1`.
*   The number of columns `n` should be equal to `2height+1 - 1`.
*   Place the **root node** in the **middle** of the **top row** (more formally, at location `res[0][(n-1)/2]`).
*   For each node that has been placed in the matrix at position `res[r][c]`, place its **left child** at `res[r+1][c-2height-r-1]` and its **right child** at `res[r+1][c+2height-r-1]`.
*   Continue this process until all the nodes in the tree have been placed.
*   Any empty cells should contain the empty string `" "`.

Return _the constructed matrix_ `res`.

**Example 1:**

**Input:** root = \[1,2\]
**Output:**
\[\[ " ", "1 ", " "\],
 \[ "2 ", " ", " "\]\]

**Example 2:**

**Input:** root = \[1,2,3,null,4\]
**Output:**
\[\[ " ", " ", " ", "1 ", " ", " ", " "\],
 \[ " ", "2 ", " ", " ", " ", "3 ", " "\],
 \[ " ", " ", "4 ", " ", " ", " ", " "\]\]

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 210]`.
*   `-99 <= Node.val <= 99`
*   The depth of the tree will be in the range `[1, 10]`.

## A solution in Java

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

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

public List<List<String>> printTree(TreeNode root) {
    if (root == null) {
        return new ArrayList<>();
    }

    // Calculate Depth
    int depth = 0;
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        int size = queue.size();
        depth++;
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
    }

    List<List<String>> res = new ArrayList<>();
    for (int i = 0; i < depth; i++) {
        List<String> row = new ArrayList<>();
        for (int j = 0; j < (1 << depth) - 1; j++) {
            row.add("");
        }
        res.add(row);
    }

    // Fill in matrix
    queue.offer(root);
    int level = 0;
    int step = (1 << (depth - 1));
    while (!queue.isEmpty()) {
        int size = queue.size();
        int curPos = step - 1;
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            res.get(level).set(curPos, String.valueOf(node.val));
            curPos += (step << 1);
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        step >>= 1;
        level++;
    }

    return res;
}
```
In this problem, we use a Breadth First Search (BFS) approach to traverse the tree level-by-level.

1. First, we start by calculating the depth of the tree using a queue (BFS traversal). For each level, we increment the depth variable.

2. Then, we initialize the formatted layout matrix (res) as a 2-dimensional array with dimensions m (depth) and n (2^(m) - 1). We fill the matrix with empty strings.

3. After initializing the matrix, we traverse the tree again using the BFS approach and fill in the node values in the matrix accordingly at each level. The position of each node in the current level is based on calculations involving the step value, which is initialized as (1 << (depth - 1)) and divided by 2 before moving to the next level. We add the result of these calculations to the current position.

4. Finally, after the BFS traversal is complete, we return the formatted layout matrix (res).

## A solution in C++

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

using namespace std;

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

vector<vector<string>> printTree(TreeNode* root) {
    if (!root) return {{}};

    // Calculate Depth
    int depth = 0;
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()) {
        int size = q.size();
        depth++;
        for (int i = 0; i < size; i++) {
            TreeNode* node = q.front(); q.pop();
            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }
    }

    // Initialize matrix
    vector<vector<string>> res(depth, vector<string>((1 << depth) - 1, ""));

    // Fill in matrix
    q.push(root);
    int level = 0;
    int step = (1 << (depth - 1));
    while (!q.empty()) {
        int size = q.size();
        int curPos = step - 1;
        for (int i = 0; i < size; i++) {
            TreeNode* node = q.front(); q.pop();
            res[level][curPos] = to_string(node->val);
            curPos += (step << 1);
            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }
        step >>= 1;
        level++;
    }

    return res;
}
```
In this problem, we use a Breadth First Search (BFS) approach to traverse the tree level-by-level.

1. First, we start by calculating the depth of the tree using a queue (BFS traversal). For each level, we increment the depth variable.

2. Then, we initialize the formatted layout matrix (res) as a 2-dimensional array with dimensions m (depth) and n (2^(m) - 1). We fill the matrix with empty strings.

3. After initializing the matrix, we traverse the tree again using the BFS approach and fill in the node values in the matrix accordingly at each level. The position of each node in the current level is based on calculations involving the step value, which is initialized as (1 << (depth - 1)) and divided by 2 before moving to the next level. We add the result of these calculations to the current position.

4. Finally, after the BFS traversal is complete, we return the formatted layout matrix (res).

## A solution in Python

```python
from collections import deque

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def printTree(root):
    if not root:
        return [[]]

    # Calculate Depth
    depth = 0
    q = deque([root])
    while q:
        depth += 1
        for _ in range(len(q)):
            node = q.popleft()
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)

    res = [["" for _ in range((1 << depth) - 1)] for _ in range(depth)]

    # Fill in matrix
    q.append(root)
    level = 0
    step = (1 << (depth - 1))
    while q:
        cur_pos = step - 1
        for _ in range(len(q)):
            node = q.popleft()
            res[level][cur_pos] = str(node.val)
            cur_pos += (step << 1)
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
        step >>= 1
        level += 1

    return res
```
In this problem, we use a Breadth First Search (BFS) approach to traverse the tree level-by-level.

1. First, we start by calculating the depth of the tree using a queue (BFS traversal). For each level, we increment the depth variable.

2. Then, we initialize the formatted layout matrix (res) as a 2-dimensional array with dimensions m (depth) and n (2^(m) - 1). We fill the matrix with empty strings.

3. After initializing the matrix, we traverse the tree again using the BFS approach and fill in the node values in the matrix accordingly at each level. The position of each node in the current level is based on calculations involving the step value, which is initialized as (1 << (depth - 1)) and divided by 2 before moving to the next level. We add the result of these calculations to the current position.

4. Finally, after the BFS traversal is complete, we return the formatted layout matrix (res).

## A solution in Javascript

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

function printTree(root) {
    if (!root) {
        return [[]];
    }

    let depth = 0;
    let q = [root];
    while (q.length) {
        depth++;
        let size = q.length;
        for (let i = 0; i < size; i++) {
            let node = q.shift();
            if (node.left) q.push(node.left);
            if (node.right) q.push(node.right);
        }
    }

    const res = Array.from({length: depth}, () => Array(2 ** depth - 1).fill(""));

    q.push(root);
    let level = 0;
    let step = (1 << (depth - 1));
    while (q.length) {
        let size = q.length;
        let curPos = step - 1;
        for (let i = 0; i < size; i++) {
            let node = q.shift();
            res[level][curPos] = String(node.val);
            curPos += (step << 1);
            if (node.left) q.push(node.left);
            if (node.right) q.push(node.right);
        }
        step >>= 1;
        level++;
    }

    return res;
}
```
In this problem, we use a Breadth First Search (BFS) approach to traverse the tree level-by-level.

1. First, we start by calculating the depth of the tree using a queue (BFS traversal). For each level, we increment the depth variable.

2. Then, we initialize the formatted layout matrix (res) as a 2-dimensional array with dimensions m (depth) and n (2^(m) - 1). We fill the matrix with empty strings.

3. After initializing the matrix, we traverse the tree again using the BFS approach and fill in the node values in the matrix accordingly at each level. The position of each node in the current level is based on calculations involving the step value, which is initialized as (1 << (depth - 1)) and divided by 2 before moving to the next level. We add the result of these calculations to the current position.

4. Finally, after the BFS traversal is complete, we return the formatted layout matrix (res).


# Coin Path

- slug: coin-path
- difficulty: Hard

You are given an integer array `coins` (**1-indexed**) of length `n` and an integer `maxJump`. You can jump to any index `i` of the array `coins` if `coins[i] != -1` and you have to pay `coins[i]` when you visit index `i`. In addition to that, if you are currently at index `i`, you can only jump to any index `i + k` where `i + k <= n` and `k` is a value in the range `[1, maxJump]`.

You are initially positioned at index `1` (`coins[1]` is not `-1`). You want to find the path that reaches index n with the minimum cost.

Return an integer array of the indices that you will visit in order so that you can reach index n with the minimum cost. If there are multiple paths with the same cost, return the **lexicographically smallest** such path. If it is not possible to reach index n, return an empty array.

A path `p1 = [Pa1, Pa2, ..., Pax]` of length `x` is **lexicographically smaller** than `p2 = [Pb1, Pb2, ..., Pbx]` of length `y`, if and only if at the first `j` where `Paj` and `Pbj` differ, `Paj < Pbj`; when no such `j` exists, then `x < y`.

**Example 1:**

**Input:** coins = \[1,2,4,-1,2\], maxJump = 2
**Output:** \[1,3,5\]

**Example 2:**

**Input:** coins = \[1,2,4,-1,2\], maxJump = 1
**Output:** \[\]

**Constraints:**

*   `1 <= coins.length <= 1000`
*   `-1 <= coins[i] <= 100`
*   `coins[1] != -1`
*   `1 <= maxJump <= 100`

## A solution in Java

```java
import java.util.*;
class Solution {
    public int[] cheapestJump(int[] coins, int maxJump) {
        int n = coins.length;
        int[] dp = new int[n];
        int[] parent = new int[n];
        Arrays.fill(dp, Integer.MAX_VALUE);
        Arrays.fill(parent, -1);
        dp[0] = coins[0];
        for (int i = 0; i < n; ++i) {
            if (coins[i] == -1) continue;
            for (int j = 1; j <= maxJump && i + j < n; ++j) {
                int next = i + j;
                int cost = coins[next] + dp[i];
                if (cost < dp[next]) {
                    dp[next] = cost;
                    parent[next] = i;
                }
            }
        }
        List<Integer> ansList = new ArrayList<>();
        if (dp[n - 1] == Integer.MAX_VALUE) return new int[0];
        int cur = n - 1;
        while (cur != -1) {
            ansList.add(cur + 1);
            cur = parent[cur];
        }
        Collections.reverse(ansList);
        int[] ans = new int[ansList.size()];
        for (int i = 0; i < ansLIST.size(); i++) {
            ans[i] = ansList.get(i);
        }
        return ans;
    }
}
```
The algorithm is a dynamic programming-based solution. The key is to define the state `dp[i]`, which represents the minimum cost to reach the `i`-th index. We initialize `dp` with infinity for all indexes except `dp[0]` which is initialized with `coins[0]`, and `parent` with -1 for all indexes.

We then traverse the input array `coins`. If `coins[i]` is -1, we skip the current index, as it is not visitable. Otherwise, we check all possible jumps from the current index `i`. For each jump, calculate the next index and cost to reach that index. If the current cost at the next index is greater than the newly calculated cost, we update the `dp[next]` and `parent[next]` with new values.

Once the traversal is complete, we construct our answer by backtracking through the parent array from the `n-1`-th index to the first index, and build the list of indices required to reach the end of the `coins` list with minimum cost. If a valid path exists, return this list of indices, otherwise, return an empty list.

## A solution in C++

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

vector<int> cheapestJump(vector<int>& coins, int maxJump) {
    int n = coins.size();
    vector<int> dp(n, 1e9), parent(n, -1);
    dp[0] = coins[0];
    for (int i = 0; i < n; ++i) {
        if (coins[i] == -1) continue;
        for (int j = 1; j <= maxJump && i + j < n; ++j) {
            int next = i + j;
            int cost = coins[next] + dp[i];
            if (cost < dp[next]) {
                dp[next] = cost;
                parent[next] = i;
            }
        }
    }
    vector<int> ans;
    if (dp[n - 1] == 1e9) return ans;
    int cur = n - 1;
    while (cur != -1) {
        ans.push_back(cur + 1);
        cur = parent[cur];
    }
    reverse(ans.begin(), ans.end());
    return ans;
}
```
The algorithm is a dynamic programming-based solution. The key is to define the state `dp[i]`, which represents the minimum cost to reach the `i`-th index. We initialize `dp` with infinity for all indexes except `dp[0]` which is initialized with `coins[0]`, and `parent` with -1 for all indexes.

We then traverse the input array `coins`. If `coins[i]` is -1, we skip the current index, as it is not visitable. Otherwise, we check all possible jumps from the current index `i`. For each jump, calculate the next index and cost to reach that index. If the current cost at the next index is greater than the newly calculated cost, we update the `dp[next]` and `parent[next]` with new values.

Once the traversal is complete, we construct our answer by backtracking through the parent array from the `n-1`-th index to the first index, and build the list of indices required to reach the end of the `coins` list with minimum cost. If a valid path exists, return this list of indices, otherwise, return an empty list.

## A solution in Python

```python
def cheapestJump(coins, maxJump):
    n = len(coins)
    dp = [float('inf')] * n
    parent = [-1] * n
    dp[0] = coins[0]
    for i in range(n):
        if coins[i] == -1:
            continue
        for j in range(1, maxJump + 1):
            if i + j >= n:
                break
            next = i + j
            cost = coins[next] + dp[i]
            if cost < dp[next]:
                dp[next] = cost
                parent[next] = i
    ans = []
    if dp[n - 1] == float('inf'):
        return ans
    cur = n - 1
    while cur != -1:
        ans.append(cur + 1)
        cur = parent[cur]
    ans.reverse()
    return ans
```
The algorithm is a dynamic programming-based solution. The key is to define the state `dp[i]`, which represents the minimum cost to reach the `i`-th index. We initialize `dp` with infinity for all indexes except `dp[0]` which is initialized with `coins[0]`, and `parent` with -1 for all indexes.

We then traverse the input array `coins`. If `coins[i]` is -1, we skip the current index, as it is not visitable. Otherwise, we check all possible jumps from the current index `i`. For each jump, calculate the next index and cost to reach that index. If the current cost at the next index is greater than the newly calculated cost, we update the `dp[next]` and `parent[next]` with new values.

Once the traversal is complete, we construct our answer by backtracking through the parent array from the `n-1`-th index to the first index, and build the list of indices required to reach the end of the `coins` list with minimum cost. If a valid path exists, return this list of indices, otherwise, return an empty list.

## A solution in Javascript

```javascript
function cheapestJump(coins, maxJump) {
    const n = coins.length;
    const dp = new Array(n).fill(Infinity);
    const parent = new Array(n).fill(-1);
    dp[0] = coins[0];
    for (let i = 0; i < n; ++i) {
        if (coins[i] === -1) continue;
        for (let j = 1; j <= maxJump && i + j < n; ++j) {
            const next = i + j;
            const cost = coins[next] + dp[i];
            if (cost < dp[next]) {
                dp[next] = cost;
                parent[next] = i;
            }
        }
    }
    const ans = [];
    if (dp[n - 1] === Infinity) return ans;
    let cur = n - 1;
    while (cur !== -1) {
        ans.push(cur + 1);
        cur = parent[cur];
    }
    ans.reverse();
    return ans;
}
```
The algorithm is a dynamic programming-based solution. The key is to define the state `dp[i]`, which represents the minimum cost to reach the `i`-th index. We initialize `dp` with infinity for all indexes except `dp[0]` which is initialized with `coins[0]`, and `parent` with -1 for all indexes.

We then traverse the input array `coins`. If `coins[i]` is -1, we skip the current index, as it is not visitable. Otherwise, we check all possible jumps from the current index `i`. For each jump, calculate the next index and cost to reach that index. If the current cost at the next index is greater than the newly calculated cost, we update the `dp[next]` and `parent[next]` with new values.

Once the traversal is complete, we construct our answer by backtracking through the parent array from the `n-1`-th index to the first index, and build the list of indices required to reach the end of the `coins` list with minimum cost. If a valid path exists, return this list of indices, otherwise, return an empty list.


# Robot Return to Origin

- slug: robot-return-to-origin
- difficulty: Easy

There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves.

You are given a string `moves` that represents the move sequence of the robot where `moves[i]` represents its `ith` move. Valid moves are `'R'` (right), `'L'` (left), `'U'` (up), and `'D'` (down).

Return `true` _if the robot returns to the origin after it finishes all of its moves, or_ `false` _otherwise_.

**Note**: The way that the robot is "facing " is irrelevant. `'R'` will always make the robot move to the right once, `'L'` will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

**Example 1:**

**Input:** moves =  "UD "
**Output:** true
**Explanation**: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

**Example 2:**

**Input:** moves =  "LL "
**Output:** false
**Explanation**: The robot moves left twice. It ends up two  "moves " to the left of the origin. We return false because it is not at the origin at the end of its moves.

**Constraints:**

*   `1 <= moves.length <= 2 * 104`
*   `moves` only contains the characters `'U'`, `'D'`, `'L'` and `'R'`.

## A solution in Java

```java
public boolean judgeCircle(String moves) {
    int x = 0, y = 0;
    for(char move : moves.toCharArray()) {
        if(move == 'U') y++;
        else if(move == 'D') y--;
        else if(move == 'R') x++;
        else if(move == 'L') x--;
    }
    return x == 0 && y == 0;
}
```
The algorithm keeps track of the robot's position in a 2D plane using two integer variables `x` and `y` initialized to 0. The `x` represents the horizontal position, and `y` represents the vertical position. It then iterates through the given moves string and updates the position based on the current move. If a move is 'R', it increments `x`; if it's 'L', it decrements `x`; if it's 'U', it increments `y`; and if it's 'D', it decrements `y`. After processing all the moves, the algorithm checks if both `x` equals to 0 and `y` equals to 0. If both are 0, it means the robot is back to the origin, and it returns true; otherwise, it returns false.

## A solution in C++

```cpp
bool judgeCircle(string moves) {
    int x = 0, y = 0;
    for(char move : moves) {
        if(move == 'U') y++;
        else if(move == 'D') y--;
        else if(move == 'R') x++;
        else if(move == 'L') x--;
    }
    return x == 0 && y == 0;
}
```
The algorithm keeps track of the robot's position in a 2D plane using two integer variables `x` and `y` initialized to 0. The `x` represents the horizontal position, and `y` represents the vertical position. It then iterates through the given moves string and updates the position based on the current move. If a move is 'R', it increments `x`; if it's 'L', it decrements `x`; if it's 'U', it increments `y`; and if it's 'D', it decrements `y`. After processing all the moves, the algorithm checks if both `x` equals to 0 and `y` equals to 0. If both are 0, it means the robot is back to the origin, and it returns true; otherwise, it returns false.

## A solution in Python

```python
def judgeCircle(moves: str) -> bool:
    x, y = 0, 0
    for move in moves:
        if move == 'U': y += 1
        elif move == 'D': y -= 1
        elif move == 'R': x += 1
        elif move == 'L': x -= 1
    return x == 0 and y == 0
```
The algorithm keeps track of the robot's position in a 2D plane using two integer variables `x` and `y` initialized to 0. The `x` represents the horizontal position, and `y` represents the vertical position. It then iterates through the given moves string and updates the position based on the current move. If a move is 'R', it increments `x`; if it's 'L', it decrements `x`; if it's 'U', it increments `y`; and if it's 'D', it decrements `y`. After processing all the moves, the algorithm checks if both `x` equals to 0 and `y` equals to 0. If both are 0, it means the robot is back to the origin, and it returns true; otherwise, it returns false.

## A solution in Javascript

```javascript
function judgeCircle(moves) {
    let x = 0, y = 0;
    for(let move of moves) {
        if(move === 'U') y++;
        else if(move === 'D') y--;
        else if(move === 'R') x++;
        else if(move === 'L') x--;
    }
    return x === 0 && y === 0;
}
```
The algorithm keeps track of the robot's position in a 2D plane using two integer variables `x` and `y` initialized to 0. The `x` represents the horizontal position, and `y` represents the vertical position. It then iterates through the given moves string and updates the position based on the current move. If a move is 'R', it increments `x`; if it's 'L', it decrements `x`; if it's 'U', it increments `y`; and if it's 'D', it decrements `y`. After processing all the moves, the algorithm checks if both `x` equals to 0 and `y` equals to 0. If both are 0, it means the robot is back to the origin, and it returns true; otherwise, it returns false.


# Find K Closest Elements

- slug: find-k-closest-elements
- difficulty: Medium

Given a **sorted** integer array `arr`, two integers `k` and `x`, return the `k` closest integers to `x` in the array. The result should also be sorted in ascending order.

An integer `a` is closer to `x` than an integer `b` if:

*   `|a - x| < |b - x|`, or
*   `|a - x| == |b - x|` and `a < b`

**Example 1:**

**Input:** arr = \[1,2,3,4,5\], k = 4, x = 3
**Output:** \[1,2,3,4\]

**Example 2:**

**Input:** arr = \[1,2,3,4,5\], k = 4, x = -1
**Output:** \[1,2,3,4\]

**Constraints:**

*   `1 <= k <= arr.length`
*   `1 <= arr.length <= 104`
*   `arr` is sorted in **ascending** order.
*   `-104 <= arr[i], x <= 104`

## A solution in Java

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

public List<Integer> findClosestElements(int[] arr, int k, int x) {
    int left = 0;
    int right = arr.length - k;

    while (left < right) {
        int mid = left + (right - left) / 2;
        if (x - arr[mid] > arr[mid + k] - x) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }

    List<Integer> result = new ArrayList<>();
    for (int i = left; i < left + k; i++) {
        result.add(arr[i]);
    }

    return result;
}
```
The algorithm uses a binary search to find the subarray of length `k` with the closest numbers to `x`.

1. Initialize the `left` pointer to the beginning of the array and the `right` pointer to the end of the array minus `k`.
2. While the `left` pointer is less than the `right` pointer:
    a. Calculate the `mid` index.
    b. Compare the difference between `arr[mid]` and `x`, and the difference between `arr[mid + k]` and `x`.
    c. If the difference at `mid` is greater, update `left` to `mid + 1`, otherwise update `right` to `mid`.
3. Once the binary search is complete, the result will be the subarray of length `k` starting at the `left` index.

This algorithm has a time complexity of O(log(n)) where n is the length of the input array, as it uses binary search to locate the closest elements. The space complexity is also O(1) since only a constant number of variables are used.

## A solution in C++

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

std::vector<int> findClosestElements(std::vector<int>& arr, int k, int x) {
    int left = 0;
    int right = arr.size() - k;

    while (left < right) {
        int mid = left + (right - left) / 2;
        if (x - arr[mid] > arr[mid + k] - x) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }

    return std::vector<int>(arr.begin() + left, arr.begin() + left + k);
}
```
The algorithm uses a binary search to find the subarray of length `k` with the closest numbers to `x`.

1. Initialize the `left` pointer to the beginning of the array and the `right` pointer to the end of the array minus `k`.
2. While the `left` pointer is less than the `right` pointer:
    a. Calculate the `mid` index.
    b. Compare the difference between `arr[mid]` and `x`, and the difference between `arr[mid + k]` and `x`.
    c. If the difference at `mid` is greater, update `left` to `mid + 1`, otherwise update `right` to `mid`.
3. Once the binary search is complete, the result will be the subarray of length `k` starting at the `left` index.

This algorithm has a time complexity of O(log(n)) where n is the length of the input array, as it uses binary search to locate the closest elements. The space complexity is also O(1) since only a constant number of variables are used.

## A solution in Python

```python
from typing import List

def findClosestElements(arr: List[int], k: int, x: int) -> List[int]:
    left = 0
    right = len(arr) - k

    while left < right:
        mid = left + (right - left) // 2
        if x - arr[mid] > arr[mid + k] - x:
            left = mid + 1
        else:
            right = mid

    return arr[left:left + k]
```
The algorithm uses a binary search to find the subarray of length `k` with the closest numbers to `x`.

1. Initialize the `left` pointer to the beginning of the array and the `right` pointer to the end of the array minus `k`.
2. While the `left` pointer is less than the `right` pointer:
    a. Calculate the `mid` index.
    b. Compare the difference between `arr[mid]` and `x`, and the difference between `arr[mid + k]` and `x`.
    c. If the difference at `mid` is greater, update `left` to `mid + 1`, otherwise update `right` to `mid`.
3. Once the binary search is complete, the result will be the subarray of length `k` starting at the `left` index.

This algorithm has a time complexity of O(log(n)) where n is the length of the input array, as it uses binary search to locate the closest elements. The space complexity is also O(1) since only a constant number of variables are used.

## A solution in Javascript

```javascript
function findClosestElements(arr, k, x) {
    let left = 0;
    let right = arr.length - k;

    while (left < right) {
        let mid = left + ((right - left) >> 1);
        if (x - arr[mid] > arr[mid + k] - x) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }

    return arr.slice(left, left + k);
}
```
The algorithm uses a binary search to find the subarray of length `k` with the closest numbers to `x`.

1. Initialize the `left` pointer to the beginning of the array and the `right` pointer to the end of the array minus `k`.
2. While the `left` pointer is less than the `right` pointer:
    a. Calculate the `mid` index.
    b. Compare the difference between `arr[mid]` and `x`, and the difference between `arr[mid + k]` and `x`.
    c. If the difference at `mid` is greater, update `left` to `mid + 1`, otherwise update `right` to `mid`.
3. Once the binary search is complete, the result will be the subarray of length `k` starting at the `left` index.

This algorithm has a time complexity of O(log(n)) where n is the length of the input array, as it uses binary search to locate the closest elements. The space complexity is also O(1) since only a constant number of variables are used.


# Split Array into Consecutive Subsequences

- slug: split-array-into-consecutive-subsequences
- difficulty: Medium

You are given an integer array `nums` that is **sorted in non-decreasing order**.

Determine if it is possible to split `nums` into **one or more subsequences** such that **both** of the following conditions are true:

*   Each subsequence is a **consecutive increasing sequence** (i.e. each integer is **exactly one** more than the previous integer).
*   All subsequences have a length of `3` **or more**.

Return `true` _if you can split_ `nums` _according to the above conditions, or_ `false` _otherwise_.

A **subsequence** of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., `[1,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,3,2]` is not).

**Example 1:**

**Input:** nums = \[1,2,3,3,4,5\]
**Output:** true
**Explanation:** nums can be split into the following subsequences:
\[**1**,**2**,**3**,3,4,5\] --> 1, 2, 3
\[1,2,3,**3**,**4**,**5**\] --> 3, 4, 5

**Example 2:**

**Input:** nums = \[1,2,3,3,4,4,5,5\]
**Output:** true
**Explanation:** nums can be split into the following subsequences:
\[**1**,**2**,**3**,3,**4**,4,**5**,5\] --> 1, 2, 3, 4, 5
\[1,2,3,**3**,4,**4**,5,**5**\] --> 3, 4, 5

**Example 3:**

**Input:** nums = \[1,2,3,4,4,5\]
**Output:** false
**Explanation:** It is impossible to split nums into consecutive increasing subsequences of length 3 or more.

**Constraints:**

*   `1 <= nums.length <= 104`
*   `-1000 <= nums[i] <= 1000`
*   `nums` is sorted in **non-decreasing** order.

## A solution in Java

```java
public boolean canSplit(int[] nums) {
    int[] freq = new int[20001], needed = new int[20001];
    for (int n : nums)
        freq[n]++;
    for (int n : nums) {
        if (freq[n] == 0) continue;
        if (needed[n - 1] == 0) {
            if (freq[n + 1] > 0 && freq[n + 2] > 0) {
                freq[n]--; freq[n + 1]--; freq[n + 2]--;
                needed[n + 2]++;
            } else return false;
        } else {
            freq[n]--; needed[n - 1]--;
            needed[n]++;
        }
    }
    return true;
}
```
The algorithm works as follows:
1. Create two arrays, one to store the frequency of elements in the given input `nums`, and another to store the number of elements needed to create a valid sequence.
2. Iterate through the input `nums`, filling up the frequency array.
3. Iterate through the input `nums` again. For each non-zero frequency element in the input `nums`:
   - If it's not needed to create a valid sequence, check if it can form a new sequence with its next two elements in the sorted order. If yes, decrement the frequencies of those three elements and increment the needed count of third elements by 1. If not, return false.
   - If it's needed for a valid sequence, decrement its frequency and the needed count of its previous element, and increment the needed count of the element itself by 1.
4. At the end of this iteration, if all conditions are met, return true.

This algorithm checks if the given sorted array can be split into subsequences of at least three consecutive integers. If any of the conditions mentioned are not met, it returns false. If all conditions are fulfilled, it returns true.

## A solution in C++

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

bool canSplit(vector<int>& nums) {
    vector<int> freq(20001, 0), needed(20001, 0);
    for (int n : nums)
        freq[n]++;
    for (int n : nums) {
        if (!freq[n]) continue;
        if (!needed[n - 1]) {
            if (freq[n + 1] && freq[n + 2]) {
                freq[n]--; freq[n + 1]--; freq[n + 2]--;
                needed[n + 2]++;
            } else return false;
        } else {
            freq[n]--; needed[n - 1]--;
            needed[n]++;
        }
    }
    return true;
}
```
The algorithm works as follows:
1. Create two arrays, one to store the frequency of elements in the given input `nums`, and another to store the number of elements needed to create a valid sequence.
2. Iterate through the input `nums`, filling up the frequency array.
3. Iterate through the input `nums` again. For each non-zero frequency element in the input `nums`:
   - If it's not needed to create a valid sequence, check if it can form a new sequence with its next two elements in the sorted order. If yes, decrement the frequencies of those three elements and increment the needed count of third elements by 1. If not, return false.
   - If it's needed for a valid sequence, decrement its frequency and the needed count of its previous element, and increment the needed count of the element itself by 1.
4. At the end of this iteration, if all conditions are met, return true.

This algorithm checks if the given sorted array can be split into subsequences of at least three consecutive integers. If any of the conditions mentioned are not met, it returns false. If all conditions are fulfilled, it returns true.

## A solution in Python

```python
def can_split(nums):
    freq = [0] * 20001
    needed = [0] * 20001
    for n in nums:
        freq[n] += 1
    for n in nums:
        if not freq[n]: continue
        if not needed[n - 1]:
            if freq[n + 1] and freq[n + 2]:
                freq[n] -= 1; freq[n + 1] -= 1; freq[n + 2] -= 1;
                needed[n + 2] += 1
            else: return False
        else:
            freq[n] -= 1; needed[n - 1] -= 1;
            needed[n] += 1
    return True
```
The algorithm works as follows:
1. Create two arrays, one to store the frequency of elements in the given input `nums`, and another to store the number of elements needed to create a valid sequence.
2. Iterate through the input `nums`, filling up the frequency array.
3. Iterate through the input `nums` again. For each non-zero frequency element in the input `nums`:
   - If it's not needed to create a valid sequence, check if it can form a new sequence with its next two elements in the sorted order. If yes, decrement the frequencies of those three elements and increment the needed count of third elements by 1. If not, return false.
   - If it's needed for a valid sequence, decrement its frequency and the needed count of its previous element, and increment the needed count of the element itself by 1.
4. At the end of this iteration, if all conditions are met, return true.

This algorithm checks if the given sorted array can be split into subsequences of at least three consecutive integers. If any of the conditions mentioned are not met, it returns false. If all conditions are fulfilled, it returns true.

## A solution in Javascript

```javascript
function canSplit(nums) {
    const freq = new Array(20001).fill(0), needed = new Array(20001).fill(0);
    for (let n of nums)
        freq[n]++;
    for (let n of nums) {
        if (!freq[n]) continue;
        if (!needed[n - 1]) {
            if (freq[n + 1] && freq[n + 2]) {
                freq[n]--; freq[n + 1]--; freq[n + 2]--;
                needed[n + 2]++;
            } else return false;
        } else {
            freq[n]--; needed[n - 1]--;
            needed[n]++;
        }
    }
    return true;
}
```
The algorithm works as follows:
1. Create two arrays, one to store the frequency of elements in the given input `nums`, and another to store the number of elements needed to create a valid sequence.
2. Iterate through the input `nums`, filling up the frequency array.
3. Iterate through the input `nums` again. For each non-zero frequency element in the input `nums`:
   - If it's not needed to create a valid sequence, check if it can form a new sequence with its next two elements in the sorted order. If yes, decrement the frequencies of those three elements and increment the needed count of third elements by 1. If not, return false.
   - If it's needed for a valid sequence, decrement its frequency and the needed count of its previous element, and increment the needed count of the element itself by 1.
4. At the end of this iteration, if all conditions are met, return true.

This algorithm checks if the given sorted array can be split into subsequences of at least three consecutive integers. If any of the conditions mentioned are not met, it returns false. If all conditions are fulfilled, it returns true.


# Remove 9

- slug: remove-9
- difficulty: Hard

Start from integer `1`, remove any integer that contains `9` such as `9`, `19`, `29`...

Now, you will have a new integer sequence `[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...]`.

Given an integer `n`, return _the_ `nth` (**1-indexed**) integer in the new sequence.

**Example 1:**

**Input:** n = 9
**Output:** 10

**Example 2:**

**Input:** n = 10
**Output:** 11

**Constraints:**

*   `1 <= n <= 8 * 108`

## A solution in Java

```java
public int newInteger(int n) {
    int result = 0, base = 1;
    while (n>0) {
        result += n % 9 * base;
        n /= 9;
        base *= 10;
    }
    return result;
}
```
The general idea is to use a radix-9 representation for the resulting numbers, ignoring the number 9. The input number `n` is first considered to be in base 9, so we divide it by 9 and calculate the remainder. The remainder corresponds to a digit position in the resulting number. The algorithm continually adds the product of the remainder and the current base (starting at 1), and updates the input number by dividing it by 9. This process continues until the input number is reduced to 0. At this point, the result contains the final number, which is then returned.

## A solution in C++

```cpp
int newInteger(int n) {
    int result = 0, base = 1;
    while (n) {
        result += n % 9 * base;
        n /= 9;
        base *= 10;
    }
    return result;
}
```
The general idea is to use a radix-9 representation for the resulting numbers, ignoring the number 9. The input number `n` is first considered to be in base 9, so we divide it by 9 and calculate the remainder. The remainder corresponds to a digit position in the resulting number. The algorithm continually adds the product of the remainder and the current base (starting at 1), and updates the input number by dividing it by 9. This process continues until the input number is reduced to 0. At this point, the result contains the final number, which is then returned.

## A solution in Python

```python
def newInteger(n):
    result = 0
    base = 1
    while n:
        result += n % 9 * base
        n //= 9
        base *= 10
    return result
```
The general idea is to use a radix-9 representation for the resulting numbers, ignoring the number 9. The input number `n` is first considered to be in base 9, so we divide it by 9 and calculate the remainder. The remainder corresponds to a digit position in the resulting number. The algorithm continually adds the product of the remainder and the current base (starting at 1), and updates the input number by dividing it by 9. This process continues until the input number is reduced to 0. At this point, the result contains the final number, which is then returned.

## A solution in Javascript

```javascript
function newInteger(n) {
    let result = 0, base = 1;
    while (n > 0) {
        result += (n % 9) * base;
        n = Math.floor(n / 9);
        base *= 10;
    }
    return result;
}
```
The general idea is to use a radix-9 representation for the resulting numbers, ignoring the number 9. The input number `n` is first considered to be in base 9, so we divide it by 9 and calculate the remainder. The remainder corresponds to a digit position in the resulting number. The algorithm continually adds the product of the remainder and the current base (starting at 1), and updates the input number by dividing it by 9. This process continues until the input number is reduced to 0. At this point, the result contains the final number, which is then returned.


# Image Smoother

- slug: image-smoother
- difficulty: Easy

An **image smoother** is a filter of the size `3 x 3` that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).

Given an `m x n` integer matrix `img` representing the grayscale of an image, return _the image after applying the smoother on each cell of it_.

**Example 1:**

**Input:** img = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[0,0,0\],\[0,0,0\],\[0,0,0\]\]
**Explanation:**
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0

**Example 2:**

**Input:** img = \[\[100,200,100\],\[200,50,200\],\[100,200,100\]\]
**Output:** \[\[137,141,137\],\[141,138,141\],\[137,141,137\]\]
**Explanation:**
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138

**Constraints:**

*   `m == img.length`
*   `n == img[i].length`
*   `1 <= m, n <= 200`
*   `0 <= img[i][j] <= 255`

## A solution in Java

```java
public int[][] imageSmoother(int[][] img) {
    int m = img.length, n = img[0].length;
    int[][] result = new int[m][n];

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            int count = 0, sum = 0;
            for (int x = i - 1; x <= i + 1; x++) {
                for (int y = j - 1; y <= j + 1; y++) {
                    if (x >= 0 && x < m && y >= 0 && y < n) {
                        sum += img[x][y];
                        count++;
                    }
                }
            }
            result[i][j] = sum / count;
        }
    }

    return result;
}
```
1. Find the dimensions (m, n) of the input img array.
2. Initialize the result array with the same dimensions as img.
3. Iterate through each cell (i, j) of the img array.
4. Iterate through 8 neighboring cells with corresponding coordinates (x, y) within a 3x3 grid centered at (i, j).
5. Check if the neighboring cell (x, y) is within the boundaries of img. If so, add the value of img[x][y] to the sum, and increment the count.
6. Calculate the average by dividing the sum by count and round down the result.
7. Set the value of the result[i][j] to the calculated average.
8. Return the result array.

## A solution in C++

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

vector<vector<int>> imageSmoother(vector<vector<int>>& img) {
    int m = img.size(), n = img[0].size();
    vector<vector<int>> result(m, vector<int>(n, 0));

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            int count = 0, sum = 0;
            for (int x = i - 1; x <= i + 1; x++) {
                for (int y = j - 1; y <= j + 1; y++) {
                    if (x >= 0 && x < m && y >= 0 && y < n) {
                        sum += img[x][y];
                        count++;
                    }
                }
            }
            result[i][j] = sum / count;
        }
    }

    return result;
}
```
1. Find the dimensions (m, n) of the input img array.
2. Initialize the result array with the same dimensions as img.
3. Iterate through each cell (i, j) of the img array.
4. Iterate through 8 neighboring cells with corresponding coordinates (x, y) within a 3x3 grid centered at (i, j).
5. Check if the neighboring cell (x, y) is within the boundaries of img. If so, add the value of img[x][y] to the sum, and increment the count.
6. Calculate the average by dividing the sum by count and round down the result.
7. Set the value of the result[i][j] to the calculated average.
8. Return the result array.

## A solution in Python

```python
def imageSmoother(img):
    m, n = len(img), len(img[0])
    result = [[0] * n for _ in range(m)]

    for i in range(m):
        for j in range(n):
            count, total = 0, 0
            for x in range(i - 1, i + 2):
                for y in range(j - 1, j + 2):
                    if 0 <= x < m and 0 <= y < n:
                        total += img[x][y]
                        count += 1
            result[i][j] = total // count

    return result
```
1. Find the dimensions (m, n) of the input img array.
2. Initialize the result array with the same dimensions as img.
3. Iterate through each cell (i, j) of the img array.
4. Iterate through 8 neighboring cells with corresponding coordinates (x, y) within a 3x3 grid centered at (i, j).
5. Check if the neighboring cell (x, y) is within the boundaries of img. If so, add the value of img[x][y] to the sum, and increment the count.
6. Calculate the average by dividing the sum by count and round down the result.
7. Set the value of the result[i][j] to the calculated average.
8. Return the result array.

## A solution in Javascript

```javascript
function imageSmoother(img) {
    const m = img.length, n = img[0].length;
    const result = new Array(m).fill(0).map(() => new Array(n).fill(0));

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            let count = 0, sum = 0;

            for (let x = i - 1; x <= i + 1; x++) {
                for (let y = j - 1; y <= j + 1; y++) {
                    if (x >= 0 && x < m && y >= 0 && y < n) {
                        sum += img[x][y];
                        count++;
                    }
                }
            }
            result[i][j] = Math.floor(sum / count);
        }
    }

    return result;
}
```
1. Find the dimensions (m, n) of the input img array.
2. Initialize the result array with the same dimensions as img.
3. Iterate through each cell (i, j) of the img array.
4. Iterate through 8 neighboring cells with corresponding coordinates (x, y) within a 3x3 grid centered at (i, j).
5. Check if the neighboring cell (x, y) is within the boundaries of img. If so, add the value of img[x][y] to the sum, and increment the count.
6. Calculate the average by dividing the sum by count and round down the result.
7. Set the value of the result[i][j] to the calculated average.
8. Return the result array.


# Maximum Width of Binary Tree

- slug: maximum-width-of-binary-tree
- difficulty: Medium

Given the `root` of a binary tree, return _the **maximum width** of the given tree_.

The **maximum width** of a tree is the maximum **width** among all levels.

The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.

It is **guaranteed** that the answer will in the range of a **32-bit** signed integer.

**Example 1:**

**Input:** root = \[1,3,2,5,3,null,9\]
**Output:** 4
**Explanation:** The maximum width exists in the third level with length 4 (5,3,null,9).

**Example 2:**

**Input:** root = \[1,3,2,5,null,null,9,6,null,7\]
**Output:** 7
**Explanation:** The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).

**Example 3:**

**Input:** root = \[1,3,2,5\]
**Output:** 2
**Explanation:** The maximum width exists in the second level with length 2 (3,2).

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 3000]`.
*   `-100 <= Node.val <= 100`

## A solution in Java

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

public int widthOfBinaryTree(TreeNode root) {
    if (root == null) return 0;
    int maxWidth = 0;
    Queue<Pair> q = new LinkedList<>();
    q.offer(new Pair(root, 1));

    while (!q.isEmpty()) {
        int levelSize = q.size();
        int left = q.peek().pos;
        int right = left;
        for (int i = 0; i < levelSize; i++) {
            Pair pair = q.poll();
            TreeNode node = pair.node;
            right = pair.pos;

            if (node.left != null) {
                q.offer(new Pair(node.left, 2 * right));
            }
            if (node.right != null) {
                q.offer(new Pair(node.right, 2 * right + 1));
            }
        }
        maxWidth = Math.max(maxWidth, right - left + 1);
    }

    return maxWidth;
}

class Pair {
    TreeNode node;
    int pos;

    public Pair(TreeNode node, int pos) {
        this.node = node;
        this.pos = pos;
    }
}
```
The algorithm is a BFS (breadth-first search) traversal of the binary tree. We use a queue to store the nodes and their positions in the tree, with the root node at position 1.

For each level of the tree, we find the first and last nodes in the queue, and calculate their widths by subtracting the position of the first node from the position of the last node, adding 1 to get the width of that level. Then, we compare this width to the maximum width seen so far and update the maximum width if needed.

We repeat this process until the whole tree has been traversed, and return the maximum width.

## A solution in C++

```cpp
#include <queue>
#include <utility>

int widthOfBinaryTree(TreeNode* root) {
    if (!root) return 0;
    int maxWidth = 0;
    std::queue<std::pair<TreeNode*, int>> q;
    q.push(std::make_pair(root, 1));

    while (!q.empty()) {
        int levelSize = q.size();
        int left = q.front().second;
        int right = left;
        for (int i = 0; i < levelSize; i++) {
            TreeNode* node = q.front().first;
            right = q.front().second;
            q.pop();

            if (node->left) {
                q.push(std::make_pair(node->left, 2 * right));
            }
            if (node->right) {
                q.push(std::make_pair(node->right, 2 * right + 1));
            }
        }
        maxWidth = std::max(maxWidth, right - left + 1);
    }
    return maxWidth;
}
```
The algorithm is a BFS (breadth-first search) traversal of the binary tree. We use a queue to store the nodes and their positions in the tree, with the root node at position 1.

For each level of the tree, we find the first and last nodes in the queue, and calculate their widths by subtracting the position of the first node from the position of the last node, adding 1 to get the width of that level. Then, we compare this width to the maximum width seen so far and update the maximum width if needed.

We repeat this process until the whole tree has been traversed, and return the maximum width.

## A solution in Python

```python
from collections import deque

def widthOfBinaryTree(root):
    if not root:
        return 0

    maxWidth = 0
    q = deque([(root, 1)])

    while q:
        levelSize = len(q)
        left, _ = q[0]
        right = left
        for _ in range(levelSize):
            node, pos = q.popleft()
            right = pos

            if node.left:
                q.append((node.left, 2 * pos))
            if node.right:
                q.append((node.right, 2 * pos + 1))

        maxWidth = max(maxWidth, right - left + 1)

    return maxWidth
```
The algorithm is a BFS (breadth-first search) traversal of the binary tree. We use a queue to store the nodes and their positions in the tree, with the root node at position 1.

For each level of the tree, we find the first and last nodes in the queue, and calculate their widths by subtracting the position of the first node from the position of the last node, adding 1 to get the width of that level. Then, we compare this width to the maximum width seen so far and update the maximum width if needed.

We repeat this process until the whole tree has been traversed, and return the maximum width.

## A solution in Javascript

```javascript
function widthOfBinaryTree(root) {
    if (!root) return 0;
    let maxWidth = 0;
    const q = [[root, 1]];

    while (q.length) {
        const levelSize = q.length;
        let left = q[0][1];
        let right = left;

        for (let i = 0; i < levelSize; i++) {
            const [node, pos] = q.shift();
            right = pos;

            if (node.left) {
                q.push([node.left, 2 * pos]);
            }
            if (node.right) {
                q.push([node.right, 2 * pos + 1]);
            }
        }
        maxWidth = Math.max(maxWidth, right - left + 1);
    }

    return maxWidth;
}
```
The algorithm is a BFS (breadth-first search) traversal of the binary tree. We use a queue to store the nodes and their positions in the tree, with the root node at position 1.

For each level of the tree, we find the first and last nodes in the queue, and calculate their widths by subtracting the position of the first node from the position of the last node, adding 1 to get the width of that level. Then, we compare this width to the maximum width seen so far and update the maximum width if needed.

We repeat this process until the whole tree has been traversed, and return the maximum width.


# Equal Tree Partition

- slug: equal-tree-partition
- difficulty: Medium

Given the `root` of a binary tree, return `true` _if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree_.

**Example 1:**

**Input:** root = \[5,10,10,null,null,2,3\]
**Output:** true

**Example 2:**

**Input:** root = \[1,2,10,null,null,2,20\]
**Output:** false
**Explanation:** You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 104]`.
*   `-105 <= Node.val <= 105`

## A solution in Java

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

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

class Solution {
    public boolean checkEqualTree(TreeNode root) {
        Set<Integer> seen = new HashSet<>();
        int total = sum(root, seen);
        if (total % 2 == 0) {
            seen.remove(total);
            return seen.contains(total / 2);
        }
        return false;
    }

    private int sum(TreeNode node, Set<Integer> seen) {
        if (node == null) return 0;
        int s = node.val + sum(node.left, seen) + sum(node.right, seen);
        seen.add(s);
        return s;
    }
}
```
The algorithm does a post-order traversal of the tree and calculates the sums of the subtrees as it traverses. It stores these sums in a set (or unordered_set in C++). Then, it checks if the set contains a value equal to half the total sum of the tree. If it does, that means there is a subtree with equal sum to the other half of the tree after removing one edge (which connects the subtree to the main tree). If the total sum is odd, it is not possible to divide the tree into two equal parts and it returns false.

## A solution in C++

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

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

class Solution {
public:
    bool checkEqualTree(TreeNode* root) {
        unordered_set<int> seen;
        int total = sum(root, seen);
        if(total % 2 == 0) {
            seen.erase(total);
            return seen.count(total / 2);
        }
        return false;
    }
    int sum(TreeNode* node, unordered_set<int>& seen) {
        if (!node) return 0;
        int s = node->val + sum(node->left, seen) + sum(node->right, seen);
        seen.insert(s);
        return s;
    }
};
```
The algorithm does a post-order traversal of the tree and calculates the sums of the subtrees as it traverses. It stores these sums in a set (or unordered_set in C++). Then, it checks if the set contains a value equal to half the total sum of the tree. If it does, that means there is a subtree with equal sum to the other half of the tree after removing one edge (which connects the subtree to the main tree). If the total sum is odd, it is not possible to divide the tree into two equal parts and it returns false.

## A solution in Python

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

class Solution:
    def checkEqualTree(self, root: TreeNode) -> bool:
        def _sum(node, seen):
            if not node:
                return 0
            s = node.val + _sum(node.left, seen) + _sum(node.right, seen)
            seen.add(s)
            return s

        seen = set()
        total = _sum(root, seen)
        return total % 2 == 0 and (total // 2) in seen
```
The algorithm does a post-order traversal of the tree and calculates the sums of the subtrees as it traverses. It stores these sums in a set (or unordered_set in C++). Then, it checks if the set contains a value equal to half the total sum of the tree. If it does, that means there is a subtree with equal sum to the other half of the tree after removing one edge (which connects the subtree to the main tree). If the total sum is odd, it is not possible to divide the tree into two equal parts and it returns false.

## A solution in Javascript

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

var checkEqualTree = function(root) {
    let seen = new Set();
    let total = sum(root, seen);
    if (total % 2 === 0) {
        seen.delete(total);
        return seen.has(total / 2)
    }
    return false;

    function sum(node, seen) {
        if (!node) return 0;
        let s = node.val + sum(node.left, seen) + sum(node.right, seen)
        seen.add(s);
        return s;
    }
};
```
The algorithm does a post-order traversal of the tree and calculates the sums of the subtrees as it traverses. It stores these sums in a set (or unordered_set in C++). Then, it checks if the set contains a value equal to half the total sum of the tree. If it does, that means there is a subtree with equal sum to the other half of the tree after removing one edge (which connects the subtree to the main tree). If the total sum is odd, it is not possible to divide the tree into two equal parts and it returns false.


# Strange Printer

- slug: strange-printer
- difficulty: Hard

There is a strange printer with the following two special properties:

*   The printer can only print a sequence of **the same character** each time.
*   At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.

Given a string `s`, return _the minimum number of turns the printer needed to print it_.

**Example 1:**

**Input:** s =  "aaabbb "
**Output:** 2
**Explanation:** Print  "aaa " first and then print  "bbb ".

**Example 2:**

**Input:** s =  "aba "
**Output:** 2
**Explanation:** Print  "aaa " first and then print  "b " from the second place of the string, which will cover the existing character 'a'.

**Constraints:**

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

## A solution in Java

```java
int strangePrinter(String s) {
    int n = s.length();
    if(n == 0) return 0;
    int[][] dp = new int[n][n];
    for(int i = 0; i < n; i++) dp[i][i] = 1;
    for(int len = 1; len < n; len++) {
        for(int i = 0; i < n - len; i++) {
            int j = i + len;
            dp[i][j] = dp[i+1][j] + 1;
            for(int k = i + 1; k <= j; k++) {
                if(s.charAt(i) == s.charAt(k)) {
                    dp[i][j] = Math.min(dp[i][j], dp[i+1][k-1] + dp[k][j]);
                }
            }
        }
    }
    return dp[0][n-1];
}
```
1. Initialize a DP table `dp` of size `n x n` where `n` is the length of the input string `s`.
2. Fill the diagonal of the DP table with 1 since it takes one turn to print a single character.
3. Iterate through subproblems of increasing length using a nested loop.
4. For each subproblem, initialize `dp[i][j]` as `dp[i+1][j] + 1` assuming it takes one more turn to print the character at the current `i`.
5. Loop through `k` from `i + 1` to `j`. If the character at `i` matches the character at `k`, update `dp[i][j]` by taking the minimum of its current value and the sum of turns for two non-overlapping subproblems `dp[i+1][k-1]` and `dp[k][j]`.
6. The answer is stored at `dp[0][n-1]`.

## A solution in C++

```cpp
int strangePrinter(string s) {
    int n = s.size();
    if(n == 0) return 0;
    vector<vector<int>> dp(n, vector<int>(n, 0));
    for(int i = 0; i < n; i++) dp[i][i] = 1;
    for(int len = 1; len < n; len++) {
        for(int i = 0; i < n - len; i++) {
            int j = i + len;
            dp[i][j] = dp[i+1][j] + 1;
            for(int k = i + 1; k <= j; k++) {
                if(s[i] == s[k]) {
                    dp[i][j] = min(dp[i][j], dp[i+1][k-1] + dp[k][j]);
                }
            }
        }
    }
    return dp[0][n-1];
}
```
1. Initialize a DP table `dp` of size `n x n` where `n` is the length of the input string `s`.
2. Fill the diagonal of the DP table with 1 since it takes one turn to print a single character.
3. Iterate through subproblems of increasing length using a nested loop.
4. For each subproblem, initialize `dp[i][j]` as `dp[i+1][j] + 1` assuming it takes one more turn to print the character at the current `i`.
5. Loop through `k` from `i + 1` to `j`. If the character at `i` matches the character at `k`, update `dp[i][j]` by taking the minimum of its current value and the sum of turns for two non-overlapping subproblems `dp[i+1][k-1]` and `dp[k][j]`.
6. The answer is stored at `dp[0][n-1]`.

## A solution in Python

```python
def strange_printer(s: str) -> int:
    n = len(s)
    if n == 0: return 0
    dp = [[0] * n for _ in range(n)]
    for i in range(n):
        dp[i][i] = 1
    for len in range(1, n):
        for i in range(n - len):
            j = i + len
            dp[i][j] = dp[i+1][j] + 1
            for k in range(i + 1, j + 1):
                if s[i] == s[k]:
                    dp[i][j] = min(dp[i][j], dp[i+1][k-1] + dp[k][j])
    return dp[0][n-1]
```
1. Initialize a DP table `dp` of size `n x n` where `n` is the length of the input string `s`.
2. Fill the diagonal of the DP table with 1 since it takes one turn to print a single character.
3. Iterate through subproblems of increasing length using a nested loop.
4. For each subproblem, initialize `dp[i][j]` as `dp[i+1][j] + 1` assuming it takes one more turn to print the character at the current `i`.
5. Loop through `k` from `i + 1` to `j`. If the character at `i` matches the character at `k`, update `dp[i][j]` by taking the minimum of its current value and the sum of turns for two non-overlapping subproblems `dp[i+1][k-1]` and `dp[k][j]`.
6. The answer is stored at `dp[0][n-1]`.

## A solution in Javascript

```javascript
function strangePrinter(s) {
    let n = s.length;
    if(n === 0) return 0;
    const dp = Array.from({ length: n }, () => Array(n).fill(0));
    for(let i = 0; i < n; i++) dp[i][i] = 1;
    for(let len = 1; len < n; len++) {
        for(let i = 0; i < n - len; i++) {
            let j = i + len;
            dp[i][j] = dp[i+1][j] + 1;
            for(let k = i + 1; k <= j; k++) {
                if(s.charAt(i) === s.charAt(k)) {
                    dp[i][j] = Math.min(dp[i][j], dp[i+1][k-1] + dp[k][j]);
                }
            }
        }
    }
    return dp[0][n-1];
}
```
1. Initialize a DP table `dp` of size `n x n` where `n` is the length of the input string `s`.
2. Fill the diagonal of the DP table with 1 since it takes one turn to print a single character.
3. Iterate through subproblems of increasing length using a nested loop.
4. For each subproblem, initialize `dp[i][j]` as `dp[i+1][j] + 1` assuming it takes one more turn to print the character at the current `i`.
5. Loop through `k` from `i + 1` to `j`. If the character at `i` matches the character at `k`, update `dp[i][j]` by taking the minimum of its current value and the sum of turns for two non-overlapping subproblems `dp[i+1][k-1]` and `dp[k][j]`.
6. The answer is stored at `dp[0][n-1]`.


# Non-decreasing Array

- slug: non-decreasing-array
- difficulty: Medium

Given an array `nums` with `n` integers, your task is to check if it could become non-decreasing by modifying **at most one element**.

We define an array is non-decreasing if `nums[i] <= nums[i + 1]` holds for every `i` (**0-based**) such that (`0 <= i <= n - 2`).

**Example 1:**

**Input:** nums = \[4,2,3\]
**Output:** true
**Explanation:** You could modify the first 4 to 1 to get a non-decreasing array.

**Example 2:**

**Input:** nums = \[4,2,1\]
**Output:** false
**Explanation:** You cannot get a non-decreasing array by modifying at most one element.

**Constraints:**

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

## A solution in Java

```java
public boolean checkPossibility(int[] nums) {
    int cnt = 0;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] < nums[i - 1]) {
            cnt++;
            if (i == 1 || nums[i] >= nums[i - 2]) {
                nums[i-1] = nums[i];
            } else {
                nums[i] = nums[i - 1];
            }
            if (cnt > 1) return false;
        }
    }
    return true;
}
```
We iterate through the given array and, if we find a decreasing pair, we increment a counter `cnt`. We then modify either the current element or the previous element to make the array non-decreasing, choosing the optimal modification based on a comparison with the element two positions before. If we find more than one decreasing pair, we return false, as it implies that we need to modify more than one element to make the array non-decreasing. If we reach the end of the iteration, we return true, as the array could be made non-decreasing by modifying at most one element.

## A solution in C++

```cpp
bool checkPossibility(vector<int>& nums) {
    int cnt = 0;
    for (int i = 1; i < nums.size(); i++) {
        if (nums[i] < nums[i - 1]) {
            cnt++;
            if (i == 1 || nums[i] >= nums[i - 2]) {
                nums[i-1] = nums[i];
            } else {
                nums[i] = nums[i - 1];
            }
            if (cnt > 1) return false;
        }
    }
    return true;
}
```
We iterate through the given array and, if we find a decreasing pair, we increment a counter `cnt`. We then modify either the current element or the previous element to make the array non-decreasing, choosing the optimal modification based on a comparison with the element two positions before. If we find more than one decreasing pair, we return false, as it implies that we need to modify more than one element to make the array non-decreasing. If we reach the end of the iteration, we return true, as the array could be made non-decreasing by modifying at most one element.

## A solution in Python

```python
def checkPossibility(nums):
    cnt = 0
    for i in range(1, len(nums)):
        if nums[i] < nums[i - 1]:
            cnt += 1
            if i == 1 or nums[i] >= nums[i - 2]:
                nums[i-1] = nums[i]
            else:
                nums[i] = nums[i - 1]
            if cnt > 1:
                return False
    return True
```
We iterate through the given array and, if we find a decreasing pair, we increment a counter `cnt`. We then modify either the current element or the previous element to make the array non-decreasing, choosing the optimal modification based on a comparison with the element two positions before. If we find more than one decreasing pair, we return false, as it implies that we need to modify more than one element to make the array non-decreasing. If we reach the end of the iteration, we return true, as the array could be made non-decreasing by modifying at most one element.

## A solution in Javascript

```javascript
function checkPossibility(nums) {
    let cnt = 0;
    for (let i = 1; i < nums.length; i++) {
        if (nums[i] < nums[i - 1]) {
            cnt++;
            if (i === 1 || nums[i] >= nums[i - 2]) {
                nums[i-1] = nums[i];
            } else {
                nums[i] = nums[i - 1];
            }
            if (cnt > 1) return false;
        }
    }
    return true;
}
```
We iterate through the given array and, if we find a decreasing pair, we increment a counter `cnt`. We then modify either the current element or the previous element to make the array non-decreasing, choosing the optimal modification based on a comparison with the element two positions before. If we find more than one decreasing pair, we return false, as it implies that we need to modify more than one element to make the array non-decreasing. If we reach the end of the iteration, we return true, as the array could be made non-decreasing by modifying at most one element.


# Path Sum IV

- slug: path-sum-iv
- difficulty: Medium

If the depth of a tree is smaller than `5`, then this tree can be represented by an array of three-digit integers. For each integer in this array:

*   The hundreds digit represents the depth `d` of this node where `1 <= d <= 4`.
*   The tens digit represents the position `p` of this node in the level it belongs to where `1 <= p <= 8`. The position is the same as that in a full binary tree.
*   The units digit represents the value `v` of this node where `0 <= v <= 9`.

Given an array of **ascending** three-digit integers `nums` representing a binary tree with a depth smaller than `5`, return _the sum of all paths from the root towards the leaves_.

It is **guaranteed** that the given array represents a valid connected binary tree.

**Example 1:**

**Input:** nums = \[113,215,221\]
**Output:** 12
**Explanation:** The tree that the list represents is shown.
The path sum is (3 + 5) + (3 + 1) = 12.

**Example 2:**

**Input:** nums = \[113,221\]
**Output:** 4
**Explanation:** The tree that the list represents is shown.
The path sum is (3 + 1) = 4.

**Constraints:**

*   `1 <= nums.length <= 15`
*   `110 <= nums[i] <= 489`
*   `nums` represents a valid binary tree with depth less than `5`.

## A solution in Java

```java
public int sum(TreeNode root, int val) {
    if (root == null) return 0;
    val = val * 10 + root.val;
    if (root.left == null && root.right == null) return val;
    return sum(root.left, val) + sum(root.right, val);
}

public int pathSum(int[] nums) {
    TreeNode root = new TreeNode(nums[0] % 10);
    for (int num : nums) {
        int depth = num / 100;
        int pos = num % 100 / 10;
        int val = num % 10;
        TreeNode cur = root;
        for (int d = depth - 2; d >= 0; --d) {
            if ((pos >> d) & 1) {
                if (cur.right == null) cur.right = new TreeNode(val);
                cur = cur.right;
            } else {
                if (cur.left == null) cur.left = new TreeNode(val);
                cur = cur.left;
            }
        }
    }
    return sum(root, 0);
}
```
The algorithm builds the binary tree from the input array `nums`, constructs a TreeNode for each element in `nums`:
1. The TreeNode constructor takes the value of the node, which is the units digit.
2. The element is then divided by 100 to get the depth, and modulo 100 is taken and then divided by 10 to get the position.
3. Traversing level by level, the nodes are inserted, updating the left or right child pointer accordingly.

After building the tree, the `sum` function is called to calculate the path sum of the tree, passing the root node and the current sum value as parameters. It recursively calculates the path sum for each child, updating the sum and returning it when the leaf node is reached.

At the end, the total path sum is returned.

## A solution in C++

```cpp
int sum(TreeNode* root, int val) {
    if (!root) return 0;
    val = val * 10 + root->val;
    if (!root->left && !root->right) return val;
    return sum(root->left, val) + sum(root->right, val);
}

int pathSum(vector<int>& nums) {
    TreeNode* root = new TreeNode(nums[0] % 10);
    for (int num : nums) {
        int depth = num / 100, pos = num % 100 / 10, val = num % 10;
        TreeNode* cur = root;
        for (int d = depth - 2; d >= 0; --d) {
            if ((pos >> d) & 1) {
                if (!cur->right) cur->right = new TreeNode(val);
                cur = cur->right;
            } else {
                if (!cur->left) cur->left = new TreeNode(val);
                cur = cur->left;
            }
        }
    }
    return sum(root, 0);
}
```
The algorithm builds the binary tree from the input array `nums`, constructs a TreeNode for each element in `nums`:
1. The TreeNode constructor takes the value of the node, which is the units digit.
2. The element is then divided by 100 to get the depth, and modulo 100 is taken and then divided by 10 to get the position.
3. Traversing level by level, the nodes are inserted, updating the left or right child pointer accordingly.

After building the tree, the `sum` function is called to calculate the path sum of the tree, passing the root node and the current sum value as parameters. It recursively calculates the path sum for each child, updating the sum and returning it when the leaf node is reached.

At the end, the total path sum is returned.

## A solution in Python

```python
def sumPaths(root, val):
    if not root: return 0
    val = val * 10 + root.val
    if not root.left and not root.right: return val
    return sumPaths(root.left, val) + sumPaths(root.right, val)

def pathSum(nums):
    root = TreeNode(nums[0] % 10)
    for num in nums:
        depth, pos, val = num // 100, num % 100 // 10, num % 10
        cur = root
        for d in reversed(range(depth - 1)):
            if (pos >> d) & 1:
                if not cur.right: cur.right = TreeNode(val)
                cur = cur.right
            else:
                if not cur.left: cur.left = TreeNode(val)
                cur = cur.left
    return sumPaths(root, 0)
```
The algorithm builds the binary tree from the input array `nums`, constructs a TreeNode for each element in `nums`:
1. The TreeNode constructor takes the value of the node, which is the units digit.
2. The element is then divided by 100 to get the depth, and modulo 100 is taken and then divided by 10 to get the position.
3. Traversing level by level, the nodes are inserted, updating the left or right child pointer accordingly.

After building the tree, the `sum` function is called to calculate the path sum of the tree, passing the root node and the current sum value as parameters. It recursively calculates the path sum for each child, updating the sum and returning it when the leaf node is reached.

At the end, the total path sum is returned.

## A solution in Javascript

```javascript
function sum(root, val) {
    if (!root) return 0;
    val = val * 10 + root.val;
    if (!root.left && !root.right) return val;
    return sum(root.left, val) + sum(root.right, val);
}

function pathSum(nums) {
    const root = new TreeNode(nums[0] % 10);
    for (const num of nums) {
        const depth = Math.floor(num / 100);
        const pos = Math.floor(num % 100 / 10);
        const val = num % 10;
        let cur = root;
        for (let d = depth - 2; d >= 0; --d) {
            if ((pos >> d) & 1) {
                if (!cur.right) cur.right = new TreeNode(val);
                cur = cur.right;
            } else {
                if (!cur.left) cur.left = new TreeNode(val);
                cur = cur.left;
            }
        }
    }
    return sum(root, 0);
}
```
The algorithm builds the binary tree from the input array `nums`, constructs a TreeNode for each element in `nums`:
1. The TreeNode constructor takes the value of the node, which is the units digit.
2. The element is then divided by 100 to get the depth, and modulo 100 is taken and then divided by 10 to get the position.
3. Traversing level by level, the nodes are inserted, updating the left or right child pointer accordingly.

After building the tree, the `sum` function is called to calculate the path sum of the tree, passing the root node and the current sum value as parameters. It recursively calculates the path sum for each child, updating the sum and returning it when the leaf node is reached.

At the end, the total path sum is returned.


# Beautiful Arrangement II

- slug: beautiful-arrangement-ii
- difficulty: Medium

Given two integers `n` and `k`, construct a list `answer` that contains `n` different positive integers ranging from `1` to `n` and obeys the following requirement:

*   Suppose this list is `answer = [a1, a2, a3, ... , an]`, then the list `[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]` has exactly `k` distinct integers.

Return _the list_ `answer`. If there multiple valid answers, return **any of them**.

**Example 1:**

**Input:** n = 3, k = 1
**Output:** \[1,2,3\]
Explanation: The \[1,2,3\] has three different positive integers ranging from 1 to 3, and the \[1,1\] has exactly 1 distinct integer: 1

**Example 2:**

**Input:** n = 3, k = 2
**Output:** \[1,3,2\]
Explanation: The \[1,3,2\] has three different positive integers ranging from 1 to 3, and the \[2,1\] has exactly 2 distinct integers: 1 and 2.

**Constraints:**

*   `1 <= k < n <= 104`

## A solution in Java

```java
import java.util.ArrayList;

class Solution {
    public List<Integer> constructArray(int n, int k) {
        ArrayList<Integer> answer = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                answer.add(i / 2 + 1);
            } else {
                answer.add(n - (i - 1) / 2);
                k--;
            }
        }
        if (k > 0) {
            for (int i = n - 2; i >= 0 && k > 0; i--) {
                answer.set(i, answer.get(i + 1) - answer.get(i));
                k--;
            }
        }
        return answer;
    }
}
```
1. Initialize an answer list of size n.
2. Loop through the range from 0 to n:
   a. If the index is even, place the value i / 2 + 1 at the current index.
   b. If the index is odd, place the value n - (i - 1) / 2 at the current index, then decrement k.
3. If k is still greater than 0, loop through the range from n - 2 to 0 (in reverse order):
   a. If k is greater than 0, update the value at the current index to the difference between the values at the indices i + 1 and i, then decrement k.
4. Return the answer list.

## A solution in C++

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

vector<int> constructArray(int n, int k) {
    vector<int> answer(n);
    for (int i = 0; i < n; ++i) {
        if (i % 2 == 0) {
            answer[i] = i / 2 + 1;
        } else {
            answer[i] = n - (i - 1) / 2;
            --k;
        }
    }
    if (k > 0) {
        for (int i = n - 2; i >= 0 && k > 0; --i) {
            answer[i] = answer[i + 1] - answer[i];
            --k;
        }
    }
    return answer;
}
```
1. Initialize an answer list of size n.
2. Loop through the range from 0 to n:
   a. If the index is even, place the value i / 2 + 1 at the current index.
   b. If the index is odd, place the value n - (i - 1) / 2 at the current index, then decrement k.
3. If k is still greater than 0, loop through the range from n - 2 to 0 (in reverse order):
   a. If k is greater than 0, update the value at the current index to the difference between the values at the indices i + 1 and i, then decrement k.
4. Return the answer list.

## A solution in Python

```python
def constructArray(n: int, k: int) -> List[int]:
    answer = [0] * n
    for i in range(n):
        if i % 2 == 0:
            answer[i] = i // 2 + 1
        else:
            answer[i] = n - (i - 1) // 2
            k -= 1
    if k > 0:
        for i in range(n - 2, -1, -1):
            if k > 0:
                answer[i] = answer[i + 1] - answer[i]
                k -= 1
    return answer
```
1. Initialize an answer list of size n.
2. Loop through the range from 0 to n:
   a. If the index is even, place the value i / 2 + 1 at the current index.
   b. If the index is odd, place the value n - (i - 1) / 2 at the current index, then decrement k.
3. If k is still greater than 0, loop through the range from n - 2 to 0 (in reverse order):
   a. If k is greater than 0, update the value at the current index to the difference between the values at the indices i + 1 and i, then decrement k.
4. Return the answer list.

## A solution in Javascript

```javascript
function constructArray(n, k) {
    let answer = new Array(n);
    for (let i = 0; i < n; i++) {
        if (i % 2 === 0) {
            answer[i] = i / 2 + 1;
        } else {
            answer[i] = n - ((i - 1) / 2);
            k--;
        }
    }
    if (k > 0) {
        for (let i = n - 2; i >= 0 && k > 0; i--) {
            answer[i] = answer[i + 1] - answer[i];
            k--;
        }
    }
    return answer;
}
```
1. Initialize an answer list of size n.
2. Loop through the range from 0 to n:
   a. If the index is even, place the value i / 2 + 1 at the current index.
   b. If the index is odd, place the value n - (i - 1) / 2 at the current index, then decrement k.
3. If k is still greater than 0, loop through the range from n - 2 to 0 (in reverse order):
   a. If k is greater than 0, update the value at the current index to the difference between the values at the indices i + 1 and i, then decrement k.
4. Return the answer list.


# Kth Smallest Number in Multiplication Table

- slug: kth-smallest-number-in-multiplication-table
- difficulty: Hard

Nearly everyone has used the [Multiplication Table](https://en.wikipedia.org/wiki/Multiplication_table). The multiplication table of size `m x n` is an integer matrix `mat` where `mat[i][j] == i * j` (**1-indexed**).

Given three integers `m`, `n`, and `k`, return _the_ `kth` _smallest element in the_ `m x n` _multiplication table_.

**Example 1:**

**Input:** m = 3, n = 3, k = 5
**Output:** 3
**Explanation:** The 5th smallest number is 3.

**Example 2:**

**Input:** m = 2, n = 3, k = 6
**Output:** 6
**Explanation:** The 6th smallest number is 6.

**Constraints:**

*   `1 <= m, n <= 3 * 104`
*   `1 <= k <= m * n`

## A solution in Java

```java
public int findKthNumber(int m, int n, int k) {
    int low = 1, high = m * n;
    while (low < high) {
        int mid = low + (high - low) / 2;
        int count = 0;
        for (int i = 1; i <= m; i++) {
            count += Math.min(mid / i, n);
        }
        if (count < k) {
            low = mid + 1;
        } else {
            high = mid;
        }
    }
    return low;
}
```
We need to find the kth smallest element in an m x n multiplication table. The table is naturally sorted, so we can use binary search to find the desired element. We start with `low` as 1 and `high` as m * n. Our search space is between these values.

In each iteration, we look for the middle value `mid`. For each row `i`, we count the number of elements that are less than or equal to `mid`. The count is the sum of either `mid // i` or `n`, whichever is smaller. Then we check if the count is less than or equal to `k`. If it is, we move `low` to `mid + 1`; otherwise, we move `high` to `mid`. Once the search space narrowed down to a single value, we return that value as the kth smallest element in the m x n multiplication table.

## A solution in C++

```cpp
int findKthNumber(int m, int n, int k) {
    int low = 1, high = m * n;
    while (low < high) {
        int mid = low + (high - low) / 2;
        int count = 0;
        for (int i = 1; i <= m; i++) {
            count += std::min(mid / i, n);
        }
        if (count < k) {
            low = mid + 1;
        } else {
            high = mid;
        }
    }
    return low;
}
```
We need to find the kth smallest element in an m x n multiplication table. The table is naturally sorted, so we can use binary search to find the desired element. We start with `low` as 1 and `high` as m * n. Our search space is between these values.

In each iteration, we look for the middle value `mid`. For each row `i`, we count the number of elements that are less than or equal to `mid`. The count is the sum of either `mid // i` or `n`, whichever is smaller. Then we check if the count is less than or equal to `k`. If it is, we move `low` to `mid + 1`; otherwise, we move `high` to `mid`. Once the search space narrowed down to a single value, we return that value as the kth smallest element in the m x n multiplication table.

## A solution in Python

```python
def findKthNumber(m, n, k):
    low, high = 1, m * n
    while low < high:
        mid = low + (high - low) // 2
        count = 0
        for i in range(1, m+1):
            count += min(mid // i, n)
        if count < k:
            low = mid + 1
        else:
            high = mid
    return low
```
We need to find the kth smallest element in an m x n multiplication table. The table is naturally sorted, so we can use binary search to find the desired element. We start with `low` as 1 and `high` as m * n. Our search space is between these values.

In each iteration, we look for the middle value `mid`. For each row `i`, we count the number of elements that are less than or equal to `mid`. The count is the sum of either `mid // i` or `n`, whichever is smaller. Then we check if the count is less than or equal to `k`. If it is, we move `low` to `mid + 1`; otherwise, we move `high` to `mid`. Once the search space narrowed down to a single value, we return that value as the kth smallest element in the m x n multiplication table.

## A solution in Javascript

```javascript
function findKthNumber(m, n, k) {
    let low = 1, high = m * n;
    while (low < high) {
        let mid = low + Math.floor((high - low) / 2);
        let count = 0;
        for (let i = 1; i <= m; i++) {
            count += Math.min(Math.floor(mid / i), n);
        }
        if (count < k) {
            low = mid + 1;
        } else {
            high = mid;
        }
    }
    return low;
}
```
We need to find the kth smallest element in an m x n multiplication table. The table is naturally sorted, so we can use binary search to find the desired element. We start with `low` as 1 and `high` as m * n. Our search space is between these values.

In each iteration, we look for the middle value `mid`. For each row `i`, we count the number of elements that are less than or equal to `mid`. The count is the sum of either `mid // i` or `n`, whichever is smaller. Then we check if the count is less than or equal to `k`. If it is, we move `low` to `mid + 1`; otherwise, we move `high` to `mid`. Once the search space narrowed down to a single value, we return that value as the kth smallest element in the m x n multiplication table.


# Trim a Binary Search Tree

- slug: trim-a-binary-search-tree
- difficulty: Medium

Given the `root` of a binary search tree and the lowest and highest boundaries as `low` and `high`, trim the tree so that all its elements lies in `[low, high]`. Trimming the tree should **not** change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a **unique answer**.

Return _the root of the trimmed binary search tree_. Note that the root may change depending on the given bounds.

**Example 1:**

**Input:** root = \[1,0,2\], low = 1, high = 2
**Output:** \[1,null,2\]

**Example 2:**

**Input:** root = \[3,0,4,null,2,null,null,1\], low = 1, high = 3
**Output:** \[3,2,null,1\]

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 104]`.
*   `0 <= Node.val <= 104`
*   The value of each node in the tree is **unique**.
*   `root` is guaranteed to be a valid binary search tree.
*   `0 <= low <= high <= 104`

## A solution in Java

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

public TreeNode trimBST(TreeNode root, int low, int high) {
    if (root == null) return null;

    if (root.val < low) {
        return trimBST(root.right, low, high);
    } else if (root.val > high) {
        return trimBST(root.left, low, high);
    } else {
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
    }

    return root;
}
```
The algorithm is a Depth-First Search that traverses the tree recursively. It checks each node's value against the given low and high boundaries.

1. If the node's value is less than the low boundary, we know that the entire left subtree is also less than the low boundary, so we can ignore it entirely and continue trimming the right subtree.
2. If the node's value is greater than the high boundary, similarly, we know that the entire right subtree is also greater than the high boundary, so we can ignore it entirely and continue trimming the left subtree.
3. If the node's value is within the low and high boundaries, then we trim the left and right subtrees independently and set the current node's left and right pointers to the trimmed subtrees.

The function returns the root of the trimmed subtree for each of the nodes.

Since we are only trimming the tree based on the valid bounds, the relative structure of the elements in the tree is preserved.

## A solution in C++

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

TreeNode* trimBST(TreeNode* root, int low, int high) {
    if (!root) return nullptr;

    if (root->val < low) {
        return trimBST(root->right, low, high);
    } else if (root->val > high) {
        return trimBST(root->left, low, high);
    } else {
        root->left = trimBST(root->left, low, high);
        root->right = trimBST(root->right, low, high);
    }

    return root;
}
```
The algorithm is a Depth-First Search that traverses the tree recursively. It checks each node's value against the given low and high boundaries.

1. If the node's value is less than the low boundary, we know that the entire left subtree is also less than the low boundary, so we can ignore it entirely and continue trimming the right subtree.
2. If the node's value is greater than the high boundary, similarly, we know that the entire right subtree is also greater than the high boundary, so we can ignore it entirely and continue trimming the left subtree.
3. If the node's value is within the low and high boundaries, then we trim the left and right subtrees independently and set the current node's left and right pointers to the trimmed subtrees.

The function returns the root of the trimmed subtree for each of the nodes.

Since we are only trimming the tree based on the valid bounds, the relative structure of the elements in the tree is preserved.

## A solution in Python

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

def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
    if not root:
        return None

    if root.val < low:
        return self.trimBST(root.right, low, high)
    elif root.val > high:
        return self.trimBST(root.left, low, high)
    else:
        root.left = self.trimBST(root.left, low, high)
        root.right = self.trimBST(root.right, low, high)

    return root
```
The algorithm is a Depth-First Search that traverses the tree recursively. It checks each node's value against the given low and high boundaries.

1. If the node's value is less than the low boundary, we know that the entire left subtree is also less than the low boundary, so we can ignore it entirely and continue trimming the right subtree.
2. If the node's value is greater than the high boundary, similarly, we know that the entire right subtree is also greater than the high boundary, so we can ignore it entirely and continue trimming the left subtree.
3. If the node's value is within the low and high boundaries, then we trim the left and right subtrees independently and set the current node's left and right pointers to the trimmed subtrees.

The function returns the root of the trimmed subtree for each of the nodes.

Since we are only trimming the tree based on the valid bounds, the relative structure of the elements in the tree is preserved.

## A solution in Javascript

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

function trimBST(root, low, high) {
    if (!root) return null;

    if (root.val < low) {
        return trimBST(root.right, low, high);
    } else if (root.val > high) {
        return trimBST(root.left, low, high);
    } else {
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
    }

    return root;
}
```
The algorithm is a Depth-First Search that traverses the tree recursively. It checks each node's value against the given low and high boundaries.

1. If the node's value is less than the low boundary, we know that the entire left subtree is also less than the low boundary, so we can ignore it entirely and continue trimming the right subtree.
2. If the node's value is greater than the high boundary, similarly, we know that the entire right subtree is also greater than the high boundary, so we can ignore it entirely and continue trimming the left subtree.
3. If the node's value is within the low and high boundaries, then we trim the left and right subtrees independently and set the current node's left and right pointers to the trimmed subtrees.

The function returns the root of the trimmed subtree for each of the nodes.

Since we are only trimming the tree based on the valid bounds, the relative structure of the elements in the tree is preserved.