# Encode N-ary Tree to Binary Tree

- slug: encode-n-ary-tree-to-binary-tree
- difficulty: Hard

Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure.

_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example)._

For example, you may encode the following `3-ary` tree to a binary tree in this way:

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

Note that the above is just an example which _might or might not_ work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

**Example 1:**

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

**Example 2:**

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

**Example 3:**

**Input:** root = \[\]
**Output:** \[\]

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 104]`.
*   `0 <= Node.val <= 104`
*   The height of the n-ary tree is less than or equal to `1000`
*   Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.

## A solution in Java

```java
class NaryTreeNode {
    int val;
    List<NaryTreeNode> children;
}

class BinaryTreeNode {
    int val;
    BinaryTreeNode left, right;
}

public BinaryTreeNode encode(NaryTreeNode root) {
    if (root == null) return null;
    BinaryTreeNode binaryRoot = new BinaryTreeNode();
    binaryRoot.val = root.val;
    if (root.children.size() > 0)
        binaryRoot.left = encode(root.children.get(0));
    BinaryTreeNode sibling = binaryRoot.left;
    for (int i = 1; i < root.children.size(); ++i) {
        sibling.right = encode(root.children.get(i));
        sibling = sibling.right;
    }
    return binaryRoot;
}

public NaryTreeNode decode(BinaryTreeNode root) {
    if (root == null) return null;
    NaryTreeNode naryRoot = new NaryTreeNode();
    naryRoot.val = root.val;
    naryRoot.children = new ArrayList<>();
    BinaryTreeNode sibling = root.left;
    while (sibling != null) {
        naryRoot.children.add(decode(sibling));
        sibling = sibling.right;
    }
    return naryRoot;
}
```
To encode the given N-ary tree into a binary tree recursively, we perform the following steps:

1. For each node of the N-ary tree, create a corresponding binary tree node with the same value.
2. Store the first child of the N-ary tree node as the left child of the binary tree node.
3. Iterate through the remaining children in the N-ary tree node, placing each child to the right of the first child of the binary tree node. In other words, we represent the siblings of the N-ary tree as the right children in the binary tree.
4. We repeat this process until every node in the given N-ary tree has been processed.

For decoding the binary tree back to N-ary tree, we reverse the process followed for encoding. While traversing the binary tree, we create a new N-ary tree node with the same value, retrieve its children from the left child and its subsequent right children of the binary tree node.

Note, in both cases, we recursively perform the process for every node in the original tree.

The above algorithms are shown in C++, Java, Python, and JavaScript.

## A solution in C++

```cpp
struct NaryTreeNode {
    int val;
    vector<NaryTreeNode*> children;
};

struct BinaryTreeNode {
    int val;
    BinaryTreeNode *left, *right;
};

BinaryTreeNode* encode(NaryTreeNode* root) {
    if (!root) return nullptr;
    BinaryTreeNode* binaryRoot = new BinaryTreeNode();
    binaryRoot->val = root->val;
    if (root->children.size() > 0)
        binaryRoot->left = encode(root->children[0]);
    BinaryTreeNode* sibling = binaryRoot->left;
    for (int i = 1; i < root->children.size(); ++i) {
        sibling->right = encode(root->children[i]);
        sibling = sibling->right;
    }
    return binaryRoot;
}

NaryTreeNode* decode(BinaryTreeNode* root) {
    if (!root) return nullptr;
    NaryTreeNode* naryRoot = new NaryTreeNode();
    naryRoot->val = root->val;
    BinaryTreeNode* sibling = root->left;
    while (sibling) {
        naryRoot->children.push_back(decode(sibling));
        sibling = sibling->right;
    }
    return naryRoot;
}
```
To encode the given N-ary tree into a binary tree recursively, we perform the following steps:

1. For each node of the N-ary tree, create a corresponding binary tree node with the same value.
2. Store the first child of the N-ary tree node as the left child of the binary tree node.
3. Iterate through the remaining children in the N-ary tree node, placing each child to the right of the first child of the binary tree node. In other words, we represent the siblings of the N-ary tree as the right children in the binary tree.
4. We repeat this process until every node in the given N-ary tree has been processed.

For decoding the binary tree back to N-ary tree, we reverse the process followed for encoding. While traversing the binary tree, we create a new N-ary tree node with the same value, retrieve its children from the left child and its subsequent right children of the binary tree node.

Note, in both cases, we recursively perform the process for every node in the original tree.

The above algorithms are shown in C++, Java, Python, and JavaScript.

## A solution in Python

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

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

def encode(root: NaryTreeNode) -> BinaryTreeNode:
    if not root:
        return None
    binary_root = BinaryTreeNode(root.val)
    if root.children:
        binary_root.left = encode(root.children[0])
    sibling = binary_root.left
    for child in root.children[1:]:
        sibling.right = encode(child)
        sibling = sibling.right
    return binary_root

def decode(root: BinaryTreeNode) -> NaryTreeNode:
    if not root:
        return None
    nary_root = NaryTreeNode(root.val)
    sibling = root.left
    while sibling:
        nary_root.children.append(decode(sibling))
        sibling = sibling.right
    return nary_root
```
To encode the given N-ary tree into a binary tree recursively, we perform the following steps:

1. For each node of the N-ary tree, create a corresponding binary tree node with the same value.
2. Store the first child of the N-ary tree node as the left child of the binary tree node.
3. Iterate through the remaining children in the N-ary tree node, placing each child to the right of the first child of the binary tree node. In other words, we represent the siblings of the N-ary tree as the right children in the binary tree.
4. We repeat this process until every node in the given N-ary tree has been processed.

For decoding the binary tree back to N-ary tree, we reverse the process followed for encoding. While traversing the binary tree, we create a new N-ary tree node with the same value, retrieve its children from the left child and its subsequent right children of the binary tree node.

Note, in both cases, we recursively perform the process for every node in the original tree.

The above algorithms are shown in C++, Java, Python, and JavaScript.

## A solution in Javascript

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

