# Partition Labels

- slug: partition-labels
- difficulty: Medium

You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part.

Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`.

Return _a list of integers representing the size of these parts_.

**Example 1:**

**Input:** s =  "ababcbacadefegdehijhklij "
**Output:** \[9,7,8\]
**Explanation:**
The partition is  "ababcbaca ",  "defegde ",  "hijhklij ".
This is a partition so that each letter appears in at most one part.
A partition like  "ababcbacadefegde ",  "hijhklij " is incorrect, because it splits s into less parts.

**Example 2:**

**Input:** s =  "eccbbbbdec "
**Output:** \[10\]

**Constraints:**

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

## A solution in Java

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

public List<Integer> partitionLabels(String s) {
    Map<Character, Integer> last = new HashMap<>();
    for (int i = 0; i < s.length(); i++) {
        last.put(s.charAt(i), i);
    }
    List<Integer> ans = new ArrayList<>();
    int j = 0, anchor = 0;
    for (int i = 0; i < s.length(); i++) {
        j = Math.max(j, last.get(s.charAt(i)));
        if (i == j) {
            ans.add(i - anchor + 1);
            anchor = i + 1;
        }
    }
    return ans;
}
```
The algorithm uses a greedy approach to solve the problem. In the first step, we loop through the input string and keep track of the last index of each character in a dictionary/hashmap. Then, we loop through the string again and keep track of the farthest index of the encountered characters. If the current index is equal to the farthest index of the encountered characters, then we know that we can partition the string at this index. We append the partition length to the answer list and update the anchor variable to the index after the current index. We continue this process for the entire input string and return the list of partition lengths.

## A solution in C++

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

std::vector<int> partitionLabels(std::string s) {
    std::unordered_map<char, int> last;
    for (int i = 0; i < s.size(); i++) {
        last[s[i]] = i;
    }
    std::vector<int> ans;
    int j = 0, anchor = 0;
    for (int i = 0; i < s.size(); i++) {
        j = std::max(j, last[s[i]]);
        if (i == j) {
            ans.push_back(i - anchor + 1);
            anchor = i + 1;
        }
    }
    return ans;
}
```
The algorithm uses a greedy approach to solve the problem. In the first step, we loop through the input string and keep track of the last index of each character in a dictionary/hashmap. Then, we loop through the string again and keep track of the farthest index of the encountered characters. If the current index is equal to the farthest index of the encountered characters, then we know that we can partition the string at this index. We append the partition length to the answer list and update the anchor variable to the index after the current index. We continue this process for the entire input string and return the list of partition lengths.

## A solution in Python

```python
def partition_labels(s):
    last = {c:i for i, c in enumerate(s)}
    ans = []
    j = anchor = 0
    for i, c in enumerate(s):
        j = max(j, last[c])
        if i == j:
            ans.append(i - anchor + 1)
            anchor = i + 1
    return ans
```
The algorithm uses a greedy approach to solve the problem. In the first step, we loop through the input string and keep track of the last index of each character in a dictionary/hashmap. Then, we loop through the string again and keep track of the farthest index of the encountered characters. If the current index is equal to the farthest index of the encountered characters, then we know that we can partition the string at this index. We append the partition length to the answer list and update the anchor variable to the index after the current index. We continue this process for the entire input string and return the list of partition lengths.

## A solution in Javascript

```javascript
function partitionLabels(s) {
    const last = {};
    for (let i = 0; i < s.length; i++) {
        last[s[i]] = i;
    }
    const ans = [];
    let j = 0, anchor = 0;
    for (let i = 0; i < s.length; i++) {
        j = Math.max(j, last[s[i]]);
        if (i === j) {
            ans.push(i - anchor + 1);
            anchor = i + 1;
        }
    }
    return ans;
}
```
The algorithm uses a greedy approach to solve the problem. In the first step, we loop through the input string and keep track of the last index of each character in a dictionary/hashmap. Then, we loop through the string again and keep track of the farthest index of the encountered characters. If the current index is equal to the farthest index of the encountered characters, then we know that we can partition the string at this index. We append the partition length to the answer list and update the anchor variable to the index after the current index. We continue this process for the entire input string and return the list of partition lengths.


# Largest Plus Sign

- slug: largest-plus-sign
- difficulty: Medium

You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`.

Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`.

An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s.

**Example 1:**

**Input:** n = 5, mines = \[\[4,2\]\]
**Output:** 2
**Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown.

**Example 2:**

**Input:** n = 1, mines = \[\[0,0\]\]
**Output:** 0
**Explanation:** There is no plus sign, so return 0.

**Constraints:**

*   `1 <= n <= 500`
*   `1 <= mines.length <= 5000`
*   `0 <= xi, yi < n`
*   All the pairs `(xi, yi)` are **unique**.

## A solution in Java

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

class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
}

public List<List<Integer>> levelOrder(Node root) {
    List<List<Integer>> result = new ArrayList<>();
    if (root == null) return result;

    Queue<Node> toVisit = new LinkedList<>();
    toVisit.offer(root);

    while (!toVisit.isEmpty()) {
        int size = toVisit.size();
        List<Integer> level = new ArrayList<>();

        for (int i = 0; i < size; i++) {
            Node currentNode = toVisit.poll();
            level.add(currentNode.val);

            for (Node child : currentNode.children) {
                toVisit.offer(child);
            }
        }
        result.add(level);
    }

    return result;
}
```
The algorithm uses a Breadth-First Search (BFS) traversal approach to traverse the n-ary tree level-by-level. A queue is used to keep track of nodes to visit at each level. The process starts by adding the root node to the queue. Then, while the queue is not empty, it continues to process nodes from the queue. For each node, we remove it from the queue, add its value to the current level, and add its children to the queue. This process continues for all nodes at the current level, and then the level is added to the result list. The algorithm continues until there are no more nodes in the queue.

In each language, the function first initializes an empty result list and a queue, adds the root node to the queue (if it is not null), and then traverses the tree using the BFS method described, adding the values of the nodes to the result list as it goes.

## A solution in C++

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

using std::vector;
using std::queue;

class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};

vector<vector<int>> levelOrder(Node* root) {
    vector<vector<int>> result;
    if (root == nullptr) return result;

    queue<Node*> toVisit;
    toVisit.push(root);

    while (!toVisit.empty()) {
        int size = toVisit.size();
        vector<int> level;

        for (int i = 0; i < size; i++) {
            Node* currentNode = toVisit.front();
            toVisit.pop();
            level.push_back(currentNode->val);

            for (Node* child : currentNode->children) {
                toVisit.push(child);
            }
        }
        result.push_back(level);
    }

    return result;
}
```
The algorithm uses a Breadth-First Search (BFS) traversal approach to traverse the n-ary tree level-by-level. A queue is used to keep track of nodes to visit at each level. The process starts by adding the root node to the queue. Then, while the queue is not empty, it continues to process nodes from the queue. For each node, we remove it from the queue, add its value to the current level, and add its children to the queue. This process continues for all nodes at the current level, and then the level is added to the result list. The algorithm continues until there are no more nodes in the queue.

In each language, the function first initializes an empty result list and a queue, adds the root node to the queue (if it is not null), and then traverses the tree using the BFS method described, adding the values of the nodes to the result list as it goes.

## A solution in Python

```python
from collections import deque

class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children if children is not None else []

def levelOrder(root):
    result = []

    if not root:
        return result

    toVisit = deque([root])

    while toVisit:
        size = len(toVisit)
        level = []

        for _ in range(size):
            currentNode = toVisit.popleft()
            level.append(currentNode.val)

            for child in currentNode.children:
                toVisit.append(child)

        result.append(level)

    return result
```
The algorithm uses a Breadth-First Search (BFS) traversal approach to traverse the n-ary tree level-by-level. A queue is used to keep track of nodes to visit at each level. The process starts by adding the root node to the queue. Then, while the queue is not empty, it continues to process nodes from the queue. For each node, we remove it from the queue, add its value to the current level, and add its children to the queue. This process continues for all nodes at the current level, and then the level is added to the result list. The algorithm continues until there are no more nodes in the queue.

In each language, the function first initializes an empty result list and a queue, adds the root node to the queue (if it is not null), and then traverses the tree using the BFS method described, adding the values of the nodes to the result list as it goes.

## A solution in Javascript

```javascript
class Node {
    constructor(val, children) {
        this.val = val;
        this.children = children;
    }
}