class BinaryTreeNode {
    constructor(val = 0, left = null, right = null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

function encode(root) {
    if (!root) return null;
    const binaryRoot = new BinaryTreeNode(root.val);
    if (root.children.length > 0) {
        binaryRoot.left = encode(root.children[0]);
    }
    let sibling = binaryRoot.left;
    for (let i = 1; i < root.children.length; ++i) {
        sibling.right = encode(root.children[i]);
        sibling = sibling.right;
    }
    return binaryRoot;
}

function decode(root) {
    if (!root) return null;
    const naryRoot = new NaryTreeNode(root.val);
    let sibling = root.left;
    while (sibling) {
        naryRoot.children.push(decode(sibling));
        sibling = sibling.right;
    }
    return naryRoot;
}
```
To encode the given N-ary tree into a binary tree recursively, we perform the following steps:

1. For each node of the N-ary tree, create a corresponding binary tree node with the same value.
2. Store the first child of the N-ary tree node as the left child of the binary tree node.
3. Iterate through the remaining children in the N-ary tree node, placing each child to the right of the first child of the binary tree node. In other words, we represent the siblings of the N-ary tree as the right children in the binary tree.
4. We repeat this process until every node in the given N-ary tree has been processed.

For decoding the binary tree back to N-ary tree, we reverse the process followed for encoding. While traversing the binary tree, we create a new N-ary tree node with the same value, retrieve its children from the left child and its subsequent right children of the binary tree node.

Note, in both cases, we recursively perform the process for every node in the original tree.

The above algorithms are shown in C++, Java, Python, and JavaScript.


# All O`one Data Structure

- slug: all-oone-data-structure
- difficulty: Hard

Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.

Implement the `AllOne` class:

*   `AllOne()` Initializes the object of the data structure.
*   `inc(String key)` Increments the count of the string `key` by `1`. If `key` does not exist in the data structure, insert it with count `1`.
*   `dec(String key)` Decrements the count of the string `key` by `1`. If the count of `key` is `0` after the decrement, remove it from the data structure. It is guaranteed that `key` exists in the data structure before the decrement.
*   `getMaxKey()` Returns one of the keys with the maximal count. If no element exists, return an empty string `" "`.
*   `getMinKey()` Returns one of the keys with the minimum count. If no element exists, return an empty string `" "`.

**Note** that each function must run in `O(1)` average time complexity.

**Example 1:**

**Input**
\[ "AllOne ",  "inc ",  "inc ",  "getMaxKey ",  "getMinKey ",  "inc ",  "getMaxKey ",  "getMinKey "\]
\[\[\], \[ "hello "\], \[ "hello "\], \[\], \[\], \[ "leet "\], \[\], \[\]\]
**Output**
\[null, null, null,  "hello ",  "hello ", null,  "hello ",  "leet "\]

**Explanation**
AllOne allOne = new AllOne();
allOne.inc( "hello ");
allOne.inc( "hello ");
allOne.getMaxKey(); // return  "hello "
allOne.getMinKey(); // return  "hello "
allOne.inc( "leet ");
allOne.getMaxKey(); // return  "hello "
allOne.getMinKey(); // return  "leet "

**Constraints:**

*   `1 <= key.length <= 10`
*   `key` consists of lowercase English letters.
*   It is guaranteed that for each call to `dec`, `key` is existing in the data structure.
*   At most `5 * 104` calls will be made to `inc`, `dec`, `getMaxKey`, and `getMinKey`.

## A solution in Java

```java
import java.util.*;

public class AllOne {
    private HashMap<String, Integer> data;

    public AllOne() {
        data = new HashMap<String, Integer>();
    }

    public void inc(String key) {
        data.put(key, data.getOrDefault(key, 0) + 1);
    }

    public void dec(String key) {
        data.put(key, data.getOrDefault(key, 0) - 1);
        if (data.get(key) == 0) {
            data.remove(key);
        }
    }

    public String getMaxKey() {
        if (data.isEmpty()) return "";
        return Collections.max(data.entrySet(), Map.Entry.comparingByValue()).getKey();
    }

    public String getMinKey() {
        if (data.isEmpty()) return "";
        return Collections.min(data.entrySet(), Map.Entry.comparingByValue()).getKey();
    }
}
```
- The algorithm stores the count of strings in a hash map/dictionary, where the keys are the strings and the values are the counts.
- For `inc` function, increment the corresponding count for the given string in the data structure using its key.
- For `dec` function, decrement the corresponding count for the given string if it exists in the data structure, and if the count becomes 0, remove the key-value pair from the data structure.
- For `getMaxKey` function, find the key with the highest count value in the key-value pairs.
- For `getMinKey` function, find the key with the lowest count value in the key-value pairs.

Note that each language has its specific ways to implement each of these operations, taking advantage of their specific features (e.g., lambdas in C++, or list comprehensions in Python).

## A solution in C++

```cpp
class AllOne {
public:
    unordered_map<string, int> data;
    void inc(string key) {
        data[key]++;
    }
    void dec(string key) {
        if (data[key] > 0) data[key]--;
        if (data[key] == 0) data.erase(key);
    }
    string getMaxKey() {
        if (data.empty()) return "";
        return max_element(data.begin(), data.end(),
            [](const auto& a, const auto& b) { return a.second < b.second; })->first;
    }
    string getMinKey() {
        if (data.empty()) return "";
        return min_element(data.begin(), data.end(),
            [](const auto& a, const auto& b) { return a.second < b.second; })->first;
    }
};
```
- The algorithm stores the count of strings in a hash map/dictionary, where the keys are the strings and the values are the counts.
- For `inc` function, increment the corresponding count for the given string in the data structure using its key.
- For `dec` function, decrement the corresponding count for the given string if it exists in the data structure, and if the count becomes 0, remove the key-value pair from the data structure.
- For `getMaxKey` function, find the key with the highest count value in the key-value pairs.
- For `getMinKey` function, find the key with the lowest count value in the key-value pairs.

Note that each language has its specific ways to implement each of these operations, taking advantage of their specific features (e.g., lambdas in C++, or list comprehensions in Python).

## A solution in Python

```python
class AllOne:
    def __init__(self):
        self.data = dict()

    def inc(self, key: str) -> None:
        self.data[key] = self.data.get(key, 0) + 1

    def dec(self, key: str) -> None:
        self.data[key] = self.data.get(key, 0) - 1
        if self.data[key] == 0:
            del self.data[key]

    def getMaxKey(self) -> str:
        if not self.data:
            return ""
        return max(self.data, key=lambda x: self.data[x])

    def getMinKey(self) -> str:
        if not self.data:
            return ""
        return min(self.data, key=lambda x: self.data[x])
```
- The algorithm stores the count of strings in a hash map/dictionary, where the keys are the strings and the values are the counts.
- For `inc` function, increment the corresponding count for the given string in the data structure using its key.
- For `dec` function, decrement the corresponding count for the given string if it exists in the data structure, and if the count becomes 0, remove the key-value pair from the data structure.
- For `getMaxKey` function, find the key with the highest count value in the key-value pairs.
- For `getMinKey` function, find the key with the lowest count value in the key-value pairs.

Note that each language has its specific ways to implement each of these operations, taking advantage of their specific features (e.g., lambdas in C++, or list comprehensions in Python).

## A solution in Javascript

```javascript
class AllOne {
    constructor() {
        this.data = new Map();
    }

    inc(key) {
        this.data.set(key, (this.data.get(key) || 0) + 1);
    }

    dec(key) {
        if (this.data.has(key)) {
            if (this.data.get(key) === 1) {
                this.data.delete(key);
            } else {
                this.data.set(key, this.data.get(key) - 1);
            }
        }
    }

    getMaxKey() {
        if (this.data.size === 0) return "";
        return [...this.data.entries()].reduce((a, b) => (a[1] > b[1] ? a : b))[0];
    }

    getMinKey() {
        if (this.data.size === 0) return "";
        return [...this.data.entries()].reduce((a, b) => (a[1] < b[1] ? a : b))[0];
    }
}
```
- The algorithm stores the count of strings in a hash map/dictionary, where the keys are the strings and the values are the counts.
- For `inc` function, increment the corresponding count for the given string in the data structure using its key.
- For `dec` function, decrement the corresponding count for the given string if it exists in the data structure, and if the count becomes 0, remove the key-value pair from the data structure.
- For `getMaxKey` function, find the key with the highest count value in the key-value pairs.
- For `getMinKey` function, find the key with the lowest count value in the key-value pairs.

Note that each language has its specific ways to implement each of these operations, taking advantage of their specific features (e.g., lambdas in C++, or list comprehensions in Python).


# Minimum Genetic Mutation

- slug: minimum-genetic-mutation
- difficulty: Medium

A gene string can be represented by an 8-character long string, with choices from `'A'`, `'C'`, `'G'`, and `'T'`.

Suppose we need to investigate a mutation from a gene string `startGene` to a gene string `endGene` where one mutation is defined as one single character changed in the gene string.

*   For example, `"AACCGGTT " --> "AACCGGTA "` is one mutation.

There is also a gene bank `bank` that records all the valid gene mutations. A gene must be in `bank` to make it a valid gene string.

Given the two gene strings `startGene` and `endGene` and the gene bank `bank`, return _the minimum number of mutations needed to mutate from_ `startGene` _to_ `endGene`. If there is no such a mutation, return `-1`.

Note that the starting point is assumed to be valid, so it might not be included in the bank.

**Example 1:**

**Input:** startGene =  "AACCGGTT ", endGene =  "AACCGGTA ", bank = \[ "AACCGGTA "\]
**Output:** 1

**Example 2:**

**Input:** startGene =  "AACCGGTT ", endGene =  "AAACGGTA ", bank = \[ "AACCGGTA ", "AACCGCTA ", "AAACGGTA "\]
**Output:** 2

**Constraints:**

*   `0 <= bank.length <= 10`
*   `startGene.length == endGene.length == bank[i].length == 8`
*   `startGene`, `endGene`, and `bank[i]` consist of only the characters `['A', 'C', 'G', 'T']`.

## A solution in Java

```java
import java.util.*;

public int minMutation(String start, String end, String[] bank) {
    Queue<String> q = new LinkedList<>();
    q.offer(start);
    Set<String> visited = new HashSet<>();
    visited.add(start);
    int depth = 0;

    while (!q.isEmpty()) {
        int levelSize = q.size();
        for (int i = 0; i < levelSize; i++) {
            String current = q.poll();
            if (current.equals(end)) return depth;

            for (String gene : bank) {
                if (!visited.contains(gene)) {
                    int diff = 0;
                    for (int j = 0; j < 8; j++) {
                        if (current.charAt(j) != gene.charAt(j)) diff++;
                        if (diff > 1) break;
                    }

                    if (diff == 1) {
                        q.offer(gene);
                        visited.add(gene);
                    }
                }
            }
        }
        depth++;
    }
    return -1;
}
```
1. Use a queue to perform Breadth-First Search.
2. Push the starting gene onto the queue, and add it to the visited set.
3. Iterate until the queue is empty.
   - Iterate through each level (mutations with the same depth) to find valid gene mutations.
   - For each gene in the bank, if it has not been visited:
     - Calculate the difference between the current gene and other genes by iterating character by character.
     - If the difference is only 1, push the new gene onto the queue and add it to the visited set.
   - Increase the depth (mutation count) after each level has been fully considered.
4. If the loop ends and the end gene has not been found, return -1, otherwise return the depth.

## A solution in C++

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

int minMutation(std::string start, std::string end, std::vector<std::string>& bank) {
    std::queue<std::string> q;
    q.push(start);
    std::unordered_set<std::string> visited;
    visited.insert(start);
    int depth = 0;

    while (!q.empty()) {
        int levelSize = q.size();
        for (int i = 0; i < levelSize; ++i) {
            std::string current = q.front();
            q.pop();
            if (current == end) return depth;

            for (const auto& gene : bank) {
                if (!visited.count(gene)) {
                    int diff = 0;
                    for (int j = 0; j < 8; ++j) {
                        if (current[j] != gene[j]) ++diff;
                        if (diff > 1) break;
                    }

                    if (diff == 1) {
                        q.push(gene);
                        visited.insert(gene);
                    }
                }
            }
        }
        depth++;
    }
    return -1;
}
```
1. Use a queue to perform Breadth-First Search.
2. Push the starting gene onto the queue, and add it to the visited set.
3. Iterate until the queue is empty.
   - Iterate through each level (mutations with the same depth) to find valid gene mutations.
   - For each gene in the bank, if it has not been visited:
     - Calculate the difference between the current gene and other genes by iterating character by character.
     - If the difference is only 1, push the new gene onto the queue and add it to the visited set.
   - Increase the depth (mutation count) after each level has been fully considered.
4. If the loop ends and the end gene has not been found, return -1, otherwise return the depth.

## A solution in Python

```python
from collections import deque

def minMutation(start, end, bank):
    q = deque([start])
    visited = set([start])
    depth = 0

    while q:
        levelSize = len(q)
        for _ in range(levelSize):
            current = q.popleft()
            if current == end:
                return depth

            for gene in bank:
                if gene not in visited:
                    diff = sum(1 for j in range(8) if current[j] != gene[j])
                    if diff == 1:
                        q.append(gene)
                        visited.add(gene)
        depth += 1
    return -1
```
1. Use a queue to perform Breadth-First Search.
2. Push the starting gene onto the queue, and add it to the visited set.
3. Iterate until the queue is empty.
   - Iterate through each level (mutations with the same depth) to find valid gene mutations.
   - For each gene in the bank, if it has not been visited:
     - Calculate the difference between the current gene and other genes by iterating character by character.
     - If the difference is only 1, push the new gene onto the queue and add it to the visited set.
   - Increase the depth (mutation count) after each level has been fully considered.
4. If the loop ends and the end gene has not been found, return -1, otherwise return the depth.

## A solution in Javascript

```javascript
function minMutation(start, end, bank) {
    const q = [start];
    const visited = new Set([start]);
    let depth = 0;

    while (q.length) {
        const levelSize = q.length;
        for (let i = 0; i < levelSize; i++) {
            const current = q.shift();
            if (current === end) return depth;

            for (const gene of bank) {
                if (!visited.has(gene)) {
                    let diff = 0;
                    for (let j = 0; j < 8; j++) {
                        if (current[j] !== gene[j]) diff++;
                        if (diff > 1) break;
                    }

                    if (diff === 1) {
                        q.push(gene);
                        visited.add(gene);
                    }
                }
            }
        }
        depth++;
    }
    return -1;
}
```
1. Use a queue to perform Breadth-First Search.
2. Push the starting gene onto the queue, and add it to the visited set.
3. Iterate until the queue is empty.
   - Iterate through each level (mutations with the same depth) to find valid gene mutations.
   - For each gene in the bank, if it has not been visited:
     - Calculate the difference between the current gene and other genes by iterating character by character.
     - If the difference is only 1, push the new gene onto the queue and add it to the visited set.
   - Increase the depth (mutation count) after each level has been fully considered.
4. If the loop ends and the end gene has not been found, return -1, otherwise return the depth.


# Number of Segments in a String

- slug: number-of-segments-in-a-string
- difficulty: Easy

Given a string `s`, return _the number of segments in the string_.

A **segment** is defined to be a contiguous sequence of **non-space characters**.

**Example 1:**

**Input:** s =  "Hello, my name is John "
**Output:** 5
**Explanation:** The five segments are \[ "Hello, ",  "my ",  "name ",  "is ",  "John "\]

**Example 2:**

**Input:** s =  "Hello "
**Output:** 1

**Constraints:**

*   `0 <= s.length <= 300`
*   `s` consists of lowercase and uppercase English letters, digits, or one of the following characters `"!@#$%^&*()_+-=',.: "`.
*   The only space character in `s` is `' '`.

## A solution in Java

```java
public int countSegments(String s) {
    if (s == null || s.trim().length() == 0) {
        return 0;
    }
    String[] segments = s.trim().split("\\s+");
    return segments.length;
}
```
The algorithm goes as follows:

1. Remove leading and trailing spaces from the input string.
2. Split the string on any whitespace into an array or list.
3. Return the length of the resulting array or list, which corresponds to the number of segments in the input string.

In C++, the `std::stringstream` is used to read words separated by spaces with the `>>` operator. Java and JavaScript use a regex to match any whitespace, and Python has a built-in `split()` method that splits on any whitespace by default.

## A solution in C++

```cpp
#include <string>
#include <sstream>

int countSegments(const std::string& s) {
    std::stringstream ss(s);
    int count = 0;
    std::string temp;

    while (ss >> temp) {
        ++count;
    }

    return count;
}
```
The algorithm goes as follows:

1. Remove leading and trailing spaces from the input string.
2. Split the string on any whitespace into an array or list.
3. Return the length of the resulting array or list, which corresponds to the number of segments in the input string.

In C++, the `std::stringstream` is used to read words separated by spaces with the `>>` operator. Java and JavaScript use a regex to match any whitespace, and Python has a built-in `split()` method that splits on any whitespace by default.

## A solution in Python

```python
def count_segments(s: str) -> int:
    return len(s.split())
```
The algorithm goes as follows:

1. Remove leading and trailing spaces from the input string.
2. Split the string on any whitespace into an array or list.
3. Return the length of the resulting array or list, which corresponds to the number of segments in the input string.

In C++, the `std::stringstream` is used to read words separated by spaces with the `>>` operator. Java and JavaScript use a regex to match any whitespace, and Python has a built-in `split()` method that splits on any whitespace by default.

## A solution in Javascript

```javascript
function countSegments(s) {
    if (!s || s.trim().length === 0) {
        return 0;
    }
    const segments = s.trim().split(/\s+/);
    return segments.length;
}
```
The algorithm goes as follows:

1. Remove leading and trailing spaces from the input string.
2. Split the string on any whitespace into an array or list.
3. Return the length of the resulting array or list, which corresponds to the number of segments in the input string.

In C++, the `std::stringstream` is used to read words separated by spaces with the `>>` operator. Java and JavaScript use a regex to match any whitespace, and Python has a built-in `split()` method that splits on any whitespace by default.


# Non-overlapping Intervals

- slug: non-overlapping-intervals
- difficulty: Medium

Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.

**Example 1:**

**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping.

**Example 2:**

**Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\]
**Output:** 2
**Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping.

**Example 3:**

**Input:** intervals = \[\[1,2\],\[2,3\]\]
**Output:** 0
**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping.

**Constraints:**

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

## A solution in Java

```java
import java.util.Arrays;

public int eraseOverlapIntervals(int[][] intervals) {
    if (intervals.length == 0) return 0;

    Arrays.sort(intervals, (a, b) -> a[1] - b[1]);

    int count = 0;
    int prev_end = intervals[0][1];

    for (int i = 1; i < intervals.length; i++) {
        if (intervals[i][0] < prev_end) {
            count++;
        } else {
            prev_end = intervals[i][1];
        }
    }

    return count;
}
```
The algorithm starts by sorting the input intervals by their ending times. This is because we want to select a minimum number of intervals with the smallest end time to make the rest of the intervals non-overlapping. Then, the algorithm initializes the count of overlapping intervals to 0 and the previous ending value with the first interval's end time.

We loop through the intervals starting from the second interval. In each iteration, if the current interval's start time is less than the previous end time, it means the current interval overlaps with the previous one. We increment the count in this case. If there's no overlap, we update the previous end time with the current interval's end time. After looping through all the intervals, the count is returned as the minimum number of intervals to remove for non-overlapping intervals.

## A solution in C++

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

bool compare(const std::vector<int>& a, const std::vector<int>& b) {
    return a[1] < b[1];
}

int eraseOverlapIntervals(std::vector<std::vector<int>>& intervals) {
    if (intervals.empty()) return 0;

    std::sort(intervals.begin(), intervals.end(), compare);

    int count = 0;
    int prev_end = intervals[0][1];

    for (size_t i = 1; i < intervals.size(); i++) {
        if (intervals[i][0] < prev_end) {
            count++;
        } else {
            prev_end = intervals[i][1];
        }
    }

    return count;
}
```
The algorithm starts by sorting the input intervals by their ending times. This is because we want to select a minimum number of intervals with the smallest end time to make the rest of the intervals non-overlapping. Then, the algorithm initializes the count of overlapping intervals to 0 and the previous ending value with the first interval's end time.

We loop through the intervals starting from the second interval. In each iteration, if the current interval's start time is less than the previous end time, it means the current interval overlaps with the previous one. We increment the count in this case. If there's no overlap, we update the previous end time with the current interval's end time. After looping through all the intervals, the count is returned as the minimum number of intervals to remove for non-overlapping intervals.

## A solution in Python

```python
def eraseOverlapIntervals(intervals):
    if not intervals:
        return 0

    intervals.sort(key=lambda x: x[1])

    count = 0
    prev_end = intervals[0][1]

    for i in range(1, len(intervals)):
        if intervals[i][0] < prev_end:
            count += 1
        else:
            prev_end = intervals[i][1]

    return count
```
The algorithm starts by sorting the input intervals by their ending times. This is because we want to select a minimum number of intervals with the smallest end time to make the rest of the intervals non-overlapping. Then, the algorithm initializes the count of overlapping intervals to 0 and the previous ending value with the first interval's end time.

We loop through the intervals starting from the second interval. In each iteration, if the current interval's start time is less than the previous end time, it means the current interval overlaps with the previous one. We increment the count in this case. If there's no overlap, we update the previous end time with the current interval's end time. After looping through all the intervals, the count is returned as the minimum number of intervals to remove for non-overlapping intervals.

## A solution in Javascript

```javascript
function eraseOverlapIntervals(intervals) {
    if (intervals.length === 0) return 0;

    intervals.sort((a, b) => a[1] - b[1]);

    let count = 0;
    let prev_end = intervals[0][1];

    for (let i = 1; i < intervals.length; i++) {
        if (intervals[i][0] < prev_end) {
            count++;
        } else {
            prev_end = intervals[i][1];
        }
    }

    return count;
}
```
The algorithm starts by sorting the input intervals by their ending times. This is because we want to select a minimum number of intervals with the smallest end time to make the rest of the intervals non-overlapping. Then, the algorithm initializes the count of overlapping intervals to 0 and the previous ending value with the first interval's end time.

We loop through the intervals starting from the second interval. In each iteration, if the current interval's start time is less than the previous end time, it means the current interval overlaps with the previous one. We increment the count in this case. If there's no overlap, we update the previous end time with the current interval's end time. After looping through all the intervals, the count is returned as the minimum number of intervals to remove for non-overlapping intervals.


# Find Right Interval

- slug: find-right-interval
- difficulty: Medium

You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.

The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.

Return _an array of **right interval** indices for each interval `i`_. If no **right interval** exists for interval `i`, then put `-1` at index `i`.

**Example 1:**

**Input:** intervals = \[\[1,2\]\]
**Output:** \[-1\]
**Explanation:** There is only one interval in the collection, so it outputs -1.

**Example 2:**

**Input:** intervals = \[\[3,4\],\[2,3\],\[1,2\]\]
**Output:** \[-1,0,1\]
**Explanation:** There is no right interval for \[3,4\].
The right interval for \[2,3\] is \[3,4\] since start0 = 3 is the smallest start that is >= end1 = 3.
The right interval for \[1,2\] is \[2,3\] since start1 = 2 is the smallest start that is >= end2 = 2.

**Example 3:**

**Input:** intervals = \[\[1,4\],\[2,3\],\[3,4\]\]
**Output:** \[-1,2,-1\]
**Explanation:** There is no right interval for \[1,4\] and \[3,4\].
The right interval for \[2,3\] is \[3,4\] since start2 = 3 is the smallest start that is >= end1 = 3.

**Constraints:**

*   `1 <= intervals.length <= 2 * 104`
*   `intervals[i].length == 2`
*   `-106 <= starti <= endi <= 106`
*   The start point of each interval is **unique**.

## A solution in Java

```java
import java.util.TreeMap;
import java.util.Map;

public int[] findRightInterval(int[][] intervals) {
    int[] res = new int[intervals.length];
    TreeMap<Integer, Integer> starts = new TreeMap<>();

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

    for(int i = 0; i < intervals.length; i++) {
        Map.Entry<Integer, Integer> right = starts.ceilingEntry(intervals[i][1]);
        res[i] = right == null ? -1 : right.getValue();
    }

    return res;
}
```
The algorithm first creates a map, `starts`, to store the start times of each interval with their corresponding index in the original array. Then, we iterate through each interval, finding the minimum interval start time greater than or equal to the interval's end time using either lower_bound (C++) or ceilingEntry (Java) or filter (Python, JavaScript). If we find a valid start time, we get the corresponding index from the `starts` map and store it in the result array, otherwise we store -1.

## A solution in C++

```cpp
#include <vector>
#include <map>

std::vector<int> findRightInterval(std::vector<std::vector<int>>& intervals) {
    std::vector<int> res(intervals.size(), -1);
    std::map<int, int> starts;
    for(int i = 0; i < intervals.size(); ++i) {
        starts[intervals[i][0]] = i;
    }

    for(int i = 0; i < intervals.size(); ++i) {
        auto it = starts.lower_bound(intervals[i][1]);
        if(it != starts.end()) {
            res[i] = it->second;
        }
    }

    return res;
}
```
The algorithm first creates a map, `starts`, to store the start times of each interval with their corresponding index in the original array. Then, we iterate through each interval, finding the minimum interval start time greater than or equal to the interval's end time using either lower_bound (C++) or ceilingEntry (Java) or filter (Python, JavaScript). If we find a valid start time, we get the corresponding index from the `starts` map and store it in the result array, otherwise we store -1.

## A solution in Python

```python
def findRightInterval(intervals):
    starts = {interval[0]: index for index, interval in enumerate(intervals)}
    res = []

    for interval in intervals:
        right = min(filter(lambda x: x >= interval[1], starts.keys()), default=-1)
        res.append(starts[right] if right != -1 else -1)

    return res
```
The algorithm first creates a map, `starts`, to store the start times of each interval with their corresponding index in the original array. Then, we iterate through each interval, finding the minimum interval start time greater than or equal to the interval's end time using either lower_bound (C++) or ceilingEntry (Java) or filter (Python, JavaScript). If we find a valid start time, we get the corresponding index from the `starts` map and store it in the result array, otherwise we store -1.

## A solution in Javascript

```javascript
function findRightInterval(intervals) {
    const starts = new Map();
    const res = [];

    intervals.forEach((interval, index) => {
        starts.set(interval[0], index);
    });

    for (const interval of intervals) {
        const rightKeys = [...starts.keys()].filter(x => x >= interval[1]);
        const right = Math.min(...rightKeys);
        res.push(right === Infinity ? -1 : starts.get(right));
    }

    return res;
}
```
The algorithm first creates a map, `starts`, to store the start times of each interval with their corresponding index in the original array. Then, we iterate through each interval, finding the minimum interval start time greater than or equal to the interval's end time using either lower_bound (C++) or ceilingEntry (Java) or filter (Python, JavaScript). If we find a valid start time, we get the corresponding index from the `starts` map and store it in the result array, otherwise we store -1.


# Path Sum III

- slug: path-sum-iii
- difficulty: Medium

Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

**Example 1:**

**Input:** root = \[10,5,-3,3,2,null,11,3,-2,null,1\], targetSum = 8
**Output:** 3
**Explanation:** The paths that sum to 8 are shown.

**Example 2:**

**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22
**Output:** 3

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 1000]`.
*   `-109 <= Node.val <= 109`
*   `-1000 <= targetSum <= 1000`

## A solution in Java

```java
public int pathSumHelper(TreeNode node, int targetSum, int currentSum) {
    if (node == null) {
        return 0;
    }

    currentSum += node.val;
    int totalPaths = currentSum == targetSum ? 1 : 0;
    totalPaths += pathSumHelper(node.left, targetSum, currentSum);
    totalPaths += pathSumHelper(node.right, targetSum, currentSum);
    return totalPaths;
}

public int pathSum(TreeNode root, int targetSum) {
    if (root == null) {
        return 0;
    }

    return pathSumHelper(root, targetSum, 0) + pathSum(root.left, targetSum) + pathSum(root.right, targetSum);
}
```
1. Create a recursive helper function `pathSumHelper` which takes the current node, `targetSum`, and the `currentSum` on the path.
2. If the current node is null, return 0 as the base case.
3. Add the value of the current node to `currentSum`.
4. Check if the `currentSum` is equal to `targetSum`. If yes, update the number of total paths by 1.
5. Recursively call the `pathSumHelper` function for the left and right child of the current node, and update the total paths accordingly.
6. Return the total paths.
7. The main function `pathSum` just calls the helper function for the root node, the left subtree and the right subtree and sums up the results.

## A solution in C++

```cpp
int pathSumHelper(TreeNode* node, int targetSum, int currentSum) {
    if (node == nullptr) {
        return 0;
    }

    currentSum += node->val;
    int totalPaths = currentSum == targetSum;
    totalPaths += pathSumHelper(node->left, targetSum, currentSum);
    totalPaths += pathSumHelper(node->right, targetSum, currentSum);
    return totalPaths;
}

int pathSum(TreeNode* root, int targetSum) {
    if (root == nullptr) {
        return 0;
    }

    return pathSumHelper(root, targetSum, 0) + pathSum(root->left, targetSum) + pathSum(root->right, targetSum);
}
```
1. Create a recursive helper function `pathSumHelper` which takes the current node, `targetSum`, and the `currentSum` on the path.
2. If the current node is null, return 0 as the base case.
3. Add the value of the current node to `currentSum`.
4. Check if the `currentSum` is equal to `targetSum`. If yes, update the number of total paths by 1.
5. Recursively call the `pathSumHelper` function for the left and right child of the current node, and update the total paths accordingly.
6. Return the total paths.
7. The main function `pathSum` just calls the helper function for the root node, the left subtree and the right subtree and sums up the results.

## A solution in Python

```python
def path_sum_helper(node, target_sum, current_sum):
    if node is None:
        return 0

    current_sum += node.val
    total_paths = 1 if current_sum == target_sum else 0
    total_paths += path_sum_helper(node.left, target_sum, current_sum)
    total_paths += path_sum_helper(node.right, target_sum, current_sum)
    return total_paths

def path_sum(root, target_sum):
    if root is None:
        return 0

    return path_sum_helper(root, target_sum, 0) + path_sum(root.left, target_sum) + path_sum(root.right, target_sum)
```
1. Create a recursive helper function `pathSumHelper` which takes the current node, `targetSum`, and the `currentSum` on the path.
2. If the current node is null, return 0 as the base case.
3. Add the value of the current node to `currentSum`.
4. Check if the `currentSum` is equal to `targetSum`. If yes, update the number of total paths by 1.
5. Recursively call the `pathSumHelper` function for the left and right child of the current node, and update the total paths accordingly.
6. Return the total paths.
7. The main function `pathSum` just calls the helper function for the root node, the left subtree and the right subtree and sums up the results.

## A solution in Javascript

```javascript
function pathSumHelper(node, targetSum, currentSum) {
    if (node === null) {
        return 0;
    }

    currentSum += node.val;
    let totalPaths = (currentSum === targetSum) ? 1 : 0;
    totalPaths += pathSumHelper(node.left, targetSum, currentSum);
    totalPaths += pathSumHelper(node.right, targetSum, currentSum);
    return totalPaths;
}

function pathSum(root, targetSum) {
    if (root === null) {
        return 0;
    }

    return pathSumHelper(root, targetSum, 0) + pathSum(root.left, targetSum) + pathSum(root.right, targetSum);
}
```
1. Create a recursive helper function `pathSumHelper` which takes the current node, `targetSum`, and the `currentSum` on the path.
2. If the current node is null, return 0 as the base case.
3. Add the value of the current node to `currentSum`.
4. Check if the `currentSum` is equal to `targetSum`. If yes, update the number of total paths by 1.
5. Recursively call the `pathSumHelper` function for the left and right child of the current node, and update the total paths accordingly.
6. Return the total paths.
7. The main function `pathSum` just calls the helper function for the root node, the left subtree and the right subtree and sums up the results.


# Find All Anagrams in a String

- slug: find-all-anagrams-in-a-string
- difficulty: Medium

Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.

An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

**Example 1:**

**Input:** s =  "cbaebabacd ", p =  "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is  "cba ", which is an anagram of  "abc ".
The substring with start index = 6 is  "bac ", which is an anagram of  "abc ".

**Example 2:**

**Input:** s =  "abab ", p =  "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is  "ab ", which is an anagram of  "ab ".
The substring with start index = 1 is  "ba ", which is an anagram of  "ab ".
The substring with start index = 2 is  "ab ", which is an anagram of  "ab ".

**Constraints:**

*   `1 <= s.length, p.length <= 3 * 104`
*   `s` and `p` consist of lowercase English letters.

## A solution in Java

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

public List<Integer> findAnagrams(String s, String p) {
    List<Integer> result = new ArrayList<>();
    if (s.length() < p.length()) return result;

    int[] s_count = new int[26];
    int[] p_count = new int[26];
    for (char c : p.toCharArray()) p_count[c - 'a']++;

    for (int i = 0; i < s.length(); i++) {
        s_count[s.charAt(i) - 'a']++;
        if (i >= p.length()) s_count[s.charAt(i - p.length()) - 'a']--;
        if (java.util.Arrays.equals(s_count, p_count)) result.add(i - p.length() + 1);
    }

    return result;
}
```
1. Create an empty result list.
2. If the given string `s` is shorter than the pattern string `p`, return the empty result list as there cannot be any anagram of `p` in `s`.
3. Create 2 arrays, `s_count` and `p_count`, with a fixed size of 26, to keep count of characters in the sliding window of `s` and characters in `p`.
4. Fill `p_count` using the characters count in `p`.
5. Iterate over the string `s`, updating the count of the characters in `s_count`.
6. If the iteration index `i` is greater than or equal to the length of `p`, reduce the count of the character that is now out of the sliding window.
7. If the `s_count` and `p_count` have the same counts, it means that a valid anagram has been found. Add the starting index of the anagram in the result list.
8. Return the result list.

## A solution in C++

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

std::vector<int> findAnagrams(std::string s, std::string p) {
    std::vector<int> result;
    if (s.size() < p.size()) return result;

    std::vector<int> s_count(26, 0), p_count(26, 0);
    for (char c : p) p_count[c - 'a']++;

    for (int i = 0; i < s.size(); i++) {
        s_count[s[i] - 'a']++;
        if (i >= p.size()) s_count[s[i - p.size()] - 'a']--;
        if (s_count == p_count) result.push_back(i - p.size() + 1);
    }

    return result;
}
```
1. Create an empty result list.
2. If the given string `s` is shorter than the pattern string `p`, return the empty result list as there cannot be any anagram of `p` in `s`.
3. Create 2 arrays, `s_count` and `p_count`, with a fixed size of 26, to keep count of characters in the sliding window of `s` and characters in `p`.
4. Fill `p_count` using the characters count in `p`.
5. Iterate over the string `s`, updating the count of the characters in `s_count`.
6. If the iteration index `i` is greater than or equal to the length of `p`, reduce the count of the character that is now out of the sliding window.
7. If the `s_count` and `p_count` have the same counts, it means that a valid anagram has been found. Add the starting index of the anagram in the result list.
8. Return the result list.

## A solution in Python

```python
def find_anagrams(s, p):
    if len(s) < len(p):
        return []