function levelOrder(root) {
    const result = [];
    if (!root) return result;

    const toVisit = [root];

    while (toVisit.length > 0) {
        const size = toVisit.length;
        const level = [];

        for (let i = 0; i < size; i++) {
            const currentNode = toVisit.shift();
            level.push(currentNode.val);

            for (const child of currentNode.children) {
                toVisit.push(child);
            }
        }
        result.push(level);
    }

    return result;
}
```
The algorithm uses a Breadth-First Search (BFS) traversal approach to traverse the n-ary tree level-by-level. A queue is used to keep track of nodes to visit at each level. The process starts by adding the root node to the queue. Then, while the queue is not empty, it continues to process nodes from the queue. For each node, we remove it from the queue, add its value to the current level, and add its children to the queue. This process continues for all nodes at the current level, and then the level is added to the result list. The algorithm continues until there are no more nodes in the queue.

In each language, the function first initializes an empty result list and a queue, adds the root node to the queue (if it is not null), and then traverses the tree using the BFS method described, adding the values of the nodes to the result list as it goes.


# Couples Holding Hands

- slug: couples-holding-hands
- difficulty: Hard

There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands.

The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, and so on with the last couple being `(2n - 2, 2n - 1)`.

Return _the minimum number of swaps so that every couple is sitting side by side_. A swap consists of choosing any two people, then they stand up and switch seats.

**Example 1:**

**Input:** row = \[0,2,1,3\]
**Output:** 1
**Explanation:** We only need to swap the second (row\[1\]) and third (row\[2\]) person.

**Example 2:**

**Input:** row = \[3,2,0,1\]
**Output:** 0
**Explanation:** All couples are already seated side by side.

**Constraints:**

*   `2n == row.length`
*   `2 <= n <= 30`
*   `n` is even.
*   `0 <= row[i] < 2n`
*   All the elements of `row` are **unique**.

## A solution in Java

```java
public int minSwapsCouples(int[] row) {
    int n = row.length;
    int[] position = new int[n];
    for (int i = 0; i < n; ++i)
        position[row[i]] = i;

    int swaps = 0;
    for (int i = 0; i < n; i += 2) {
        int partner = row[i] % 2 == 0 ? row[i] + 1 : row[i] - 1;
        if (row[i + 1] != partner) {
            int temp = row[position[partner]];
            row[position[partner]] = row[i + 1];
            row[i + 1] = temp;

            temp = position[row[i + 1]];
            position[row[i + 1]] = position[partner];
            position[partner] = temp;

            swaps++;
        }
    }
    return swaps;
}
```
The algorithm works by iterating through the array `row` in increments of 2, representing the couple's seats side by side. During the iteration, it checks if the couple's partner is sitting next to the current person, based on the fact that the partner would have an ID that is either one more or one less than the current person's ID.

If the partner is not sitting in the expected position, it then swaps the person sitting next to the current person with the partner. The positions of the people in the array are stored in a separate `position` array. The swap is done both in the `row` and `position` arrays, and the swap count is incremented.

After the entire iteration, the swap count represents the minimum number of swaps needed to arrange the couples side by side.

## A solution in C++

```cpp
int minSwapsCouples(vector<int>& row) {
    int n = row.size();
    vector<int> position(n);
    for (int i = 0; i < n; ++i)
        position[row[i]] = i;

    int swaps = 0;
    for (int i = 0; i < n; i += 2) {
        int partner = row[i] % 2 == 0 ? row[i] + 1 : row[i] - 1;
        if (row[i + 1] != partner) {
            swap(row[position[partner]], row[i + 1]);
            swap(position[row[i + 1]], position[partner]);
            swaps++;
        }
    }
    return swaps;
}
```
The algorithm works by iterating through the array `row` in increments of 2, representing the couple's seats side by side. During the iteration, it checks if the couple's partner is sitting next to the current person, based on the fact that the partner would have an ID that is either one more or one less than the current person's ID.

If the partner is not sitting in the expected position, it then swaps the person sitting next to the current person with the partner. The positions of the people in the array are stored in a separate `position` array. The swap is done both in the `row` and `position` arrays, and the swap count is incremented.

After the entire iteration, the swap count represents the minimum number of swaps needed to arrange the couples side by side.

## A solution in Python

```python
def minSwapsCouples(row):
    n = len(row)
    position = [0] * n
    for i in range(n):
        position[row[i]] = i

    swaps = 0
    for i in range(0, n, 2):
        partner = row[i] + 1 if row[i] % 2 == 0 else row[i] - 1
        if row[i + 1] != partner:
            row[position[partner]], row[i + 1] = row[i + 1], row[position[partner]]
            position[row[i + 1]], position[partner] = position[partner], position[row[i + 1]]
            swaps += 1
    return swaps
```
The algorithm works by iterating through the array `row` in increments of 2, representing the couple's seats side by side. During the iteration, it checks if the couple's partner is sitting next to the current person, based on the fact that the partner would have an ID that is either one more or one less than the current person's ID.

If the partner is not sitting in the expected position, it then swaps the person sitting next to the current person with the partner. The positions of the people in the array are stored in a separate `position` array. The swap is done both in the `row` and `position` arrays, and the swap count is incremented.

After the entire iteration, the swap count represents the minimum number of swaps needed to arrange the couples side by side.

## A solution in Javascript

```javascript
function minSwapsCouples(row) {
    const n = row.length;
    const position = new Array(n);
    for (let i = 0; i < n; ++i)
        position[row[i]] = i;

    let swaps = 0;
    for (let i = 0; i < n; i += 2) {
        const partner = row[i] % 2 === 0 ? row[i] + 1 : row[i] - 1;
        if (row[i + 1] !== partner) {
            [row[position[partner]], row[i + 1]] = [row[i + 1], row[position[partner]]];
            [position[row[i + 1]], position[partner]] = [position[partner], position[row[i + 1]]];
            swaps++;
        }
    }
    return swaps;
}
```
The algorithm works by iterating through the array `row` in increments of 2, representing the couple's seats side by side. During the iteration, it checks if the couple's partner is sitting next to the current person, based on the fact that the partner would have an ID that is either one more or one less than the current person's ID.

If the partner is not sitting in the expected position, it then swaps the person sitting next to the current person with the partner. The positions of the people in the array are stored in a separate `position` array. The swap is done both in the `row` and `position` arrays, and the swap count is incremented.

After the entire iteration, the swap count represents the minimum number of swaps needed to arrange the couples side by side.


# Toeplitz Matrix

- slug: toeplitz-matrix
- difficulty: Easy

Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._

A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements.

**Example 1:**

**Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\]
**Output:** true
**Explanation:**
In the above grid, the diagonals are:
 "\[9\] ",  "\[5, 5\] ",  "\[1, 1, 1\] ",  "\[2, 2, 2\] ",  "\[3, 3\] ",  "\[4\] ".
In each diagonal all elements are the same, so the answer is True.

**Example 2:**

**Input:** matrix = \[\[1,2\],\[2,2\]\]
**Output:** false
**Explanation:**
The diagonal  "\[1, 2\] " has different elements.

**Constraints:**

*   `m == matrix.length`
*   `n == matrix[i].length`
*   `1 <= m, n <= 20`
*   `0 <= matrix[i][j] <= 99`

**Follow up:**

*   What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
*   What if the `matrix` is so large that you can only load up a partial row into the memory at once?

## A solution in Java

```java
public class Node {
    public int val;
    public Node prev;
    public Node next;
    public Node child;
}

public Node flatten(Node head) {
    if(head == null) return null;

    Node curr = head;
    while(curr != null) {
        if(curr.child != null) {
            Node insert = curr.child;
            Node next = curr.next;

            insert.prev = curr;
            curr.next = insert;
            curr.child = null;

            while(insert.next != null) insert = insert.next;

            if(next != null) {
                next.prev = insert;
                insert.next = next;
            }
        }
        curr = curr.next;
    }

    return head;
}
```
The basic idea of the algorithm is to traverse the doubly linked list and if a node has a child, we insert the child list between the current node and its next node. We do this by adjusting the previous and next pointers accordingly. After inserting the child list, we set the child pointer of the current node to null. We keep doing this for each node in the list.

## A solution in C++

```cpp
class Node {
public:
    int val;
    Node* prev;
    Node* next;
    Node* child;
};

Node* flatten(Node* head) {
    if(!head) return nullptr;

    Node* curr = head;
    while(curr) {
        if(curr->child) {
            Node* insert = curr->child;
            Node* next = curr->next;

            insert->prev = curr;
            curr->next = insert;
            curr->child = nullptr;

            while(insert->next) insert = insert->next;

            if(next) {
                next->prev = insert;
                insert->next = next;
            }
        }
        curr = curr->next;
    }

    return head;
}
```
The basic idea of the algorithm is to traverse the doubly linked list and if a node has a child, we insert the child list between the current node and its next node. We do this by adjusting the previous and next pointers accordingly. After inserting the child list, we set the child pointer of the current node to null. We keep doing this for each node in the list.

## A solution in Python

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

def flatten(head: Node) -> Node:
    if not head:
        return None

    curr = head
    while curr:
        if curr.child:
            insert = curr.child
            next_node = curr.next

            insert.prev = curr
            curr.next = insert
            curr.child = None

            while insert.next:
                insert = insert.next

            if next_node:
                next_node.prev = insert
                insert.next = next_node

        curr = curr.next

    return head
```
The basic idea of the algorithm is to traverse the doubly linked list and if a node has a child, we insert the child list between the current node and its next node. We do this by adjusting the previous and next pointers accordingly. After inserting the child list, we set the child pointer of the current node to null. We keep doing this for each node in the list.

## A solution in Javascript

```javascript
class Node {
    constructor(val, prev, next, child) {
        this.val = val;
        this.prev = prev || null;
        this.next = next || null;
        this.child = child || null;
    }
}

function flatten(head) {
    if (!head) return null;

    let curr = head;
    while (curr) {
        if (curr.child) {
            let insert = curr.child;
            let next = curr.next;

            insert.prev = curr;
            curr.next = insert;
            curr.child = null;

            while (insert.next) insert = insert.next;

            if (next) {
                next.prev = insert;
                insert.next = next;
            }
        }
        curr = curr.next;
    }

    return head;
}
```
The basic idea of the algorithm is to traverse the doubly linked list and if a node has a child, we insert the child list between the current node and its next node. We do this by adjusting the previous and next pointers accordingly. After inserting the child list, we set the child pointer of the current node to null. We keep doing this for each node in the list.


# Reorganize String

- slug: reorganize-string
- difficulty: Medium

Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same.

Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_.

**Example 1:**

**Input:** s = "aab"
**Output:** "aba"

**Example 2:**

**Input:** s = "aaab"
**Output:** ""

**Constraints:**

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

## A solution in Java

```java
public boolean isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

public int countPrimeSetBits(int left, int right) {
    int count = 0;
    for (int i = left; i <= right; i++) {
        int bits = Integer.bitCount(i);
        if (isPrime(bits)) count++;
    }
    return count;
}
```
The algorithm consists of two functions: `is_prime` which checks if a given number is prime, and `count_prime_set_bits` which iterates through the range [left, right] and counts the numbers with a prime number of set bits in their binary representation.