    s_count = [0] * 26
    p_count = [0] * 26
    for c in p:
        p_count[ord(c) - ord('a')] += 1

    result = []
    for i in range(len(s)):
        s_count[ord(s[i]) - ord('a')] += 1
        if i >= len(p):
            s_count[ord(s[i - len(p)]) - ord('a')] -= 1
        if s_count == p_count:
            result.append(i - len(p) + 1)

    return result
```
1. Create an empty result list.
2. If the given string `s` is shorter than the pattern string `p`, return the empty result list as there cannot be any anagram of `p` in `s`.
3. Create 2 arrays, `s_count` and `p_count`, with a fixed size of 26, to keep count of characters in the sliding window of `s` and characters in `p`.
4. Fill `p_count` using the characters count in `p`.
5. Iterate over the string `s`, updating the count of the characters in `s_count`.
6. If the iteration index `i` is greater than or equal to the length of `p`, reduce the count of the character that is now out of the sliding window.
7. If the `s_count` and `p_count` have the same counts, it means that a valid anagram has been found. Add the starting index of the anagram in the result list.
8. Return the result list.

## A solution in Javascript

```javascript
function findAnagrams(s, p) {
    if (s.length < p.length) return [];

    const s_count = new Array(26).fill(0);
    const p_count = new Array(26).fill(0);
    for (const c of p) p_count[c.charCodeAt(0) - 'a'.charCodeAt(0)]++;

    const result = [];
    for (let i = 0; i < s.length; i++) {
        s_count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
        if (i >= p.length) s_count[s.charCodeAt(i - p.length) - 'a'.charCodeAt(0)]--;
        if (s_count.join(',') === p_count.join(',')) result.push(i - p.length + 1);
    }

    return result;
}
```
1. Create an empty result list.
2. If the given string `s` is shorter than the pattern string `p`, return the empty result list as there cannot be any anagram of `p` in `s`.
3. Create 2 arrays, `s_count` and `p_count`, with a fixed size of 26, to keep count of characters in the sliding window of `s` and characters in `p`.
4. Fill `p_count` using the characters count in `p`.
5. Iterate over the string `s`, updating the count of the characters in `s_count`.
6. If the iteration index `i` is greater than or equal to the length of `p`, reduce the count of the character that is now out of the sliding window.
7. If the `s_count` and `p_count` have the same counts, it means that a valid anagram has been found. Add the starting index of the anagram in the result list.
8. Return the result list.


# Ternary Expression Parser

- slug: ternary-expression-parser
- difficulty: Medium

Given a string `expression` representing arbitrarily nested ternary expressions, evaluate the expression, and return _the result of it_.

You can always assume that the given expression is valid and only contains digits, `'?'`, `':'`, `'T'`, and `'F'` where `'T'` is true and `'F'` is false. All the numbers in the expression are **one-digit** numbers (i.e., in the range `[0, 9]`).

The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, `'T'` or `'F'`.

**Example 1:**

**Input:** expression =  "T?2:3 "
**Output:**  "2 "
**Explanation:** If true, then result is 2; otherwise result is 3.

**Example 2:**

**Input:** expression =  "F?1:T?4:5 "
**Output:**  "4 "
**Explanation:** The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
 "(F ? 1 : (T ? 4 : 5)) " -->  "(F ? 1 : 4) " -->  "4 "
or  "(F ? 1 : (T ? 4 : 5)) " -->  "(T ? 4 : 5) " -->  "4 "

**Example 3:**

**Input:** expression =  "T?T?F:5:3 "
**Output:**  "F "
**Explanation:** The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
 "(T ? (T ? F : 5) : 3) " -->  "(T ? F : 3) " -->  "F "
 "(T ? (T ? F : 5) : 3) " -->  "(T ? F : 5) " -->  "F "

**Constraints:**

*   `5 <= expression.length <= 104`
*   `expression` consists of digits, `'T'`, `'F'`, `'?'`, and `':'`.
*   It is **guaranteed** that `expression` is a valid ternary expression and that each number is a **one-digit number**.

## A solution in Java

```java
import java.util.Stack;

public String parseTernary(String expression) {
    Stack<Character> stk = new Stack<>();
    for (int i = expression.length() - 1; i >= 0; --i) {
        char c = expression.charAt(i);
        if (!stk.isEmpty() && stk.peek() == '?') {
            stk.pop(); // Pop '?'
            char first = stk.pop();
            stk.pop(); // Pop ':'
            char second = stk.pop();
            stk.push(c == 'T' ? first : second);
        } else {
            stk.push(c);
        }
    }
    return String.valueOf(stk.peek());
}
```
The algorithm uses a stack to process the ternary expression. Iterate through the expression from the right to left, and push each character on the stack. If the stack is not empty and the top of the stack is a '?', then pop the '?' from the stack and store the next two elements (first and second). Pop the ':' from the stack and push either 'first' or 'second' on the stack based on whether the current character is 'T' or 'F'. The top element of the stack after iteration has the result of evaluating the ternary expression.

## A solution in C++

```cpp
#include <string>
#include <stack>

std::string parseTernary(std::string expression) {
    std::stack<char> stk;
    for (int i = expression.size() - 1; i >= 0; --i) {
        char c = expression[i];
        if (!stk.empty() && stk.top() == '?') {
            stk.pop(); // Pop '?'
            char first = stk.top();
            stk.pop();
            stk.pop(); // Pop ':'
            char second = stk.top();
            stk.pop();
            stk.push(c == 'T' ? first : second);
        } else {
            stk.push(c);
        }
    }
    return std::string(1, stk.top());
}
```
The algorithm uses a stack to process the ternary expression. Iterate through the expression from the right to left, and push each character on the stack. If the stack is not empty and the top of the stack is a '?', then pop the '?' from the stack and store the next two elements (first and second). Pop the ':' from the stack and push either 'first' or 'second' on the stack based on whether the current character is 'T' or 'F'. The top element of the stack after iteration has the result of evaluating the ternary expression.

## A solution in Python

```python
def parseTernary(expression: str) -> str:
    stack = []
    for c in reversed(expression):
        if stack and stack[-1] == '?':
            stack.pop()  # Pop '?'
            first = stack.pop()
            stack.pop()  # Pop ':'
            second = stack.pop()
            stack.append(first if c == 'T' else second)
        else:
            stack.append(c)
    return stack[-1]
```
The algorithm uses a stack to process the ternary expression. Iterate through the expression from the right to left, and push each character on the stack. If the stack is not empty and the top of the stack is a '?', then pop the '?' from the stack and store the next two elements (first and second). Pop the ':' from the stack and push either 'first' or 'second' on the stack based on whether the current character is 'T' or 'F'. The top element of the stack after iteration has the result of evaluating the ternary expression.

## A solution in Javascript

```javascript
function parseTernary(expression) {
    const stack = [];
    for (let i = expression.length - 1; i >= 0; i--) {
        const c = expression[i];
        if (stack.length && stack[stack.length - 1] === '?') {
            stack.pop(); // Pop '?'
            const first = stack.pop();
            stack.pop(); // Pop ':'
            const second = stack.pop();
            stack.push(c === 'T' ? first : second);
        } else {
            stack.push(c);
        }
    }
    return stack[stack.length - 1];
}
```
The algorithm uses a stack to process the ternary expression. Iterate through the expression from the right to left, and push each character on the stack. If the stack is not empty and the top of the stack is a '?', then pop the '?' from the stack and store the next two elements (first and second). Pop the ':' from the stack and push either 'first' or 'second' on the stack based on whether the current character is 'T' or 'F'. The top element of the stack after iteration has the result of evaluating the ternary expression.


# K-th Smallest in Lexicographical Order

- slug: k-th-smallest-in-lexicographical-order
- difficulty: Hard

Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.

**Example 1:**

**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.

**Example 2:**

**Input:** n = 1, k = 1
**Output:** 1

**Constraints:**

*   `1 <= k <= n <= 109`

## A solution in Java

```java
import java.util.*;
public class Solution {
    public int findKthNumber(int n, int k) {
        List<Integer> nums = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            nums.add(i);
        }
        nums.sort((a, b) -> String.valueOf(a).compareTo(String.valueOf(b)));
        return nums.get(k - 1);
    }
}
```
First, we initialize a list or vector containing all the integers from 1 to n.

Then, we sort this list lexicographically. For C++ and Java, we use a lambda function to compare the string representation of the numbers. In Python, we use a lambda function inside the sort function, and in JavaScript, we use the `localeCompare()` method to sort the integers lexicographically.

Finally, we return the Kth element in the sorted list by accessing the element at index `k - 1`.

## A solution in C++

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

int findKthNumber(int n, int k) {
    vector<int> nums;
    for (int i = 1; i <= n; ++i) {
        nums.push_back(i);
    }
    sort(nums.begin(), nums.end(), [](int a, int b) {
        return to_string(a) < to_string(b);
    });
    return nums[k - 1];
}
```
First, we initialize a list or vector containing all the integers from 1 to n.