The `is_prime` function checks if a number is prime by iterating through the range [2, sqrt(n)] and checking if n is divisible by any of these numbers. If it's divisible by any of these numbers, then it's not prime (returns false) otherwise, it's prime (returns true).

In the `count_prime_set_bits` function, we iterate through the range [left, right]. For each number, we count the number of set bits (1's) in its binary representation using an appropriate bit counting function/method for each language. We then check if the resulting count is prime using the `is_prime` function. If it is, we increment the counter.

Finally, we return the counter after iterating through the range.

## A solution in C++

```cpp
#include <bitset>
#include <vector>

bool is_prime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

int count_prime_set_bits(int left, int right) {
    int count = 0;
    for (int i = left; i <= right; i++) {
        if (is_prime(std::bitset<32>(i).count())) count++;
    }
    return count;
}
```
The algorithm consists of two functions: `is_prime` which checks if a given number is prime, and `count_prime_set_bits` which iterates through the range [left, right] and counts the numbers with a prime number of set bits in their binary representation.

The `is_prime` function checks if a number is prime by iterating through the range [2, sqrt(n)] and checking if n is divisible by any of these numbers. If it's divisible by any of these numbers, then it's not prime (returns false) otherwise, it's prime (returns true).

In the `count_prime_set_bits` function, we iterate through the range [left, right]. For each number, we count the number of set bits (1's) in its binary representation using an appropriate bit counting function/method for each language. We then check if the resulting count is prime using the `is_prime` function. If it is, we increment the counter.

Finally, we return the counter after iterating through the range.

## A solution in Python

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

def count_prime_set_bits(left: int, right: int) -> int:
    count = 0
    for i in range(left, right + 1):
        bits = bin(i).count('1')
        if is_prime(bits):
            count += 1
    return count
```
The algorithm consists of two functions: `is_prime` which checks if a given number is prime, and `count_prime_set_bits` which iterates through the range [left, right] and counts the numbers with a prime number of set bits in their binary representation.

The `is_prime` function checks if a number is prime by iterating through the range [2, sqrt(n)] and checking if n is divisible by any of these numbers. If it's divisible by any of these numbers, then it's not prime (returns false) otherwise, it's prime (returns true).

In the `count_prime_set_bits` function, we iterate through the range [left, right]. For each number, we count the number of set bits (1's) in its binary representation using an appropriate bit counting function/method for each language. We then check if the resulting count is prime using the `is_prime` function. If it is, we increment the counter.

Finally, we return the counter after iterating through the range.

## A solution in Javascript

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

function countPrimeSetBits(left, right) {
    let count = 0;
    for (let i = left; i <= right; i++) {
        let bits = i.toString(2).split('1').length - 1;
        if (isPrime(bits)) count++;
    }
    return count;
}
```
The algorithm consists of two functions: `is_prime` which checks if a given number is prime, and `count_prime_set_bits` which iterates through the range [left, right] and counts the numbers with a prime number of set bits in their binary representation.

The `is_prime` function checks if a number is prime by iterating through the range [2, sqrt(n)] and checking if n is divisible by any of these numbers. If it's divisible by any of these numbers, then it's not prime (returns false) otherwise, it's prime (returns true).

In the `count_prime_set_bits` function, we iterate through the range [left, right]. For each number, we count the number of set bits (1's) in its binary representation using an appropriate bit counting function/method for each language. We then check if the resulting count is prime using the `is_prime` function. If it is, we increment the counter.

Finally, we return the counter after iterating through the range.


# Max Chunks To Make Sorted II

- slug: max-chunks-to-make-sorted-ii
- difficulty: Hard

You are given an integer array `arr`.

We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.

Return _the largest number of chunks we can make to sort the array_.

**Example 1:**

**Input:** arr = \[5,4,3,2,1\]
**Output:** 1
**Explanation:**
Splitting into two or more chunks will not return the required result.
For example, splitting into \[5, 4\], \[3, 2, 1\] will result in \[4, 5, 1, 2, 3\], which isn't sorted.

**Example 2:**

**Input:** arr = \[2,1,3,4,4\]
**Output:** 4
**Explanation:**
We can split into two chunks, such as \[2, 1\], \[3, 4, 4\].
However, splitting into \[2, 1\], \[3\], \[4\], \[4\] is the highest number of chunks possible.

**Constraints:**

*   `1 <= arr.length <= 2000`
*   `0 <= arr[i] <= 108`

## A solution in Java

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

public List<Integer> partitionLabels(String s) {
    HashMap<Character, Integer> lastPos = new HashMap<>();
    for (int i = 0; i < s.length(); i++) {
        lastPos.put(s.charAt(i), i);
    }

    List<Integer> partitions = new ArrayList<>();
    int start = 0, end = 0;
    for (int i = 0; i < s.length(); i++) {
        end = Math.max(end, lastPos.get(s.charAt(i)));
        if (i == end) {
            partitions.add(end - start + 1);
            start = i + 1;
        }
    }
    return partitions;
}
```
1. Create a dictionary `lastPos` to store the last position for each character in the string.
2. Iterate over the string, and for each character, store its last position in the `lastPos` dictionary.
3. Create a list `partitions` to store the partition sizes.
4. Initialize two variables `start` and `end` with value 0.
5. Iterate over the string again:
   a. For each character, update `end` with the maximum value between `end` and its last position from the `lastPos` dictionary.
   b. If the current index is equal to `end`, calculate the length of the current partition, append it to `partitions`, and update `start` to the next index.
6. Return the `partitions` list.

## A solution in C++

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

std::vector<int> partitionLabels(const std::string& s) {
    std::unordered_map<char, int> lastPos;
    for (int i = 0; i < s.size(); i++) {
        lastPos[s[i]] = i;
    }

    std::vector<int> partitions;
    int start = 0, end = 0;
    for (int i = 0; i < s.size(); i++) {
        end = std::max(end, lastPos[s[i]]);
        if (i == end) {
            partitions.push_back(end - start + 1);
            start = i + 1;
        }
    }
    return partitions;
}
```
1. Create a dictionary `lastPos` to store the last position for each character in the string.
2. Iterate over the string, and for each character, store its last position in the `lastPos` dictionary.
3. Create a list `partitions` to store the partition sizes.
4. Initialize two variables `start` and `end` with value 0.
5. Iterate over the string again:
   a. For each character, update `end` with the maximum value between `end` and its last position from the `lastPos` dictionary.
   b. If the current index is equal to `end`, calculate the length of the current partition, append it to `partitions`, and update `start` to the next index.
6. Return the `partitions` list.

## A solution in Python

```python
def partition_labels(s: str) -> list[int]:
    last_pos = {}
    for i, c in enumerate(s):
        last_pos[c] = i

    partitions = []
    start, end = 0, 0
    for i, c in enumerate(s):
        end = max(end, last_pos[c])
        if i == end:
            partitions.append(end - start + 1)
            start = i + 1
    return partitions
```
1. Create a dictionary `lastPos` to store the last position for each character in the string.
2. Iterate over the string, and for each character, store its last position in the `lastPos` dictionary.
3. Create a list `partitions` to store the partition sizes.
4. Initialize two variables `start` and `end` with value 0.
5. Iterate over the string again:
   a. For each character, update `end` with the maximum value between `end` and its last position from the `lastPos` dictionary.
   b. If the current index is equal to `end`, calculate the length of the current partition, append it to `partitions`, and update `start` to the next index.
6. Return the `partitions` list.

## A solution in Javascript

```javascript
function partitionLabels(s) {
    const lastPos = {};
    for (let i = 0; i < s.length; i++) {
        lastPos[s[i]] = i;
    }

    const partitions = [];
    let start = 0, end = 0;
    for (let i = 0; i < s.length; i++) {
        end = Math.max(end, lastPos[s[i]]);
        if (i === end) {
            partitions.push(end - start + 1);
            start = i + 1;
        }
    }
    return partitions;
}
```
1. Create a dictionary `lastPos` to store the last position for each character in the string.
2. Iterate over the string, and for each character, store its last position in the `lastPos` dictionary.
3. Create a list `partitions` to store the partition sizes.
4. Initialize two variables `start` and `end` with value 0.
5. Iterate over the string again:
   a. For each character, update `end` with the maximum value between `end` and its last position from the `lastPos` dictionary.
   b. If the current index is equal to `end`, calculate the length of the current partition, append it to `partitions`, and update `start` to the next index.
6. Return the `partitions` list.


# Max Chunks To Make Sorted

- slug: max-chunks-to-make-sorted
- difficulty: Medium

You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`.

We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.

Return _the largest number of chunks we can make to sort the array_.

**Example 1:**

**Input:** arr = \[4,3,2,1,0\]
**Output:** 1
**Explanation:**
Splitting into two or more chunks will not return the required result.
For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted.

**Example 2:**

**Input:** arr = \[1,0,2,3,4\]
**Output:** 4
**Explanation:**
We can split into two chunks, such as \[1, 0\], \[2, 3, 4\].
However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible.

**Constraints:**

*   `n == arr.length`
*   `1 <= n <= 10`
*   `0 <= arr[i] < n`
*   All the elements of `arr` are **unique**.

## A solution in Java

```java
public int orderOfLargestPlusSign(int n, int[][] mines) {
    int[][] grid = new int[n][n];
    for (int[] row : grid) Arrays.fill(row, 1);
    for (int[] mine : mines) grid[mine[0]][mine[1]] = 0;

    int[][][] dp = new int[n][n][4];
    for (int i=0; i<n; ++i)
        for (int j=0; j<n; ++j)
            if (grid[i][j] > 0) {
                dp[i][j][0] = i > 0 ? dp[i - 1][j][0] + 1 : 1;
                dp[i][j][1] = j > 0 ? dp[i][j - 1][1] + 1 : 1;
            }

    int ans = 0;
    for (int i=n-1; i>=0; --i)
        for (int j=n-1; j>=0; --j)
            if (grid[i][j] > 0) {
                dp[i][j][2] = i < n - 1 ? dp[i + 1][j][2] + 1 : 1;
                dp[i][j][3] = j < n - 1 ? dp[i][j + 1][3] + 1 : 1;
                int cur = Collections.min(Arrays.asList(dp[i][j]));
                ans = Math.max(ans, cur);
            }

    return ans;
}
```
1. Initialize a grid of n x n with all 1's and set the elements at the indices given in mines as 0.
2. Create four matrices called left, right, up, and down which are copies of the grid.
3. Iterate through the grid left to right, top to bottom and update the left and up matrices based on the grid values.
4. Iterate through the grid right to left, bottom to top and update the right and down matrices based on the grid values.
5. Iterate through the grid again and calculate the minimum value at each position between the left, right, up, and down matrices.
6. Return the maximum value seen during step 5 which is the largest axis-aligned plus sign order.

## A solution in C++

```cpp
int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {
    vector<vector<int>> grid(n, vector<int>(n, 1));
    for (const auto& mine : mines)
        grid[mine[0]][mine[1]] = 0;

    vector<vector<int>> left(grid), right(grid), up(grid), down(grid);
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (grid[i][j]) {
                left[i][j] = j > 0 ? left[i][j - 1] + 1 : 1;
                up[i][j] = i > 0 ? up[i - 1][j] + 1 : 1;
            }
            if (grid[n - i - 1][n - j - 1]) {
                right[n - i - 1][n - j - 1] = j > 0 ? right[n - i - 1][n - j] + 1 : 1;
                down[n - i - 1][n - j - 1] = i > 0 ? down[n - i][n - j - 1] + 1 : 1;
            }
        }
    }

    int ans = 0;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            ans = max(ans, min({left[i][j], right[i][j], up[i][j], down[i][j]}));
    return ans;
}
```
1. Initialize a grid of n x n with all 1's and set the elements at the indices given in mines as 0.
2. Create four matrices called left, right, up, and down which are copies of the grid.
3. Iterate through the grid left to right, top to bottom and update the left and up matrices based on the grid values.
4. Iterate through the grid right to left, bottom to top and update the right and down matrices based on the grid values.
5. Iterate through the grid again and calculate the minimum value at each position between the left, right, up, and down matrices.
6. Return the maximum value seen during step 5 which is the largest axis-aligned plus sign order.

## A solution in Python

```python
def orderOfLargestPlusSign(n, mines):
    grid = [[1] * n for _ in range(n)]
    for mine in mines:
        grid[mine[0]][mine[1]] = 0

    left, right, up, down = [list(grid) for _ in range(4)]

    for i in range(n):
        for j in range(n):
            if grid[i][j]:
                left[i][j] = 1 + (left[i][j - 1] if j > 0 else 0)
                up[i][j] = 1 + (up[i - 1][j] if i > 0 else 0)

    ans = 0
    for i in range(n - 1, -1, -1):
        for j in range(n - 1, -1, -1):
            if grid[i][j]:
                right[i][j] = 1 + (right[i][j + 1] if j < n - 1 else 0)
                down[i][j] = 1 + (down[i + 1][j] if i < n - 1 else 0)
                ans = max(ans, min([left[i][j], right[i][j], up[i][j], down[i][j]]))

    return ans
```
1. Initialize a grid of n x n with all 1's and set the elements at the indices given in mines as 0.
2. Create four matrices called left, right, up, and down which are copies of the grid.
3. Iterate through the grid left to right, top to bottom and update the left and up matrices based on the grid values.
4. Iterate through the grid right to left, bottom to top and update the right and down matrices based on the grid values.
5. Iterate through the grid again and calculate the minimum value at each position between the left, right, up, and down matrices.
6. Return the maximum value seen during step 5 which is the largest axis-aligned plus sign order.

## A solution in Javascript

```javascript
function orderOfLargestPlusSign(n, mines) {
    const grid = Array.from({ length: n }, () => Array(n).fill(1));
    for (const mine of mines)
        grid[mine[0]][mine[1]] = 0;

    const left = grid.map(row => [...row]);
    const right = grid.map(row => [...row]);
    const up = grid.map(row => [...row]);
    const down = grid.map(row => [...row]);

    for (let i = 0; i < n; ++i) {
        for (let j = 0; j < n; ++j) {
            if (grid[i][j]) {
                left[i][j] = j > 0 ? left[i][j - 1] + 1 : 1;
                up[i][j] = i > 0 ? up[i - 1][j] + 1 : 1;
            }
            if (grid[n - i - 1][n - j - 1]) {
                right[n - i - 1][n - j - 1] = j > 0 ? right[n - i - 1][n - j] + 1 : 1;
                down[n - i - 1][n - j - 1] = i > 0 ? down[n - i][n - j - 1] + 1 : 1;
            }
        }
    }

    let ans = 0;
    for (let i = 0; i < n; ++i)
        for (let j = 0; j < n; ++j)
            ans = Math.max(ans, Math.min(left[i][j], right[i][j], up[i][j], down[i][j]));

    return ans;
}
```
1. Initialize a grid of n x n with all 1's and set the elements at the indices given in mines as 0.
2. Create four matrices called left, right, up, and down which are copies of the grid.
3. Iterate through the grid left to right, top to bottom and update the left and up matrices based on the grid values.
4. Iterate through the grid right to left, bottom to top and update the right and down matrices based on the grid values.
5. Iterate through the grid again and calculate the minimum value at each position between the left, right, up, and down matrices.
6. Return the maximum value seen during step 5 which is the largest axis-aligned plus sign order.


# Basic Calculator IV

- slug: basic-calculator-iv
- difficulty: Hard

Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]`

*   An expression alternates chunks and symbols, with a space separating each chunk and symbol.
*   A chunk is either an expression in parentheses, a variable, or a non-negative integer.
*   A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `"2x "` or `"-x "`.

Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.

*   For example, `expression = "1 + 2 * 3 "` has an answer of `[ "7 "]`.

The format of the output is as follows:

*   For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
    *   For example, we would never write a term like `"b*a*c "`, only `"a*b*c "`.
*   Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
    *   For example, `"a*a*b*c "` has degree `4`.
*   The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.
*   An example of a well-formatted answer is `[ "-2*a*a*a ", "3*a*a*b ", "3*b*b ", "4*a ", "5*c ", "-6 "]`.
*   Terms (including constant terms) with coefficient `0` are not included.
    *   For example, an expression of `"0 "` has an output of `[]`.

**Note:** You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`.

**Example 1:**

**Input:** expression =  "e + 8 - a + 5 ", evalvars = \[ "e "\], evalints = \[1\]
**Output:** \[ "-1\*a ", "14 "\]

**Example 2:**

**Input:** expression =  "e - 8 + temperature - pressure ", evalvars = \[ "e ",  "temperature "\], evalints = \[1, 12\]
**Output:** \[ "-1\*pressure ", "5 "\]

**Example 3:**

**Input:** expression =  "(e + 8) \* (e - 8) ", evalvars = \[\], evalints = \[\]
**Output:** \[ "1\*e\*e ", "-64 "\]

**Constraints:**

*   `1 <= expression.length <= 250`
*   `expression` consists of lowercase English letters, digits, `'+'`, `'-'`, `'*'`, `'('`, `')'`, `' '`.
*   `expression` does not contain any leading or trailing spaces.
*   All the tokens in `expression` are separated by a single space.
*   `0 <= evalvars.length <= 100`
*   `1 <= evalvars[i].length <= 20`
*   `evalvars[i]` consists of lowercase English letters.
*   `evalints.length == evalvars.length`
*   `-100 <= evalints[i] <= 100`

## A solution in Java

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

public int minSwapsCouples(int[] row) {
    int n = row.length / 2;
    int swaps = 0;
    Map<Integer, Integer> position = new HashMap<>();

    for (int i = 0; i < row.length; i++) {
        position.put(row[i], i);
    }

    for (int i = 0; i < row.length; i += 2) {
        int couple = (row[i] % 2 == 0) ? row[i] + 1 : row[i] - 1;
        if (row[i + 1] != couple) {
            int temp = row[i + 1];
            row[i + 1] = row[position.get(couple)];
            row[position.get(couple)] = temp;
            position.put(temp, position.get(couple));
            position.put(couple, i + 1);
            swaps++;
        }
    }
    return swaps;
}
```
1. Initialize variables: n (the number of couples), swaps (the number of swaps), and a dictionary 'position' where the keys are the person IDs and the values are their positions in the row.
2. For each even-indexed element (i) in 'row', check if the current couple is sitting side by side.
3. If not, find the position of the couple of the person sitting at index i, and swap the positions of the person sitting at i+1 and the couple. Update the position of them in the 'position' dictionary accordingly.
4. Increment the swap counter.
5. Repeat for all even-indexed elements in 'row', then return the total number of swaps.

This algorithm runs in O(n) time complexity due to iterating through the row once and performing swaps accordingly.

## A solution in C++

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

int minSwapsCouples(vector<int>& row) {
    int n = row.size() / 2;
    int swaps = 0;
    unordered_map<int, int> position;

    for (int i = 0; i < row.size(); i++) {
        position[row[i]] = i;
    }

    for (int i = 0; i < row.size(); i += 2) {
        int couple = (row[i] % 2 == 0) ? row[i] + 1 : row[i] - 1;
        if (row[i + 1] != couple) {
            swap(row[i + 1], row[position[couple]]);
            swap(position[row[i + 1]], position[couple]);
            swaps++;
        }
    }
    return swaps;
}
```
1. Initialize variables: n (the number of couples), swaps (the number of swaps), and a dictionary 'position' where the keys are the person IDs and the values are their positions in the row.
2. For each even-indexed element (i) in 'row', check if the current couple is sitting side by side.
3. If not, find the position of the couple of the person sitting at index i, and swap the positions of the person sitting at i+1 and the couple. Update the position of them in the 'position' dictionary accordingly.
4. Increment the swap counter.
5. Repeat for all even-indexed elements in 'row', then return the total number of swaps.

This algorithm runs in O(n) time complexity due to iterating through the row once and performing swaps accordingly.

## A solution in Python

```python
def minSwapsCouples(row):
    n = len(row) // 2
    swaps = 0
    position = {num: i for i, num in enumerate(row)}

    for i in range(0, len(row), 2):
        couple = row[i] - 1 if row[i] % 2 else row[i] + 1
        if row[i + 1] != couple:
            row[i + 1], row[position[couple]] = row[position[couple]], row[i + 1]
            position[row[i + 1]], position[couple] = position[couple], i + 1
            swaps += 1

    return swaps
```
1. Initialize variables: n (the number of couples), swaps (the number of swaps), and a dictionary 'position' where the keys are the person IDs and the values are their positions in the row.
2. For each even-indexed element (i) in 'row', check if the current couple is sitting side by side.
3. If not, find the position of the couple of the person sitting at index i, and swap the positions of the person sitting at i+1 and the couple. Update the position of them in the 'position' dictionary accordingly.
4. Increment the swap counter.
5. Repeat for all even-indexed elements in 'row', then return the total number of swaps.

This algorithm runs in O(n) time complexity due to iterating through the row once and performing swaps accordingly.

## A solution in Javascript

```javascript
function minSwapsCouples(row) {
    const n = row.length / 2;
    let swaps = 0;
    const position = {};

    for (let i = 0; i < row.length; i++) {
        position[row[i]] = i;
    }

    for (let i = 0; i < row.length; i += 2) {
        const couple = (row[i] % 2 === 0) ? row[i] + 1 : row[i] - 1;
        if (row[i + 1] !== couple) {
            [row[i + 1], row[position[couple]]] = [row[position[couple]], row[i + 1]];
            [position[row[i + 1]], position[couple]] = [position[couple], i + 1];
            swaps++;
        }
    }

    return swaps;
}
```
1. Initialize variables: n (the number of couples), swaps (the number of swaps), and a dictionary 'position' where the keys are the person IDs and the values are their positions in the row.
2. For each even-indexed element (i) in 'row', check if the current couple is sitting side by side.
3. If not, find the position of the couple of the person sitting at index i, and swap the positions of the person sitting at i+1 and the couple. Update the position of them in the 'position' dictionary accordingly.
4. Increment the swap counter.
5. Repeat for all even-indexed elements in 'row', then return the total number of swaps.

This algorithm runs in O(n) time complexity due to iterating through the row once and performing swaps accordingly.


# Jewels and Stones

- slug: jewels-and-stones
- difficulty: Easy

You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`.

**Example 1:**

**Input:** jewels = "aA", stones = "aAAbbbb"
**Output:** 3

**Example 2:**

**Input:** jewels = "z", stones = "ZZ"
**Output:** 0

**Constraints:**

*   `1 <= jewels.length, stones.length <= 50`
*   `jewels` and `stones` consist of only English letters.
*   All the characters of `jewels` are **unique**.

## A solution in Java

```java
public int numJewelsInStones(String jewels, String stones) {
    int count = 0;
    for (char stone : stones.toCharArray()) {
        if (jewels.indexOf(stone) != -1) {
            count++;
        }
    }
    return count;
}
```
The algorithm is pretty simple, as it iterates through each character (stone) in the `stones` string, and checks if that character is present in the `jewels` string. If it is, increment the counter. Finally, return the counter as the result.

This method does not require any additional space, except for the counter variable, and its time complexity is O(n*m) where n is the length of `stones` and m is the length of `jewels`.

## A solution in C++

```cpp
int numJewelsInStones(string jewels, string stones) {
    int count = 0;
    for (char stone : stones) {
        if (jewels.find(stone) != std::string::npos) {
            count++;
        }
    }
    return count;
}
```
The algorithm is pretty simple, as it iterates through each character (stone) in the `stones` string, and checks if that character is present in the `jewels` string. If it is, increment the counter. Finally, return the counter as the result.

This method does not require any additional space, except for the counter variable, and its time complexity is O(n*m) where n is the length of `stones` and m is the length of `jewels`.

## A solution in Python

```python
def num_jewels_in_stones(jewels: str, stones: str) -> int:
    count = 0
    for stone in stones:
        if stone in jewels:
            count += 1
    return count
```
The algorithm is pretty simple, as it iterates through each character (stone) in the `stones` string, and checks if that character is present in the `jewels` string. If it is, increment the counter. Finally, return the counter as the result.

This method does not require any additional space, except for the counter variable, and its time complexity is O(n*m) where n is the length of `stones` and m is the length of `jewels`.

## A solution in Javascript

```javascript
function numJewelsInStones(jewels, stones) {
    let count = 0;
    for (let stone of stones) {
        if (jewels.indexOf(stone) !== -1) {
            count++;
        }
    }
    return count;
}
```
The algorithm is pretty simple, as it iterates through each character (stone) in the `stones` string, and checks if that character is present in the `jewels` string. If it is, increment the counter. Finally, return the counter as the result.

This method does not require any additional space, except for the counter variable, and its time complexity is O(n*m) where n is the length of `stones` and m is the length of `jewels`.


# Basic Calculator III

- slug: basic-calculator-iii
- difficulty: Hard

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, `'+'`, `'-'`, `'*'`, `'/'` operators, and open `'('` and closing parentheses `')'`. The integer division should **truncate toward zero**.

You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`.

**Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.

**Example 1:**

**Input:** s =  "1+1 "
**Output:** 2

**Example 2:**

**Input:** s =  "6-4/2 "
**Output:** 4

**Example 3:**

**Input:** s =  "2\*(5+5\*2)/3+(6/2+8) "
**Output:** 21

**Constraints:**

*   `1 <= s <= 104`
*   `s` consists of digits, `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`.
*   `s` is a **valid** expression.

## A solution in Java

```java
class Node {
    boolean val;
    boolean isLeaf;
    Node topLeft;
    Node topRight;
    Node bottomLeft;
    Node bottomRight;

    public Node() {
        this(false, false, null, null, null, null);
    }

    public Node(boolean val, boolean isLeaf) {
        this(val, isLeaf, null, null, null, null);
    }

    public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {
        this.val = val;
        this.isLeaf = isLeaf;
        this.topLeft = topLeft;
        this.topRight = topRight;
        this.bottomLeft = bottomLeft;
        this.bottomRight = bottomRight;
    }
}

public Node construct(int[][] grid) {
    return helper(grid, 0, 0, grid.length);
}

private Node helper(int[][] grid, int x, int y, int length) {
    if (length == 1) {
        return new Node(grid[x][y] == 1, true);
    }

    Node tl = helper(grid, x, y, length / 2);
    Node tr = helper(grid, x, y + length / 2, length / 2);
    Node bl = helper(grid, x + length / 2, y, length / 2);
    Node br = helper(grid, x + length / 2, y + length / 2, length / 2);

    if (tl.isLeaf && tr.isLeaf && bl.isLeaf && br.isLeaf &&
        tl.val == tr.val && tr.val == bl.val && bl.val == br.val) {
        return new Node(tl.val, true);
    } else {
        return new Node(false, false, tl, tr, bl, br);
    }
}
```
We start by defining a Node class for each language implementation, which represents a node in the Quad-Tree. The construct function initiates the construction of the Quad-Tree by calling the helper function with the initial indices (0, 0) and the length of the input grid.

The helper function works recursively to build the Quad-Tree. The base case for the recursion is when the length is 1, and we create a leaf node with the value of the cell in the grid.

In order to create the internal nodes, the helper function checks the topLeft, topRight, bottomLeft, and bottomRight subgrids by recursively calling itself with the updated indices and a halved length. If all the children nodes are leaf nodes and they have the same value, we return a new leaf node with the same value, discarding the created children nodes. If this condition doesn't hold, an internal node with the current children nodes is created.

Once the recursion successfully checks and constructs the entire grid, the root node of the Quad-Tree is returned, representing the constructed tree for the input grid.

## A solution in C++

```cpp
struct Node {
    bool val;
    bool isLeaf;
    Node* topLeft;
    Node* topRight;
    Node* bottomLeft;
    Node* bottomRight;
};

Node* construct(vector<vector<int>>& grid) {
    return helper(grid, 0, 0, grid.size());
}

Node* helper(vector<vector<int>>& grid, int x, int y, int length) {
    if (length == 1) {
        return new Node{grid[x][y] == 1, true, nullptr, nullptr, nullptr, nullptr};
    }

    Node* tl = helper(grid, x, y, length / 2);
    Node* tr = helper(grid, x, y + length / 2, length / 2);
    Node* bl = helper(grid, x + length / 2, y, length / 2);
    Node* br = helper(grid, x + length / 2, y + length / 2, length / 2);

    if (tl->isLeaf && tr->isLeaf && bl->isLeaf && br->isLeaf &&
        tl->val == tr->val && tr->val == bl->val && bl->val == br->val) {
        bool value = tl->val;
        delete tl;
        delete tr;
        delete bl;
        delete br;
        return new Node{value, true, nullptr, nullptr, nullptr, nullptr};
    } else {
        return new Node{false, false, tl, tr, bl, br};
    }
}
```
We start by defining a Node class for each language implementation, which represents a node in the Quad-Tree. The construct function initiates the construction of the Quad-Tree by calling the helper function with the initial indices (0, 0) and the length of the input grid.

The helper function works recursively to build the Quad-Tree. The base case for the recursion is when the length is 1, and we create a leaf node with the value of the cell in the grid.

In order to create the internal nodes, the helper function checks the topLeft, topRight, bottomLeft, and bottomRight subgrids by recursively calling itself with the updated indices and a halved length. If all the children nodes are leaf nodes and they have the same value, we return a new leaf node with the same value, discarding the created children nodes. If this condition doesn't hold, an internal node with the current children nodes is created.

Once the recursion successfully checks and constructs the entire grid, the root node of the Quad-Tree is returned, representing the constructed tree for the input grid.

## A solution in Python

```python
class Node:
    def __init__(self, val: bool, isLeaf: bool, topLeft: 'Node', topRight: 'Node', bottomLeft: 'Node', bottomRight: 'Node'):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight

def construct(grid):
    def helper(x, y, length):
        if length == 1:
            return Node(grid[x][y] == 1, True, None, None, None, None)

        tl = helper(x, y, length // 2)
        tr = helper(x, y + length // 2, length // 2)
        bl = helper(x + length // 2, y, length // 2)
        br = helper(x + length // 2, y + length // 2, length // 2)

        if tl.isLeaf and tr.isLeaf and bl.isLeaf and br.isLeaf and tl.val == tr.val and tr.val == bl.val and bl.val == br.val:
            return Node(tl.val, True, None, None, None, None)
        else:
            return Node(False, False, tl, tr, bl, br)

    return helper(0, 0, len(grid))
```
We start by defining a Node class for each language implementation, which represents a node in the Quad-Tree. The construct function initiates the construction of the Quad-Tree by calling the helper function with the initial indices (0, 0) and the length of the input grid.

The helper function works recursively to build the Quad-Tree. The base case for the recursion is when the length is 1, and we create a leaf node with the value of the cell in the grid.

In order to create the internal nodes, the helper function checks the topLeft, topRight, bottomLeft, and bottomRight subgrids by recursively calling itself with the updated indices and a halved length. If all the children nodes are leaf nodes and they have the same value, we return a new leaf node with the same value, discarding the created children nodes. If this condition doesn't hold, an internal node with the current children nodes is created.

Once the recursion successfully checks and constructs the entire grid, the root node of the Quad-Tree is returned, representing the constructed tree for the input grid.

## A solution in Javascript

```javascript
class Node {
    constructor(val, isLeaf, topLeft, topRight, bottomLeft, bottomRight) {
        this.val = val;
        this.isLeaf = isLeaf;
        this.topLeft = topLeft;
        this.topRight = topRight;
        this.bottomLeft = bottomLeft;
        this.bottomRight = bottomRight;
    }
}

function construct(grid) {
    function helper(x, y, length) {
        if (length === 1) {
            return new Node(grid[x][y] === 1, true, null, null, null, null);
        }

        const tl = helper(x, y, length >> 1);
        const tr = helper(x, y + (length >> 1), length >> 1);
        const bl = helper(x + (length >> 1), y, length >> 1);
        const br = helper(x + (length >> 1), y + (length >> 1), length >> 1);

        if (tl.isLeaf && tr.isLeaf && bl.isLeaf && br.isLeaf && tl.val === tr.val && tr.val === bl.val && bl.val === br.val) {
            return new Node(tl.val, true, null, null, null, null);
        } else {
            return new Node(false, false, tl, tr, bl, br);
        }
    }

    return helper(0, 0, grid.length);
}
```
We start by defining a Node class for each language implementation, which represents a node in the Quad-Tree. The construct function initiates the construction of the Quad-Tree by calling the helper function with the initial indices (0, 0) and the length of the input grid.

The helper function works recursively to build the Quad-Tree. The base case for the recursion is when the length is 1, and we create a leaf node with the value of the cell in the grid.

In order to create the internal nodes, the helper function checks the topLeft, topRight, bottomLeft, and bottomRight subgrids by recursively calling itself with the updated indices and a halved length. If all the children nodes are leaf nodes and they have the same value, we return a new leaf node with the same value, discarding the created children nodes. If this condition doesn't hold, an internal node with the current children nodes is created.

Once the recursion successfully checks and constructs the entire grid, the root node of the Quad-Tree is returned, representing the constructed tree for the input grid.


# Sliding Puzzle

- slug: sliding-puzzle
- difficulty: Hard

On an `2 x 3` board, there are five tiles labeled from `1` to `5`, and an empty square represented by `0`. A **move** consists of choosing `0` and a 4-directionally adjacent number and swapping it.

The state of the board is solved if and only if the board is `[[1,2,3],[4,5,0]]`.

Given the puzzle board `board`, return _the least number of moves required so that the state of the board is solved_. If it is impossible for the state of the board to be solved, return `-1`.

**Example 1:**

**Input:** board = \[\[1,2,3\],\[4,0,5\]\]
**Output:** 1
**Explanation:** Swap the 0 and the 5 in one move.

**Example 2:**

**Input:** board = \[\[1,2,3\],\[5,4,0\]\]
**Output:** -1
**Explanation:** No number of moves will make the board solved.

**Example 3:**

**Input:** board = \[\[4,1,2\],\[5,0,3\]\]
**Output:** 5
**Explanation:** 5 is the smallest number of moves that solves the board.
An example path:
After move 0: \[\[4,1,2\],\[5,0,3\]\]
After move 1: \[\[4,1,2\],\[0,5,3\]\]
After move 2: \[\[0,1,2\],\[4,5,3\]\]
After move 3: \[\[1,0,2\],\[4,5,3\]\]
After move 4: \[\[1,2,0\],\[4,5,3\]\]
After move 5: \[\[1,2,3\],\[4,5,0\]\]

**Constraints:**

*   `board.length == 2`
*   `board[i].length == 3`
*   `0 <= board[i][j] <= 5`
*   Each value `board[i][j]` is **unique**.

## A solution in Java

```java
public class TreeNode {
    boolean isLeaf;
    boolean val;
    TreeNode topLeft;
    TreeNode topRight;
    TreeNode bottomLeft;
    TreeNode bottomRight;
}

public TreeNode intersect(TreeNode quadTree1, TreeNode quadTree2) {
    if (quadTree1.isLeaf) {
        return quadTree1.val ? quadTree1 : quadTree2;
    }
    if (quadTree2.isLeaf) {
        return quadTree2.val ? quadTree2 : quadTree1;
    }

    quadTree1.topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft);
    quadTree1.topRight = intersect(quadTree1.topRight, quadTree2.topRight);
    quadTree1.bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft);
    quadTree1.bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight);

    if (quadTree1.topLeft.isLeaf && quadTree1.topRight.isLeaf && quadTree1.bottomLeft.isLeaf && quadTree1.bottomRight.isLeaf && quadTree1.topLeft.val == quadTree1.topRight.val && quadTree1.topRight.val == quadTree1.bottomLeft.val && quadTree1.bottomLeft.val == quadTree1.bottomRight.val) {
        quadTree1.isLeaf = true;
        quadTree1.val = quadTree1.topLeft.val;
    }

    return quadTree1;
}
```
The algorithm for this problem can be solved using a tree traversal approach. The base cases are when either of the quadTrees (quadTree1 or quadTree2) are leaf nodes. If either one is a leaf and has a value of 1 (true), we return that leaf. Otherwise, we return the other leaf.

Next, we recursively compute the OR operation on the child nodes:
- topLeft: quadTree1.topLeft and quadTree2.topLeft
- topRight: quadTree1.topRight and quadTree2.topRight
- bottomLeft: quadTree1.bottomLeft and quadTree2.bottomLeft
- bottomRight: quadTree1.bottomRight and quadTree2.bottomRight

After the recursion, we check if all the children are leaf nodes and have the same value. If so, we can collapse the tree into a single leaf node with that value, effectively compressing the quadtree.

Finally, we return the resulting quadTree.

## A solution in C++

```cpp
struct TreeNode {
    bool isLeaf;
    bool val;
    TreeNode* topLeft;
    TreeNode* topRight;
    TreeNode* bottomLeft;
    TreeNode* bottomRight;
};

TreeNode* intersect(TreeNode* quadTree1, TreeNode* quadTree2) {
    if (quadTree1->isLeaf) {
        return quadTree1->val ? quadTree1 : quadTree2;
    }
    if (quadTree2->isLeaf) {
        return quadTree2->val ? quadTree2 : quadTree1;
    }

    quadTree1->topLeft = intersect(quadTree1->topLeft, quadTree2->topLeft);
    quadTree1->topRight = intersect(quadTree1->topRight, quadTree2->topRight);
    quadTree1->bottomLeft = intersect(quadTree1->bottomLeft, quadTree2->bottomLeft);
    quadTree1->bottomRight = intersect(quadTree1->bottomRight, quadTree2->bottomRight);

    if (quadTree1->topLeft->isLeaf && quadTree1->topRight->isLeaf && quadTree1->bottomLeft->isLeaf && quadTree1->bottomRight->isLeaf && quadTree1->topLeft->val == quadTree1->topRight->val && quadTree1->topRight->val == quadTree1->bottomLeft->val && quadTree1->bottomLeft->val == quadTree1->bottomRight->val) {
        quadTree1->isLeaf = true;
        quadTree1->val = quadTree1->topLeft->val;
        delete quadTree1->topLeft;
        delete quadTree1->topRight;
        delete quadTree1->bottomLeft;
        delete quadTree1->bottomRight;
    }

    return quadTree1;
}
```
The algorithm for this problem can be solved using a tree traversal approach. The base cases are when either of the quadTrees (quadTree1 or quadTree2) are leaf nodes. If either one is a leaf and has a value of 1 (true), we return that leaf. Otherwise, we return the other leaf.

Next, we recursively compute the OR operation on the child nodes:
- topLeft: quadTree1.topLeft and quadTree2.topLeft
- topRight: quadTree1.topRight and quadTree2.topRight
- bottomLeft: quadTree1.bottomLeft and quadTree2.bottomLeft
- bottomRight: quadTree1.bottomRight and quadTree2.bottomRight

After the recursion, we check if all the children are leaf nodes and have the same value. If so, we can collapse the tree into a single leaf node with that value, effectively compressing the quadtree.

Finally, we return the resulting quadTree.

## A solution in Python

```python
class TreeNode:
    def __init__(self, isLeaf, val, topLeft=None, topRight=None, bottomLeft=None, bottomRight=None):
        self.isLeaf = isLeaf
        self.val = val
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight

def intersect(quadTree1, quadTree2):
    if quadTree1.isLeaf:
        return quadTree1 if quadTree1.val else quadTree2
    if quadTree2.isLeaf:
        return quadTree2 if quadTree2.val else quadTree1

    quadTree1.topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft)
    quadTree1.topRight = intersect(quadTree1.topRight, quadTree2.topRight)
    quadTree1.bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft)
    quadTree1.bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight)

    if quadTree1.topLeft.isLeaf and quadTree1.topRight.isLeaf and quadTree1.bottomLeft.isLeaf and quadTree1.bottomRight.isLeaf and quadTree1.topLeft.val == quadTree1.topRight.val == quadTree1.bottomLeft.val == quadTree1.bottomRight.val:
        quadTree1.isLeaf = True
        quadTree1.val = quadTree1.topLeft.val

    return quadTree1
```
The algorithm for this problem can be solved using a tree traversal approach. The base cases are when either of the quadTrees (quadTree1 or quadTree2) are leaf nodes. If either one is a leaf and has a value of 1 (true), we return that leaf. Otherwise, we return the other leaf.

Next, we recursively compute the OR operation on the child nodes:
- topLeft: quadTree1.topLeft and quadTree2.topLeft
- topRight: quadTree1.topRight and quadTree2.topRight
- bottomLeft: quadTree1.bottomLeft and quadTree2.bottomLeft
- bottomRight: quadTree1.bottomRight and quadTree2.bottomRight

After the recursion, we check if all the children are leaf nodes and have the same value. If so, we can collapse the tree into a single leaf node with that value, effectively compressing the quadtree.

Finally, we return the resulting quadTree.

## A solution in Javascript

```javascript
class TreeNode {
    constructor(isLeaf, val, topLeft = null, topRight = null, bottomLeft = null, bottomRight = null) {
        this.isLeaf = isLeaf;
        this.val = val;
        this.topLeft = topLeft;
        this.topRight = topRight;
        this.bottomLeft = bottomLeft;
        this.bottomRight = bottomRight;
    }
}

function intersect(quadTree1, quadTree2) {
    if (quadTree1.isLeaf) {
        return quadTree1.val ? quadTree1 : quadTree2;
    }
    if (quadTree2.isLeaf) {
        return quadTree2.val ? quadTree2 : quadTree1;
    }

    quadTree1.topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft);
    quadTree1.topRight = intersect(quadTree1.topRight, quadTree2.topRight);
    quadTree1.bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft);
    quadTree1.bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight);

    if (quadTree1.topLeft.isLeaf && quadTree1.topRight.isLeaf && quadTree1.bottomLeft.isLeaf && quadTree1.bottomRight.isLeaf && quadTree1.topLeft.val == quadTree1.topRight.val && quadTree1.topRight.val == quadTree1.bottomLeft.val && quadTree1.bottomLeft.val == quadTree1.bottomRight.val) {
        quadTree1.isLeaf = true;
        quadTree1.val = quadTree1.topLeft.val;
    }

    return quadTree1;
}
```
The algorithm for this problem can be solved using a tree traversal approach. The base cases are when either of the quadTrees (quadTree1 or quadTree2) are leaf nodes. If either one is a leaf and has a value of 1 (true), we return that leaf. Otherwise, we return the other leaf.

Next, we recursively compute the OR operation on the child nodes:
- topLeft: quadTree1.topLeft and quadTree2.topLeft
- topRight: quadTree1.topRight and quadTree2.topRight
- bottomLeft: quadTree1.bottomLeft and quadTree2.bottomLeft
- bottomRight: quadTree1.bottomRight and quadTree2.bottomRight

After the recursion, we check if all the children are leaf nodes and have the same value. If so, we can collapse the tree into a single leaf node with that value, effectively compressing the quadtree.

Finally, we return the resulting quadTree.


# Minimize Max Distance to Gas Station

- slug: minimize-max-distance-to-gas-station
- difficulty: Hard

You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`.