Then, we sort this list lexicographically. For C++ and Java, we use a lambda function to compare the string representation of the numbers. In Python, we use a lambda function inside the sort function, and in JavaScript, we use the `localeCompare()` method to sort the integers lexicographically.

Finally, we return the Kth element in the sorted list by accessing the element at index `k - 1`.

## A solution in Python

```python
def find_kth_number(n, k):
    nums = [i for i in range(1, n + 1)]
    nums.sort(key=lambda x: str(x))
    return nums[k - 1]
```
First, we initialize a list or vector containing all the integers from 1 to n.

Then, we sort this list lexicographically. For C++ and Java, we use a lambda function to compare the string representation of the numbers. In Python, we use a lambda function inside the sort function, and in JavaScript, we use the `localeCompare()` method to sort the integers lexicographically.

Finally, we return the Kth element in the sorted list by accessing the element at index `k - 1`.

## A solution in Javascript

```javascript
function findKthNumber(n, k) {
    const nums = [];
    for (let i = 1; i <= n; i++) {
        nums.push(i);
    }
    nums.sort((a, b) => String(a).localeCompare(String(b)));
    return nums[k - 1];
}
```
First, we initialize a list or vector containing all the integers from 1 to n.

Then, we sort this list lexicographically. For C++ and Java, we use a lambda function to compare the string representation of the numbers. In Python, we use a lambda function inside the sort function, and in JavaScript, we use the `localeCompare()` method to sort the integers lexicographically.

Finally, we return the Kth element in the sorted list by accessing the element at index `k - 1`.


# Arranging Coins

- slug: arranging-coins
- difficulty: Easy

You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.

Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.

**Example 1:**

**Input:** n = 5
**Output:** 2
**Explanation:** Because the 3rd row is incomplete, we return 2.

**Example 2:**

**Input:** n = 8
**Output:** 3
**Explanation:** Because the 4th row is incomplete, we return 3.

**Constraints:**

*   `1 <= n <= 231 - 1`

## A solution in Java

```java
public int arrangeCoins(int n) {
    int k = 0;
    while (n > k) {
        k++;
        n -= k;
    }
    return k;
}
```
The algorithm initializes a variable k, which represents the current row number, to 0. Then it enters a loop where it checks if n is greater than k. If so, it increments k by 1 and subtracts k from n. This process continues until n is no longer greater than k. Finally, the value of k is returned, representing the number of complete rows of the staircase. This approach has a time complexity of O(sqrt(n)) since the number of iterations increases linearly with the size of the staircase.

## A solution in C++

```cpp
int arrangeCoins(int n) {
    int k = 0;
    while (n > k) {
        k++;
        n -= k;
    }
    return k;
}
```
The algorithm initializes a variable k, which represents the current row number, to 0. Then it enters a loop where it checks if n is greater than k. If so, it increments k by 1 and subtracts k from n. This process continues until n is no longer greater than k. Finally, the value of k is returned, representing the number of complete rows of the staircase. This approach has a time complexity of O(sqrt(n)) since the number of iterations increases linearly with the size of the staircase.

## A solution in Python

```python
def arrange_coins(n: int) -> int:
    k = 0
    while n > k:
        k += 1
        n -= k
    return k
```
The algorithm initializes a variable k, which represents the current row number, to 0. Then it enters a loop where it checks if n is greater than k. If so, it increments k by 1 and subtracts k from n. This process continues until n is no longer greater than k. Finally, the value of k is returned, representing the number of complete rows of the staircase. This approach has a time complexity of O(sqrt(n)) since the number of iterations increases linearly with the size of the staircase.

## A solution in Javascript

```javascript
function arrangeCoins(n) {
    let k = 0;
    while (n > k) {
        k++;
        n -= k;
    }
    return k;
}
```
The algorithm initializes a variable k, which represents the current row number, to 0. Then it enters a loop where it checks if n is greater than k. If so, it increments k by 1 and subtracts k from n. This process continues until n is no longer greater than k. Finally, the value of k is returned, representing the number of complete rows of the staircase. This approach has a time complexity of O(sqrt(n)) since the number of iterations increases linearly with the size of the staircase.


# Find All Duplicates in an Array

- slug: find-all-duplicates-in-an-array
- difficulty: Medium

Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.

You must write an algorithm that runs in `O(n)` time and uses only constant extra space.

**Example 1:**

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

**Example 2:**

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

**Example 3:**

**Input:** nums = \[1\]
**Output:** \[\]

**Constraints:**

*   `n == nums.length`
*   `1 <= n <= 105`
*   `1 <= nums[i] <= n`
*   Each element in `nums` appears **once** or **twice**.

## A solution in Java

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

public List<Integer> findDuplicates(int[] nums) {
    List<Integer> duplicates = new ArrayList<>();
    for (int i = 0; i < nums.length; i++) {
        int index = Math.abs(nums[i]) - 1;
        if (nums[index] < 0) {
            duplicates.add(Math.abs(nums[i]));
        } else {
            nums[index] *= -1;
        }
    }
    return duplicates;
}
```
The algorithm iterates through the input array, using the array values as indices. For each index, we make the corresponding value in the array negative. If we encounter a negative value during the process, that means this index was seen before (i.e., the value was duplicated), so we add the absolute value of the duplicated number to the result.

The algorithm runs in O(n) time complexity, as there is only one iteration through the input array. It also uses constant extra space, because the input array is utilized for marking, and only the result array is created separately.

## A solution in C++

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

std::vector<int> findDuplicates(std::vector<int>& nums) {
    std::vector<int> duplicates;
    for (int i = 0; i < nums.size(); i++) {
        int index = abs(nums[i]) - 1;
        if (nums[index] < 0) {
            duplicates.push_back(abs(nums[i]));
        } else {
            nums[index] *= -1;
        }
    }
    return duplicates;
}
```
The algorithm iterates through the input array, using the array values as indices. For each index, we make the corresponding value in the array negative. If we encounter a negative value during the process, that means this index was seen before (i.e., the value was duplicated), so we add the absolute value of the duplicated number to the result.

The algorithm runs in O(n) time complexity, as there is only one iteration through the input array. It also uses constant extra space, because the input array is utilized for marking, and only the result array is created separately.

## A solution in Python

```python
def find_duplicates(nums):
    duplicates = []
    for i in range(len(nums)):
        index = abs(nums[i]) - 1
        if nums[index] < 0:
            duplicates.append(abs(nums[i]))
        else:
            nums[index] *= -1
    return duplicates
```
The algorithm iterates through the input array, using the array values as indices. For each index, we make the corresponding value in the array negative. If we encounter a negative value during the process, that means this index was seen before (i.e., the value was duplicated), so we add the absolute value of the duplicated number to the result.

The algorithm runs in O(n) time complexity, as there is only one iteration through the input array. It also uses constant extra space, because the input array is utilized for marking, and only the result array is created separately.

## A solution in Javascript

```javascript
function findDuplicates(nums) {
    let duplicates = [];
    for (let i = 0; i < nums.length; i++) {
        let index = Math.abs(nums[i]) - 1;
        if (nums[index] < 0) {
            duplicates.push(Math.abs(nums[i]));
        } else {
            nums[index] *= -1;
        }
    }
    return duplicates;
}
```
The algorithm iterates through the input array, using the array values as indices. For each index, we make the corresponding value in the array negative. If we encounter a negative value during the process, that means this index was seen before (i.e., the value was duplicated), so we add the absolute value of the duplicated number to the result.

The algorithm runs in O(n) time complexity, as there is only one iteration through the input array. It also uses constant extra space, because the input array is utilized for marking, and only the result array is created separately.


# String Compression

- slug: string-compression
- difficulty: Medium

Given an array of characters `chars`, compress it using the following algorithm:

Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:

*   If the group's length is `1`, append the character to `s`.
*   Otherwise, append the character followed by the group's length.

The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`.

After you are done **modifying the input array,** return _the new length of the array_.

You must write an algorithm that uses only constant extra space.

**Example 1:**

**Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\]
**Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\]
**Explanation:** The groups are  "aa ",  "bb ", and  "ccc ". This compresses to  "a2b2c3 ".

**Example 2:**

**Input:** chars = \[ "a "\]
**Output:** Return 1, and the first character of the input array should be: \[ "a "\]
**Explanation:** The only group is  "a ", which remains uncompressed since it's a single character.

**Example 3:**

**Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\]
**Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\].
**Explanation:** The groups are  "a " and  "bbbbbbbbbbbb ". This compresses to  "ab12 ".

**Constraints:**

*   `1 <= chars.length <= 2000`
*   `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.

## A solution in Java

```java
public int compress(char[] chars) {
    int index = 0, count;
    for(int i = 0; i < chars.length; i += count) {
        count = 1;
        while(i + count < chars.length && chars[i] == chars[i + count]) {
            count++;
        }
        chars[index++] = chars[i];
        if(count > 1) {
            for(char c : Integer.toString(count).toCharArray()) {
                chars[index++] = c;
            }
        }
    }
    return index;
}
```
This algorithm iterates through the input array `chars`, for each character, it counts the number of consecutive occurrences (using `count` variable) of that character. Then, the algorithm replaces the current character(s) with the compressed form (the character itself, followed by the count if it is greater than 1). `index` keeps track of the position in the modified input array `chars`.

At the end of each iteration, the value of `i` is incremented by `count` to move to the next unique character in the array. Finally, the algorithm returns `index`, which is the new length of the array.

This implementation uses only constant extra space by modifying the input array itself and using a couple of simple variables.

## A solution in C++

```cpp
int compress(vector<char>& chars) {
    int index = 0, count;
    for(int i = 0; i < chars.size(); i += count) {
        count = 1;
        while(i + count < chars.size() && chars[i] == chars[i + count]) {
            count++;
        }
        chars[index++] = chars[i];
        if(count > 1) {
            for(char c : to_string(count)) {
                chars[index++] = c;
            }
        }
    }
    return index;
}
```
This algorithm iterates through the input array `chars`, for each character, it counts the number of consecutive occurrences (using `count` variable) of that character. Then, the algorithm replaces the current character(s) with the compressed form (the character itself, followed by the count if it is greater than 1). `index` keeps track of the position in the modified input array `chars`.