You should add `k` new gas stations. You can add the stations anywhere on the **x-axis**, and not necessarily on an integer position.

Let `penalty()` be the maximum distance between **adjacent** gas stations after adding the `k` new stations.

Return _the smallest possible value of_ `penalty()`. Answers within `10-6` of the actual answer will be accepted.

**Example 1:**

**Input:** stations = \[1,2,3,4,5,6,7,8,9,10\], k = 9
**Output:** 0.50000

**Example 2:**

**Input:** stations = \[23,24,36,39,46,56,57,65,84,98\], k = 1
**Output:** 14.00000

**Constraints:**

*   `10 <= stations.length <= 2000`
*   `0 <= stations[i] <= 108`
*   `stations` is sorted in a **strictly increasing** order.
*   `1 <= k <= 106`

## A solution in Java

```java
import java.util.List;

class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }
}

public int maxDepth(Node root) {
    if (root == null) {
        return 0;
    }
    int depth = 0;
    for (Node child : root.children) {
        depth = Math.max(depth, maxDepth(child));
    }
    return 1 + depth;
}
```
The algorithm works by recursively traversing the n-ary tree. It visits each node in the tree and calculates the maximum depth for each of its children. To find the maximum depth for the entire tree, it takes the maximum depth of all children and adds 1, representing the current root node. If the root is `null` or `None`, the maximum depth is 0.