At the end of each iteration, the value of `i` is incremented by `count` to move to the next unique character in the array. Finally, the algorithm returns `index`, which is the new length of the array.

This implementation uses only constant extra space by modifying the input array itself and using a couple of simple variables.

## A solution in Python

```python
def compress(chars):
    index, i = 0, 0

    while i < len(chars):
        count = 1
        while i + count < len(chars) and chars[i] == chars[i + count]:
            count += 1

        chars[index] = chars[i]
        index += 1

        if count > 1:
            count_str = str(count)
            for c in count_str:
                chars[index] = c
                index += 1

        i += count

    return index
```
This algorithm iterates through the input array `chars`, for each character, it counts the number of consecutive occurrences (using `count` variable) of that character. Then, the algorithm replaces the current character(s) with the compressed form (the character itself, followed by the count if it is greater than 1). `index` keeps track of the position in the modified input array `chars`.

At the end of each iteration, the value of `i` is incremented by `count` to move to the next unique character in the array. Finally, the algorithm returns `index`, which is the new length of the array.

This implementation uses only constant extra space by modifying the input array itself and using a couple of simple variables.

## A solution in Javascript

```javascript
function compress(chars) {
    let index = 0, count;
    for(let i = 0; i < chars.length; i += count) {
        count = 1;
        while(i + count < chars.length && chars[i] === chars[i + count]) {
            count++;
        }
        chars[index++] = chars[i];
        if(count > 1) {
            for(let c of count.toString()) {
                chars[index++] = c;
            }
        }
    }
    return index;
}
```
This algorithm iterates through the input array `chars`, for each character, it counts the number of consecutive occurrences (using `count` variable) of that character. Then, the algorithm replaces the current character(s) with the compressed form (the character itself, followed by the count if it is greater than 1). `index` keeps track of the position in the modified input array `chars`.

At the end of each iteration, the value of `i` is incremented by `count` to move to the next unique character in the array. Finally, the algorithm returns `index`, which is the new length of the array.

This implementation uses only constant extra space by modifying the input array itself and using a couple of simple variables.


# Sequence Reconstruction

- slug: sequence-reconstruction
- difficulty: Medium

You are given an integer array `nums` of length `n` where `nums` is a permutation of the integers in the range `[1, n]`. You are also given a 2D integer array `sequences` where `sequences[i]` is a subsequence of `nums`.

Check if `nums` is the shortest possible and the only **supersequence**. The shortest **supersequence** is a sequence **with the shortest length** and has all `sequences[i]` as subsequences. There could be multiple valid **supersequences** for the given array `sequences`.

*   For example, for `sequences = [[1,2],[1,3]]`, there are two shortest **supersequences**, `[1,2,3]` and `[1,3,2]`.
*   While for `sequences = [[1,2],[1,3],[1,2,3]]`, the only shortest **supersequence** possible is `[1,2,3]`. `[1,2,3,4]` is a possible supersequence but not the shortest.

Return `true` _if_ `nums` _is the only shortest **supersequence** for_ `sequences`_, or_ `false` _otherwise_.

A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

**Example 1:**

**Input:** nums = \[1,2,3\], sequences = \[\[1,2\],\[1,3\]\]
**Output:** false
**Explanation:** There are two possible supersequences: \[1,2,3\] and \[1,3,2\].
The sequence \[1,2\] is a subsequence of both: \[**1**,**2**,3\] and \[**1**,3,**2**\].
The sequence \[1,3\] is a subsequence of both: \[**1**,2,**3**\] and \[**1**,**3**,2\].
Since nums is not the only shortest supersequence, we return false.

**Example 2:**

**Input:** nums = \[1,2,3\], sequences = \[\[1,2\]\]
**Output:** false
**Explanation:** The shortest possible supersequence is \[1,2\].
The sequence \[1,2\] is a subsequence of it: \[**1**,**2**\].
Since nums is not the shortest supersequence, we return false.

**Example 3:**

**Input:** nums = \[1,2,3\], sequences = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** true
**Explanation:** The shortest possible supersequence is \[1,2,3\].
The sequence \[1,2\] is a subsequence of it: \[**1**,**2**,3\].
The sequence \[1,3\] is a subsequence of it: \[**1**,2,**3**\].
The sequence \[2,3\] is a subsequence of it: \[1,**2**,**3**\].
Since nums is the only shortest supersequence, we return true.

**Constraints:**

*   `n == nums.length`
*   `1 <= n <= 104`
*   `nums` is a permutation of all the integers in the range `[1, n]`.
*   `1 <= sequences.length <= 104`
*   `1 <= sequences[i].length <= 104`
*   `1 <= sum(sequences[i].length) <= 105`
*   `1 <= sequences[i][j] <= n`
*   All the arrays of `sequences` are **unique**.
*   `sequences[i]` is a subsequence of `nums`.

## A solution in Java

```java
public boolean isShortestAndUniqueSupersequence(int[] nums, int[][] sequences) {
    Map<Integer, Integer> pos = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        pos.put(nums[i], i);
    }

    for (int[] seq : sequences) {
        if (pos.get(seq[0]) > pos.get(seq[seq.length - 1])) {
            return false;
        }
    }
    return true;
}
```
We start by creating a hashmap (or dictionary in Python and Map in JavaScript) to store the position of each element in the given `nums` array for efficient lookup. The map is filled with each value of the `nums` array as the key and its index as the value.

We then iterate through each sequence in `sequences` and check if the position of the first element in the sequence is greater than the position of the last element in the same sequence. If so, it means the given sequence is not a valid subsequence of the given `nums`, and we return `false`.

If we passed all sequences in the iteration without returning `false`, it means that the given `nums` array is the shortest possible and the only supersequence of the input sequences. Thus, we return `true`.

## A solution in C++

```cpp
bool isShortestAndUniqueSupersequence(vector<int>& nums, vector<vector<int>>& sequences) {
    unordered_map<int, int> pos;
    for (int i = 0; i < nums.size(); ++i) {
        pos[nums[i]] = i;
    }

    for (const auto& seq : sequences) {
        if (pos[seq[0]] > pos[seq.back()]) {
            return false;
        }
    }
    return true;
}
```
We start by creating a hashmap (or dictionary in Python and Map in JavaScript) to store the position of each element in the given `nums` array for efficient lookup. The map is filled with each value of the `nums` array as the key and its index as the value.

We then iterate through each sequence in `sequences` and check if the position of the first element in the sequence is greater than the position of the last element in the same sequence. If so, it means the given sequence is not a valid subsequence of the given `nums`, and we return `false`.

If we passed all sequences in the iteration without returning `false`, it means that the given `nums` array is the shortest possible and the only supersequence of the input sequences. Thus, we return `true`.

## A solution in Python

```python
def is_shortest_and_unique_supersequence(nums, sequences):
    pos = {val: idx for idx, val in enumerate(nums)}

    for seq in sequences:
        if pos[seq[0]] > pos[seq[-1]]:
            return False
    return True
```
We start by creating a hashmap (or dictionary in Python and Map in JavaScript) to store the position of each element in the given `nums` array for efficient lookup. The map is filled with each value of the `nums` array as the key and its index as the value.

We then iterate through each sequence in `sequences` and check if the position of the first element in the sequence is greater than the position of the last element in the same sequence. If so, it means the given sequence is not a valid subsequence of the given `nums`, and we return `false`.

If we passed all sequences in the iteration without returning `false`, it means that the given `nums` array is the shortest possible and the only supersequence of the input sequences. Thus, we return `true`.

## A solution in Javascript

```javascript
function isShortestAndUniqueSupersequence(nums, sequences) {
    const pos = new Map();
    for (let i = 0; i < nums.length; i++) {
        pos.set(nums[i], i);
    }

    for (const seq of sequences) {
        if (pos.get(seq[0]) > pos.get(seq[seq.length - 1])) {
            return false;
        }
    }
    return true;
}
```
We start by creating a hashmap (or dictionary in Python and Map in JavaScript) to store the position of each element in the given `nums` array for efficient lookup. The map is filled with each value of the `nums` array as the key and its index as the value.

We then iterate through each sequence in `sequences` and check if the position of the first element in the sequence is greater than the position of the last element in the same sequence. If so, it means the given sequence is not a valid subsequence of the given `nums`, and we return `false`.

If we passed all sequences in the iteration without returning `false`, it means that the given `nums` array is the shortest possible and the only supersequence of the input sequences. Thus, we return `true`.


# Add Two Numbers II

- slug: add-two-numbers-ii
- difficulty: Medium

You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

**Example 1:**

**Input:** l1 = \[7,2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,8,0,7\]

**Example 2:**

**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[8,0,7\]

**Example 3:**

**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]

**Constraints:**

*   The number of nodes in each linked list is in the range `[1, 100]`.
*   `0 <= Node.val <= 9`
*   It is guaranteed that the list represents a number that does not have leading zeros.

**Follow up:** Could you solve it without reversing the input lists?

## A solution in Java

```java
public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode result = new ListNode(0);
    ListNode current = result;
    int carry = 0;
    while (l1 != null || l2 != null || carry != 0) {
        int sum = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;
        carry = sum / 10;
        current.next = new ListNode(sum % 10);
        current = current.next;
        if (l1 != null) l1 = l1.next;
        if (l2 != null) l2 = l2.next;
    }
    return result.next;
}
```
The algorithm starts by initializing a dummy result list, setting `current` to point to the dummy node, and initializing a `carry` var to 0. In a `while` loop, we iterate over both input lists and update the `carry` var with the sum divided by 10, representing the digit to be carried to the left (carrying occurs if the sum is >= 10). The sum modulo 10 will be the current digit of the result, and we create a new list node for this digit, updating `current.next` to point to this node. We then update the pointers to the next elements in input lists `l1` and `l2` if they're not null. Once the loop ends, we return the next pointer of the dummy result node.

## A solution in C++

```cpp
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode* result = nullptr;
    ListNode** current = &result;
    int carry = 0;
    while (l1 || l2 || carry) {
        int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
        carry = sum / 10;
        *current = new ListNode(sum % 10);
        current = &((*current)->next);
        if (l1) l1 = l1->next;
        if (l2) l2 = l2->next;
    }
    return result;
}
```
The algorithm starts by initializing a dummy result list, setting `current` to point to the dummy node, and initializing a `carry` var to 0. In a `while` loop, we iterate over both input lists and update the `carry` var with the sum divided by 10, representing the digit to be carried to the left (carrying occurs if the sum is >= 10). The sum modulo 10 will be the current digit of the result, and we create a new list node for this digit, updating `current.next` to point to this node. We then update the pointers to the next elements in input lists `l1` and `l2` if they're not null. Once the loop ends, we return the next pointer of the dummy result node.

## A solution in Python

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

def addTwoNumbers(l1, l2):
    result = ListNode(0)
    current = result
    carry = 0
    while l1 or l2 or carry:
        sum = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
        carry = sum // 10
        current.next = ListNode(sum % 10)
        current = current.next
        if l1: l1 = l1.next
        if l2: l2 = l2.next
    return result.next
```
The algorithm starts by initializing a dummy result list, setting `current` to point to the dummy node, and initializing a `carry` var to 0. In a `while` loop, we iterate over both input lists and update the `carry` var with the sum divided by 10, representing the digit to be carried to the left (carrying occurs if the sum is >= 10). The sum modulo 10 will be the current digit of the result, and we create a new list node for this digit, updating `current.next` to point to this node. We then update the pointers to the next elements in input lists `l1` and `l2` if they're not null. Once the loop ends, we return the next pointer of the dummy result node.

## A solution in Javascript

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

function addTwoNumbers(l1, l2) {
    let result = new ListNode(0);
    let current = result;
    let carry = 0;
    while (l1 !== null || l2 !== null || carry !== 0) {
        let sum = (l1 !== null ? l1.val : 0) + (l2 !== null ? l2.val : 0) + carry;
        carry = Math.floor(sum / 10);
        current.next = new ListNode(sum % 10);
        current = current.next;
        if (l1 !== null) l1 = l1.next;
        if (l2 !== null) l2 = l2.next;
    }
    return result.next;
}
```
The algorithm starts by initializing a dummy result list, setting `current` to point to the dummy node, and initializing a `carry` var to 0. In a `while` loop, we iterate over both input lists and update the `carry` var with the sum divided by 10, representing the digit to be carried to the left (carrying occurs if the sum is >= 10). The sum modulo 10 will be the current digit of the result, and we create a new list node for this digit, updating `current.next` to point to this node. We then update the pointers to the next elements in input lists `l1` and `l2` if they're not null. Once the loop ends, we return the next pointer of the dummy result node.


# Arithmetic Slices II - Subsequence

- slug: arithmetic-slices-ii-subsequence
- difficulty: Hard

Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`.

A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.

*   For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and `[3, -1, -5, -9]` are arithmetic sequences.
*   For example, `[1, 1, 2, 5, 7]` is not an arithmetic sequence.

A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array.

*   For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`.

The test cases are generated so that the answer fits in **32-bit** integer.

**Example 1:**

**Input:** nums = \[2,4,6,8,10\]
**Output:** 7
**Explanation:** All arithmetic subsequence slices are:
\[2,4,6\]
\[4,6,8\]
\[6,8,10\]
\[2,4,6,8\]
\[4,6,8,10\]
\[2,4,6,8,10\]
\[2,6,10\]

**Example 2:**

**Input:** nums = \[7,7,7,7,7\]
**Output:** 16
**Explanation:** Any subsequence of this array is arithmetic.

**Constraints:**

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

## A solution in Java

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

public int numberOfArithmeticSlices(int[] nums) {
    int res = 0;
    int n = nums.length;
    Map<Integer, Integer>[] dp = new HashMap[n];

    for (int i = 0; i < n; ++i) {
        dp[i] = new HashMap<>();
        for (int j = 0; j < i; ++j) {
            long diff = (long)nums[i] - (long)nums[j];
            if (diff <= Integer.MIN_VALUE || diff > Integer.MAX_VALUE) continue;

            int delta = (int)diff;
            dp[i].put(delta, dp[i].getOrDefault(delta, 0) + 1);

            if (dp[j].containsKey(delta)) {
                res += dp[j].get(delta);
                dp[i].put(delta, dp[i].get(delta) + dp[j].get(delta));
            }
        }
    }
    return res;
}
```
To solve this problem, we use dynamic programming. The `dp` data structure is an array of hashmaps or dictionaries. Each index `i` in the array represents an element in the given array `nums`, and the hashmap stored at `dp[i]` will store the count of arithmetic subsequences that end at the element `nums[i]`, with keys representing the differences between elements.

Starting with index `i = 0`, we iterate through the `nums` array. For each element `nums[i]`, we iterate through all previous elements `nums[j]` with `j < i`.

For each pair of elements `(nums[i], nums[j])`, we calculate their difference and store the count of arithmetic subsequences formed by this difference at `dp[i]`.

If an existing subsequence with the same difference is found in `dp[j]`, we should be able to append `nums[i]` to all previously formed subsequences ending at `nums[j]`. Thus, we add the count of subsequences from `dp[j][delta]` to the result, and also update the count in `dp[i][delta]`.

Finally, after iterating through all elements, the `res` variable will hold the count of all the arithmetic subsequences.

## A solution in C++

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

int numberOfArithmeticSlices(std::vector<int>& nums) {
    int res = 0;
    int n = nums.size();
    std::vector<std::unordered_map<int, int>> dp(n);

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < i; ++j) {
            long diff = (long)nums[i] - (long)nums[j];
            if (diff <= INT_MIN || diff > INT_MAX) continue;

            int delta = (int)diff;
            dp[i][delta] += 1;

            if (dp[j].count(delta)) {
                res += dp[j][delta];
                dp[i][delta] += dp[j][delta];
            }
        }
    }
    return res;
}
```
To solve this problem, we use dynamic programming. The `dp` data structure is an array of hashmaps or dictionaries. Each index `i` in the array represents an element in the given array `nums`, and the hashmap stored at `dp[i]` will store the count of arithmetic subsequences that end at the element `nums[i]`, with keys representing the differences between elements.

Starting with index `i = 0`, we iterate through the `nums` array. For each element `nums[i]`, we iterate through all previous elements `nums[j]` with `j < i`.

For each pair of elements `(nums[i], nums[j])`, we calculate their difference and store the count of arithmetic subsequences formed by this difference at `dp[i]`.

If an existing subsequence with the same difference is found in `dp[j]`, we should be able to append `nums[i]` to all previously formed subsequences ending at `nums[j]`. Thus, we add the count of subsequences from `dp[j][delta]` to the result, and also update the count in `dp[i][delta]`.

Finally, after iterating through all elements, the `res` variable will hold the count of all the arithmetic subsequences.

## A solution in Python

```python
def numberOfArithmeticSlices(nums):
    res = 0
    n = len(nums)
    dp = [dict() for _ in range(n)]

    for i in range(n):
        for j in range(i):
            diff = nums[i] - nums[j]
            if diff <= -2**31 or diff > 2**31:
                continue

            dp[i][diff] = dp[i].get(diff, 0) + 1

            if diff in dp[j]:
                res += dp[j][diff]
                dp[i][diff] += dp[j][diff]

    return res
```
To solve this problem, we use dynamic programming. The `dp` data structure is an array of hashmaps or dictionaries. Each index `i` in the array represents an element in the given array `nums`, and the hashmap stored at `dp[i]` will store the count of arithmetic subsequences that end at the element `nums[i]`, with keys representing the differences between elements.

Starting with index `i = 0`, we iterate through the `nums` array. For each element `nums[i]`, we iterate through all previous elements `nums[j]` with `j < i`.

For each pair of elements `(nums[i], nums[j])`, we calculate their difference and store the count of arithmetic subsequences formed by this difference at `dp[i]`.

If an existing subsequence with the same difference is found in `dp[j]`, we should be able to append `nums[i]` to all previously formed subsequences ending at `nums[j]`. Thus, we add the count of subsequences from `dp[j][delta]` to the result, and also update the count in `dp[i][delta]`.

Finally, after iterating through all elements, the `res` variable will hold the count of all the arithmetic subsequences.

## A solution in Javascript

```javascript
function numberOfArithmeticSlices(nums) {
    let res = 0;
    const n = nums.length;
    const dp = new Array(n).fill(0).map(() => new Map());

    for (let i = 0; i < n; ++i) {
        for (let j = 0; j < i; ++j) {
            const diff = nums[i] - nums[j];
            if (diff <= Number.MIN_SAFE_INTEGER || diff > Number.MAX_SAFE_INTEGER) continue;

            if (!dp[i].has(diff)) {
                dp[i].set(diff, 0);
            }

            dp[i].set(diff, dp[i].get(diff) + 1);

            if (dp[j].has(diff)) {
                res += dp[j].get(diff);
                dp[i].set(diff, dp[i].get(diff) + dp[j].get(diff));
            }
        }
    }
    return res;
}
```
To solve this problem, we use dynamic programming. The `dp` data structure is an array of hashmaps or dictionaries. Each index `i` in the array represents an element in the given array `nums`, and the hashmap stored at `dp[i]` will store the count of arithmetic subsequences that end at the element `nums[i]`, with keys representing the differences between elements.

Starting with index `i = 0`, we iterate through the `nums` array. For each element `nums[i]`, we iterate through all previous elements `nums[j]` with `j < i`.

For each pair of elements `(nums[i], nums[j])`, we calculate their difference and store the count of arithmetic subsequences formed by this difference at `dp[i]`.

If an existing subsequence with the same difference is found in `dp[j]`, we should be able to append `nums[i]` to all previously formed subsequences ending at `nums[j]`. Thus, we add the count of subsequences from `dp[j][delta]` to the result, and also update the count in `dp[i][delta]`.

Finally, after iterating through all elements, the `res` variable will hold the count of all the arithmetic subsequences.