Each language implementation utilizes a `Node` class with a constructor to store the node value and children. It also has a `maxDepth` function that carries out the algorithm mentioned above. The difference among the languages lies only in the syntax for the class definitions and function calls.

## A solution in C++

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

class Node {
public:
    int val;
    std::vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }
};

int maxDepth(Node* root) {
    if (root == nullptr) {
        return 0;
    }
    int depth = 0;
    for (Node* child : root->children) {
        depth = std::max(depth, maxDepth(child));
    }
    return 1 + depth;
}
```
The algorithm works by recursively traversing the n-ary tree. It visits each node in the tree and calculates the maximum depth for each of its children. To find the maximum depth for the entire tree, it takes the maximum depth of all children and adds 1, representing the current root node. If the root is `null` or `None`, the maximum depth is 0.

Each language implementation utilizes a `Node` class with a constructor to store the node value and children. It also has a `maxDepth` function that carries out the algorithm mentioned above. The difference among the languages lies only in the syntax for the class definitions and function calls.

## A solution in Python

```python
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children if children is not None else []

def max_depth(root):
    if root is None:
        return 0
    depth = 0
    for child in root.children:
        depth = max(depth, max_depth(child))
    return 1 + depth
```
The algorithm works by recursively traversing the n-ary tree. It visits each node in the tree and calculates the maximum depth for each of its children. To find the maximum depth for the entire tree, it takes the maximum depth of all children and adds 1, representing the current root node. If the root is `null` or `None`, the maximum depth is 0.

Each language implementation utilizes a `Node` class with a constructor to store the node value and children. It also has a `maxDepth` function that carries out the algorithm mentioned above. The difference among the languages lies only in the syntax for the class definitions and function calls.

## A solution in Javascript

```javascript
class Node {
    constructor(val, children = []) {
        this.val = val;
        this.children = children;
    }
}

function maxDepth(root) {
    if (root === null) {
        return 0;
    }
    let depth = 0;
    for (const child of root.children) {
        depth = Math.max(depth, maxDepth(child));
    }
    return 1 + depth;
}
```
The algorithm works by recursively traversing the n-ary tree. It visits each node in the tree and calculates the maximum depth for each of its children. To find the maximum depth for the entire tree, it takes the maximum depth of all children and adds 1, representing the current root node. If the root is `null` or `None`, the maximum depth is 0.

Each language implementation utilizes a `Node` class with a constructor to store the node value and children. It also has a `maxDepth` function that carries out the algorithm mentioned above. The difference among the languages lies only in the syntax for the class definitions and function calls.


# Global and Local Inversions

- slug: global-and-local-inversions
- difficulty: Medium

You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`.

The number of **global inversions** is the number of the different pairs `(i, j)` where:

*   `0 <= i < j < n`
*   `nums[i] > nums[j]`

The number of **local inversions** is the number of indices `i` where:

*   `0 <= i < n - 1`
*   `nums[i] > nums[i + 1]`

Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_.

**Example 1:**

**Input:** nums = \[1,0,2\]
**Output:** true
**Explanation:** There is 1 global inversion and 1 local inversion.

**Example 2:**

**Input:** nums = \[1,2,0\]
**Output:** false
**Explanation:** There are 2 global inversions and 1 local inversion.

**Constraints:**

*   `n == nums.length`
*   `1 <= n <= 105`
*   `0 <= nums[i] < n`
*   All the integers of `nums` are **unique**.
*   `nums` is a permutation of all the numbers in the range `[0, n - 1]`.

## A solution in Java

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

class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) { val = _val; }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
}

class Solution {
    private void helper(Node root, List<Integer> result) {
        if (root == null) return;
        result.add(root.val);
        for (Node child : root.children) {
            helper(child, result);
        }
    }

    public List<Integer> preorder(Node root) {
        List<Integer> result = new ArrayList<>();
        helper(root, result);
        return result;
    }
}
```
The algorithm uses a helper function to perform a Depth First Search traversal on the given N-ary tree. The helper function is called recursively for each child of the current node, following a preorder traversal (i.e., visiting the current node before its children). During the traversal, the value of each node is added to the result list/array. The primary function returns this result list/array when the traversal is complete.

## A solution in C++

```cpp
#include <vector>

class Node {
public:
    int val;
    std::vector<Node*> children;

    Node() {}
    Node(int _val) { val = _val; }
    Node(int _val, std::vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};

void helper(Node* root, std::vector<int>& result) {
    if (!root) return;
    result.push_back(root->val);
    for (Node* child : root->children) {
        helper(child, result);
    }
}

std::vector<int> preorder(Node* root) {
    std::vector<int> result;
    helper(root, result);
    return result;
}
```
The algorithm uses a helper function to perform a Depth First Search traversal on the given N-ary tree. The helper function is called recursively for each child of the current node, following a preorder traversal (i.e., visiting the current node before its children). During the traversal, the value of each node is added to the result list/array. The primary function returns this result list/array when the traversal is complete.

## A solution in Python

```python
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children if children is not None else []

def helper(root, result):
    if not root:
        return
    result.append(root.val)
    for child in root.children:
        helper(child, result)

def preorder(root):
    result = []
    helper(root, result)
    return result
```
The algorithm uses a helper function to perform a Depth First Search traversal on the given N-ary tree. The helper function is called recursively for each child of the current node, following a preorder traversal (i.e., visiting the current node before its children). During the traversal, the value of each node is added to the result list/array. The primary function returns this result list/array when the traversal is complete.

## A solution in Javascript

```javascript
class Node {
    constructor(val, children) {
        this.val = val === undefined ? 0 : val;
        this.children = children === undefined ? [] : children;
    }
}

var helper = function (root, result) {
    if (root === null) return;
    result.push(root.val);
    for (let child of root.children) {
        helper(child, result);
    }
}

var preorder = function (root) {
    let result = [];
    helper(root, result);
    return result;
};
```
The algorithm uses a helper function to perform a Depth First Search traversal on the given N-ary tree. The helper function is called recursively for each child of the current node, following a preorder traversal (i.e., visiting the current node before its children). During the traversal, the value of each node is added to the result list/array. The primary function returns this result list/array when the traversal is complete.


# Split BST

- slug: split-bst
- difficulty: Medium

Given the `root` of a binary search tree (BST) and an integer `target`, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, while the other subtree has all nodes that are greater than the target value. It Is not necessarily the case that the tree contains a node with the value `target`.

Additionally, most of the structure of the original tree should remain. Formally, for any child `c` with parent `p` in the original tree, if they are both in the same subtree after the split, then node `c` should still have the parent `p`.

Return _an array of the two roots of the two subtrees_.

**Example 1:**

**Input:** root = \[4,2,6,1,3,5,7\], target = 2
**Output:** \[\[2,1\],\[4,3,6,null,null,5,7\]\]

**Example 2:**

**Input:** root = \[1\], target = 1
**Output:** \[\[1\],\[\]\]

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 50]`.
*   `0 <= Node.val, target <= 1000`

## A solution in Java

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

class Node {
    public int val;
    public List<Node> children;

    public Node() {}
    public Node(int _val) {val = _val;}
    public Node(int _val, List<Node> _children) {val = _val; children = _children;}
}

public List<Integer> postorder(Node root) {
    List<Integer> result = new ArrayList<>();
    if(root == null) return result;

    Stack<Node> stack = new Stack<>();
    stack.push(root);
    while(!stack.isEmpty()) {
        Node current = stack.pop();

        result.add(current.val);
        for(Node child : current.children) {
            stack.push(child);
        }
    }
    Collections.reverse(result);
    return result;
}
```
The algorithm uses an iterative approach with a stack to perform the postorder traversal of the n-ary tree. Instead of appending the values of the nodes during the traversal, the values are pushed to the result list. As we go deeper into the tree, the children of each node encountered are pushed onto a stack to keep track of the nodes to visit next.

After traversing the tree, the result list is reversed, which gives the desired postorder traversal.

This algorithm works for all the languages mentioned: C++, Java, Python, and JavaScript, with minor syntax differences for handling the stack and the children of the nodes.

## A solution in C++

```cpp
#include <vector>
#include <stack>

class Node {
public:
    int val;
    std::vector<Node*> children;

    Node() {}
    Node(int _val) {val = _val;}
    Node(int _val, std::vector<Node*> _children) {val = _val; children = _children;}
};

std::vector<int> postorder(Node* root) {
    std::vector<int> result;
    if(root == nullptr) return result;

    std::stack<Node*> s;
    s.push(root);
    while(!s.empty()) {
        Node* curr = s.top();
        s.pop();

        result.push_back(curr->val);
        for(Node* child : curr->children) {
            s.push(child);
        }
    }
    std::reverse(result.begin(), result.end());
    return result;
}
```
The algorithm uses an iterative approach with a stack to perform the postorder traversal of the n-ary tree. Instead of appending the values of the nodes during the traversal, the values are pushed to the result list. As we go deeper into the tree, the children of each node encountered are pushed onto a stack to keep track of the nodes to visit next.

After traversing the tree, the result list is reversed, which gives the desired postorder traversal.

This algorithm works for all the languages mentioned: C++, Java, Python, and JavaScript, with minor syntax differences for handling the stack and the children of the nodes.

## A solution in Python

```python
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children if children is not None else []

def postorder(root: 'Node'):
    if root is None:
        return []

    result = []
    stack = [root]

    while stack:
        curr = stack.pop()
        result.append(curr.val)
        stack.extend(curr.children)

    return result[::-1]
```
The algorithm uses an iterative approach with a stack to perform the postorder traversal of the n-ary tree. Instead of appending the values of the nodes during the traversal, the values are pushed to the result list. As we go deeper into the tree, the children of each node encountered are pushed onto a stack to keep track of the nodes to visit next.

After traversing the tree, the result list is reversed, which gives the desired postorder traversal.

This algorithm works for all the languages mentioned: C++, Java, Python, and JavaScript, with minor syntax differences for handling the stack and the children of the nodes.

## A solution in Javascript

```javascript
class Node {
    constructor(val, children) {
        this.val = val;
        this.children = children ? children : [];
    }
}

function postorder(root) {
    if (!root) return [];

    let result = [];
    let stack = [root];

    while (stack.length) {
        let current = stack.pop();
        result.push(current.val);
        stack.push(...current.children);
    }

    return result.reverse();
}
```
The algorithm uses an iterative approach with a stack to perform the postorder traversal of the n-ary tree. Instead of appending the values of the nodes during the traversal, the values are pushed to the result list. As we go deeper into the tree, the children of each node encountered are pushed onto a stack to keep track of the nodes to visit next.

After traversing the tree, the result list is reversed, which gives the desired postorder traversal.

This algorithm works for all the languages mentioned: C++, Java, Python, and JavaScript, with minor syntax differences for handling the stack and the children of the nodes.


# Swap Adjacent in LR String

- slug: swap-adjacent-in-lr-string
- difficulty: Medium

In a string composed of `'L'`, `'R'`, and `'X'` characters, like `"RXXLRXRXL "`, a move consists of either replacing one occurrence of `"XL "` with `"LX "`, or replacing one occurrence of `"RX "` with `"XR "`. Given the starting string `start` and the ending string `end`, return `True` if and only if there exists a sequence of moves to transform one string to the other.

**Example 1:**

**Input:** start =  "RXXLRXRXL ", end =  "XRLXXRRLX "
**Output:** true
**Explanation:** We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX

**Example 2:**

**Input:** start =  "X ", end =  "L "
**Output:** false

**Constraints:**

*   `1 <= start.length <= 104`
*   `start.length == end.length`
*   Both `start` and `end` will only consist of characters in `'L'`, `'R'`, and `'X'`.

## A solution in Java

```java
public boolean isToeplitzMatrix(int[][] matrix) {
    int rows = matrix.length;
    int cols = matrix[0].length;
    for(int i = 0; i < rows - 1; i++) {
        for(int j = 0; j < cols - 1; j++) {
            if(matrix[i][j] != matrix[i+1][j+1]) return false;
        }
    }
    return true;
}
```
The algorithm iterates through each element in the matrix except the last row and last column. For each element, it checks if it is equal to the element on the bottom right diagonal. If any such pair of elements is not equal, the matrix is not Toeplitz and the function returns false. If every pair of elements is equal, the matrix is Toeplitz and the function returns true.

## A solution in C++

```cpp
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    for(int i = 0; i < rows - 1; ++i) {
        for(int j = 0; j < cols - 1; ++j) {
            if(matrix[i][j] != matrix[i+1][j+1]) return false;
        }
    }
    return true;
}
```
The algorithm iterates through each element in the matrix except the last row and last column. For each element, it checks if it is equal to the element on the bottom right diagonal. If any such pair of elements is not equal, the matrix is not Toeplitz and the function returns false. If every pair of elements is equal, the matrix is Toeplitz and the function returns true.

## A solution in Python

```python
def isToeplitzMatrix(matrix):
    rows = len(matrix)
    cols = len(matrix[0])
    for i in range(rows - 1):
        for j in range(cols - 1):
            if matrix[i][j] != matrix[i+1][j+1]:
                return False
    return True
```
The algorithm iterates through each element in the matrix except the last row and last column. For each element, it checks if it is equal to the element on the bottom right diagonal. If any such pair of elements is not equal, the matrix is not Toeplitz and the function returns false. If every pair of elements is equal, the matrix is Toeplitz and the function returns true.

## A solution in Javascript

```javascript
function isToeplitzMatrix(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;
    for(let i = 0; i < rows - 1; i++) {
        for(let j = 0; j < cols - 1; j++) {
            if(matrix[i][j] !== matrix[i+1][j+1]) return false;
        }
    }
    return true;
}
```
The algorithm iterates through each element in the matrix except the last row and last column. For each element, it checks if it is equal to the element on the bottom right diagonal. If any such pair of elements is not equal, the matrix is not Toeplitz and the function returns false. If every pair of elements is equal, the matrix is Toeplitz and the function returns true.