# Factor Combinations

- slug: factor-combinations
- difficulty: Medium

Numbers can be regarded as the product of their factors.

*   For example, `8 = 2 x 2 x 2 = 2 x 4`.

Given an integer `n`, return _all possible combinations of its factors_. You may return the answer in **any order**.

**Note** that the factors should be in the range `[2, n - 1]`.

**Example 1:**

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

**Example 2:**

**Input:** n = 12
**Output:** \[\[2,6\],\[3,4\],\[2,2,3\]\]

**Example 3:**

**Input:** n = 37
**Output:** \[\]

**Constraints:**

*   `1 <= n <= 107`

## A solution in Java

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

public List<List<Integer>> getFactors(int n) {
    List<List<Integer>> result = new ArrayList<>();
    helper(n, 2, new ArrayList<Integer>(), result);
    return result;
}

private void helper(int n, int start, List<Integer> path, List<List<Integer>> result) {
    if (n == 1) {
        if (path.size() > 1) {
            result.add(new ArrayList<>(path));
        }
        return;
    }

    for (int i = start; i <= n; i++) {
        if (n % i == 0) {
            path.add(i);
            helper(n / i, i, path, result);
            path.remove(path.size() - 1);
        }
    }
}
```
We use a backtracking algorithm to find all possible combinations of factors. The algorithm starts with `n` and splits it into all possible factors in the range `[2, n]`. We keep track of the current path, which represents the factors found so far. When `n` equals 1, we check if the current path has more than one element. If it does, we add the current combination of factors to the result.

To avoid duplicates, we ensure that the next factor in the sequence is greater than or equal to the previous one by passing a "start" variable in the helper function. This ensures that we always explore factors in a non-decreasing order.

At each recursive step, we first check if the current value of `n` is divisible by the current factor (i.e., it has no remainder when divided). If it is, we update the path with the current factor and call the helper function with the updated value of `n` divided by the current factor. After the recursive call returns, we remove the last factor from the path to backtrack to the previous level and explore other factors. This continues until we've explored all factors for the given input `n`. The final result is a list of lists representing all possible combinations of factors.

## A solution in C++

```cpp
#include <vector>

void helper(int n, int start, std::vector<int>& path, std::vector<std::vector<int>>& result) {
    if (n == 1) {
        if (path.size() > 1) {
            result.push_back(path);
        }
        return;
    }

    for (int i = start; i <= n; ++i) {
        if (n % i == 0) {
            path.push_back(i);
            helper(n / i, i, path, result);
            path.pop_back();
        }
    }
}

std::vector<std::vector<int>> getFactors(int n) {
    std::vector<std::vector<int>> result;
    std::vector<int> path;
    helper(n, 2, path, result);
    return result;
}
```
We use a backtracking algorithm to find all possible combinations of factors. The algorithm starts with `n` and splits it into all possible factors in the range `[2, n]`. We keep track of the current path, which represents the factors found so far. When `n` equals 1, we check if the current path has more than one element. If it does, we add the current combination of factors to the result.

To avoid duplicates, we ensure that the next factor in the sequence is greater than or equal to the previous one by passing a "start" variable in the helper function. This ensures that we always explore factors in a non-decreasing order.

At each recursive step, we first check if the current value of `n` is divisible by the current factor (i.e., it has no remainder when divided). If it is, we update the path with the current factor and call the helper function with the updated value of `n` divided by the current factor. After the recursive call returns, we remove the last factor from the path to backtrack to the previous level and explore other factors. This continues until we've explored all factors for the given input `n`. The final result is a list of lists representing all possible combinations of factors.

## A solution in Python

```python
def getFactors(n):
    def helper(n, start, path, result):
        if n == 1:
            if len(path) > 1:
                result.append(path[:])
            return

        for i in range(start, n + 1):
            if n % i == 0:
                path.append(i)
                helper(n // i, i, path, result)
                path.pop()

    result = []
    helper(n, 2, [], result)
    return result
```
We use a backtracking algorithm to find all possible combinations of factors. The algorithm starts with `n` and splits it into all possible factors in the range `[2, n]`. We keep track of the current path, which represents the factors found so far. When `n` equals 1, we check if the current path has more than one element. If it does, we add the current combination of factors to the result.

To avoid duplicates, we ensure that the next factor in the sequence is greater than or equal to the previous one by passing a "start" variable in the helper function. This ensures that we always explore factors in a non-decreasing order.

At each recursive step, we first check if the current value of `n` is divisible by the current factor (i.e., it has no remainder when divided). If it is, we update the path with the current factor and call the helper function with the updated value of `n` divided by the current factor. After the recursive call returns, we remove the last factor from the path to backtrack to the previous level and explore other factors. This continues until we've explored all factors for the given input `n`. The final result is a list of lists representing all possible combinations of factors.

## A solution in Javascript

```javascript
function getFactors(n) {
    const result = [];
    const helper = (n, start, path) => {
        if (n === 1) {
            if (path.length > 1) {
                result.push([...path]);
            }
            return;
        }

        for (let i = start; i <= n; i++) {
            if (n % i === 0) {
                path.push(i);
                helper(n / i, i, path);
                path.pop();
            }
        }
    };

    helper(n, 2, []);
    return result;
}
```
We use a backtracking algorithm to find all possible combinations of factors. The algorithm starts with `n` and splits it into all possible factors in the range `[2, n]`. We keep track of the current path, which represents the factors found so far. When `n` equals 1, we check if the current path has more than one element. If it does, we add the current combination of factors to the result.

To avoid duplicates, we ensure that the next factor in the sequence is greater than or equal to the previous one by passing a "start" variable in the helper function. This ensures that we always explore factors in a non-decreasing order.

At each recursive step, we first check if the current value of `n` is divisible by the current factor (i.e., it has no remainder when divided). If it is, we update the path with the current factor and call the helper function with the updated value of `n` divided by the current factor. After the recursive call returns, we remove the last factor from the path to backtrack to the previous level and explore other factors. This continues until we've explored all factors for the given input `n`. The final result is a list of lists representing all possible combinations of factors.


# Verify Preorder Sequence in Binary Search Tree

- slug: verify-preorder-sequence-in-binary-search-tree
- difficulty: Medium

Given an array of **unique** integers `preorder`, return `true` _if it is the correct preorder traversal sequence of a binary search tree_.

**Example 1:**

**Input:** preorder = \[5,2,1,3,6\]
**Output:** true

**Example 2:**

**Input:** preorder = \[5,2,6,1,3\]
**Output:** false

**Constraints:**

*   `1 <= preorder.length <= 104`
*   `1 <= preorder[i] <= 104`
*   All the elements of `preorder` are **unique**.

**Follow up:** Could you do it using only constant space complexity?

## A solution in Java

```java
public boolean isValidPreorder(int[] preorder) {
    Stack<Integer> stack = new Stack<>();
    int lowerBound = Integer.MIN_VALUE;
    for (int num : preorder) {
        if (num < lowerBound) return false;
        while (!stack.isEmpty() && num > stack.peek()) {
            lowerBound = stack.pop();
        }
        stack.push(num);
    }
    return true;
}
```
The algorithm is mainly based on a stack. It processes each element in the given `preorder` array and uses the stack to keep track of nodes that are not yet part of a completed subtree.

Initially, `lower_bound` is set to the minimum possible value.

For each number in the preorder array:

1. If the number is less than lower_bound, it means the number is trying to be added as a right child but the value is less than the minimum possible value, hence breaks the binary search tree property. So return false.

2. If the number is greater than the top of the stack, it means the number is the right child of the last node encountered. So, we pop from the stack and set the lower_bound to the last popped value until the stack is empty or the number is smaller than the top of the stack.

3. Push the number onto the stack.

If no false case is encountered during the loop, return true as it is a valid preorder traversal sequence of a binary search tree.

## A solution in C++

```cpp
bool isValidPreorder(vector<int>& preorder) {
    stack<int> stk;
    int lower_bound = INT_MIN;
    for (int num : preorder) {
        if (num < lower_bound) return false;
        while (!stk.empty() && num > stk.top()) {
            lower_bound = stk.top();
            stk.pop();
        }
        stk.push(num);
    }
    return true;
}
```
The algorithm is mainly based on a stack. It processes each element in the given `preorder` array and uses the stack to keep track of nodes that are not yet part of a completed subtree.

Initially, `lower_bound` is set to the minimum possible value.

For each number in the preorder array:

1. If the number is less than lower_bound, it means the number is trying to be added as a right child but the value is less than the minimum possible value, hence breaks the binary search tree property. So return false.

2. If the number is greater than the top of the stack, it means the number is the right child of the last node encountered. So, we pop from the stack and set the lower_bound to the last popped value until the stack is empty or the number is smaller than the top of the stack.

3. Push the number onto the stack.

If no false case is encountered during the loop, return true as it is a valid preorder traversal sequence of a binary search tree.

## A solution in Python

```python
def isValidPreorder(preorder: List[int]) -> bool:
    stack = []
    lower_bound = float('-inf')
    for num in preorder:
        if num < lower_bound:
            return False
        while stack and num > stack[-1]:
            lower_bound = stack.pop()
        stack.append(num)
    return True
```
The algorithm is mainly based on a stack. It processes each element in the given `preorder` array and uses the stack to keep track of nodes that are not yet part of a completed subtree.

Initially, `lower_bound` is set to the minimum possible value.

For each number in the preorder array:

1. If the number is less than lower_bound, it means the number is trying to be added as a right child but the value is less than the minimum possible value, hence breaks the binary search tree property. So return false.

2. If the number is greater than the top of the stack, it means the number is the right child of the last node encountered. So, we pop from the stack and set the lower_bound to the last popped value until the stack is empty or the number is smaller than the top of the stack.

3. Push the number onto the stack.

If no false case is encountered during the loop, return true as it is a valid preorder traversal sequence of a binary search tree.

## A solution in Javascript

```javascript
var isValidPreorder = function(preorder) {
    let stack = [];
    let lowerBound = Number.MIN_SAFE_INTEGER;
    for (let num of preorder) {
        if (num < lowerBound) return false;
        while (stack.length > 0 && num > stack[stack.length - 1]) {
            lowerBound = stack.pop();
        }
        stack.push(num);
    }
    return true;
};
```
The algorithm is mainly based on a stack. It processes each element in the given `preorder` array and uses the stack to keep track of nodes that are not yet part of a completed subtree.

Initially, `lower_bound` is set to the minimum possible value.

For each number in the preorder array:

1. If the number is less than lower_bound, it means the number is trying to be added as a right child but the value is less than the minimum possible value, hence breaks the binary search tree property. So return false.

2. If the number is greater than the top of the stack, it means the number is the right child of the last node encountered. So, we pop from the stack and set the lower_bound to the last popped value until the stack is empty or the number is smaller than the top of the stack.

3. Push the number onto the stack.

If no false case is encountered during the loop, return true as it is a valid preorder traversal sequence of a binary search tree.


# Paint House

- slug: paint-house
- difficulty: Medium

There is a row of `n` houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

The cost of painting each house with a certain color is represented by an `n x 3` cost matrix `costs`.

*   For example, `costs[0][0]` is the cost of painting house `0` with the color red; `costs[1][2]` is the cost of painting house 1 with color green, and so on...

Return _the minimum cost to paint all houses_.

**Example 1:**

**Input:** costs = \[\[17,2,17\],\[16,16,5\],\[14,3,19\]\]
**Output:** 10
**Explanation:** Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
Minimum cost: 2 + 5 + 3 = 10.

**Example 2:**

**Input:** costs = \[\[7,6,2\]\]
**Output:** 2

**Constraints:**

*   `costs.length == n`
*   `costs[i].length == 3`
*   `1 <= n <= 100`
*   `1 <= costs[i][j] <= 20`

## A solution in Java

```java
public int minCost(int[][] costs) {
    if (costs.length == 0) return 0;
    for (int i = 1; i < costs.length; i++) {
        costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]);
        costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]);
        costs[i][2] += Math.min(costs[i - 1][0], costs[i - 1][1]);
    }
    return Math.min(costs[costs.length - 1][0], Math.min(costs[costs.length - 1][1], costs[costs.length - 1][2]));
}
```
We use a dynamic programming approach to solve this problem. Initially, if there are no houses to paint, we return 0.
For the rest of the houses, we iterate through the array starting from the second house. For each house i, we calculate the cost of painting it with each color considering the last colored house.

1. costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]);
2. costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]);
3. costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]);

After iterating through all houses, we return the minimum cost of the possible color configurations for the last house.

## A solution in C++

```cpp
int minCost(vector<vector<int>>& costs) {
    if (costs.empty()) return 0;
    for (int i = 1; i < costs.size(); ++i) {
        costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]);
        costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]);
        costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]);
    }
    return min(costs.back()[0], min(costs.back()[1], costs.back()[2]));
}
```
We use a dynamic programming approach to solve this problem. Initially, if there are no houses to paint, we return 0.
For the rest of the houses, we iterate through the array starting from the second house. For each house i, we calculate the cost of painting it with each color considering the last colored house.

1. costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]);
2. costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]);
3. costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]);

After iterating through all houses, we return the minimum cost of the possible color configurations for the last house.

## A solution in Python

```python
def minCost(costs: List[List[int]]) -> int:
    if not costs:
        return 0
    for i in range(1, len(costs)):
        costs[i][0] += min(costs[i - 1][1], costs[i - 1][2])
        costs[i][1] += min(costs[i - 1][0], costs[i - 1][2])
        costs[i][2] += min(costs[i - 1][0], costs[i - 1][1])
    return min(costs[-1][0], costs[-1][1], costs[-1][2])
```
We use a dynamic programming approach to solve this problem. Initially, if there are no houses to paint, we return 0.
For the rest of the houses, we iterate through the array starting from the second house. For each house i, we calculate the cost of painting it with each color considering the last colored house.

1. costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]);
2. costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]);
3. costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]);

After iterating through all houses, we return the minimum cost of the possible color configurations for the last house.

## A solution in Javascript

```javascript
function minCost(costs) {
    if (costs.length === 0) return 0;
    for (let i = 1; i < costs.length; i++) {
        costs[i][0] += Math.min(costs[i - 1][1], costs[i - 1][2]);
        costs[i][1] += Math.min(costs[i - 1][0], costs[i - 1][2]);
        costs[i][2] += Math.min(costs[i - 1][0], costs[i - 1][1]);
    }
    return Math.min(costs[costs.length - 1][0], costs[costs.length - 1][1], costs[costs.length - 1][2]);
}
```
We use a dynamic programming approach to solve this problem. Initially, if there are no houses to paint, we return 0.
For the rest of the houses, we iterate through the array starting from the second house. For each house i, we calculate the cost of painting it with each color considering the last colored house.

1. costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]);
2. costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]);
3. costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]);

After iterating through all houses, we return the minimum cost of the possible color configurations for the last house.


# Binary Tree Paths

- slug: binary-tree-paths
- difficulty: Easy

Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.

A **leaf** is a node with no children.

**Example 1:**

**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]

**Example 2:**

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

**Constraints:**

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

## A solution in Java

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

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public List<String> binaryTreePaths(TreeNode root) {
    List<String> paths = new ArrayList<>();
    if (root == null) {
        return paths;
    }
    if (root.left == null && root.right == null) {
        paths.add(Integer.toString(root.val));
        return paths;
    }
    for (String path : binaryTreePaths(root.left)) {
      paths.add(root.val + "->" + path);
    }
    for (String path : binaryTreePaths(root.right)) {
      paths.add(root.val + "->" + path);
    }
    return paths;
}
```
The algorithm is a simple recursive algorithm that explores depth-first each node of the binary tree. Initially, if the root is `null`, it returns an empty result. Next, if it's a leaf node, it returns the node's value as a string. If it's not a leaf node, it iteratively calls the `binary_tree_paths()` function for the left child and then the right child, appending the current node's value and a " -> " separator at the beginning of each path. Finally, it aggregates and returns all the resulting paths of the recursive calls. The language-specific implementations are all very similar, with only slight syntax adjustments across languages.

## A solution in C++

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

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

std::vector<std::string> binaryTreePaths(TreeNode* root) {
    std::vector<std::string> paths;
    if (!root)
        return paths;
    if (!root->left && !root->right) {
        paths.push_back(std::to_string(root->val));
        return paths;
    }
    for (const std::string &path : binaryTreePaths(root->left)) {
      paths.push_back(std::to_string(root->val) + "->" + path);
    }
    for (const std::string &path : binaryTreePaths(root->right)) {
      paths.push_back(std::to_string(root->val) + "->" + path);
    }
    return paths;
}
```
The algorithm is a simple recursive algorithm that explores depth-first each node of the binary tree. Initially, if the root is `null`, it returns an empty result. Next, if it's a leaf node, it returns the node's value as a string. If it's not a leaf node, it iteratively calls the `binary_tree_paths()` function for the left child and then the right child, appending the current node's value and a " -> " separator at the beginning of each path. Finally, it aggregates and returns all the resulting paths of the recursive calls. The language-specific implementations are all very similar, with only slight syntax adjustments across languages.

## A solution in Python

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

def binary_tree_paths(root: TreeNode):
    if not root:
        return []
    if not root.left and not root.right:
        return [str(root.val)]
    paths = []
    for path in binary_tree_paths(root.left):
        paths.append(str(root.val) + "->" + path)
    for path in binary_tree_paths(root.right):
        paths.append(str(root.val) + "->" + path)
    return paths
```
The algorithm is a simple recursive algorithm that explores depth-first each node of the binary tree. Initially, if the root is `null`, it returns an empty result. Next, if it's a leaf node, it returns the node's value as a string. If it's not a leaf node, it iteratively calls the `binary_tree_paths()` function for the left child and then the right child, appending the current node's value and a " -> " separator at the beginning of each path. Finally, it aggregates and returns all the resulting paths of the recursive calls. The language-specific implementations are all very similar, with only slight syntax adjustments across languages.

## A solution in Javascript

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

function binaryTreePaths(root) {
    if (!root) {
        return [];
    }
    if (!root.left && !root.right) {
        return [`${root.val}`];
    }
    let paths = [];
    for (let path of binaryTreePaths(root.left)) {
        paths.push(`${root.val}->${path}`);
    }
    for (let path of binaryTreePaths(root.right)) {
        paths.push(`${root.val}->${path}`);
    }
    return paths;
}
```
The algorithm is a simple recursive algorithm that explores depth-first each node of the binary tree. Initially, if the root is `null`, it returns an empty result. Next, if it's a leaf node, it returns the node's value as a string. If it's not a leaf node, it iteratively calls the `binary_tree_paths()` function for the left child and then the right child, appending the current node's value and a " -> " separator at the beginning of each path. Finally, it aggregates and returns all the resulting paths of the recursive calls. The language-specific implementations are all very similar, with only slight syntax adjustments across languages.


# Add Digits

- slug: add-digits
- difficulty: Easy

Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.

**Example 1:**

**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.

**Example 2:**

**Input:** num = 0
**Output:** 0

**Constraints:**

*   `0 <= num <= 231 - 1`

**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?

## A solution in Java

```java
public int addDigits(int num) {
    return 1 + (num - 1) % 9;
}
```
The idea is to find the pattern for the single digit that will be the outcome of repeatedly summing up a number's digits. Observe that for numbers 1-9, the single digit outcome is the number itself. For numbers 10-18 (i.e., 1+0, 1+1, 1+2, ..., 1+8), the single digit outcome is 1-9 again. This pattern repeats.

In the given code, we return the value computed from the formula `1 + (num - 1) % 9`. The formula derives from the observation mentioned above. Here's the explanation:

- Subtracting 1 shifts the sequence to range from 0 to 8 instead of 1 to 9.
- Taking num modulo 9 reveals the repeating 0-8 pattern.
- Adding 1 offsets the range back to 1-9.

This algorithm works for all positive integer numbers, and the result is the single digit number that is the outcome of repeatedly summing up the original number's digits.

## A solution in C++

```cpp
int addDigits(int num) {
    return 1 + (num - 1) % 9;
}
```
The idea is to find the pattern for the single digit that will be the outcome of repeatedly summing up a number's digits. Observe that for numbers 1-9, the single digit outcome is the number itself. For numbers 10-18 (i.e., 1+0, 1+1, 1+2, ..., 1+8), the single digit outcome is 1-9 again. This pattern repeats.

In the given code, we return the value computed from the formula `1 + (num - 1) % 9`. The formula derives from the observation mentioned above. Here's the explanation:

- Subtracting 1 shifts the sequence to range from 0 to 8 instead of 1 to 9.
- Taking num modulo 9 reveals the repeating 0-8 pattern.
- Adding 1 offsets the range back to 1-9.

This algorithm works for all positive integer numbers, and the result is the single digit number that is the outcome of repeatedly summing up the original number's digits.

## A solution in Python

```python
def addDigits(num: int) -> int:
    return 1 + (num - 1) % 9
```
The idea is to find the pattern for the single digit that will be the outcome of repeatedly summing up a number's digits. Observe that for numbers 1-9, the single digit outcome is the number itself. For numbers 10-18 (i.e., 1+0, 1+1, 1+2, ..., 1+8), the single digit outcome is 1-9 again. This pattern repeats.

In the given code, we return the value computed from the formula `1 + (num - 1) % 9`. The formula derives from the observation mentioned above. Here's the explanation:

- Subtracting 1 shifts the sequence to range from 0 to 8 instead of 1 to 9.
- Taking num modulo 9 reveals the repeating 0-8 pattern.
- Adding 1 offsets the range back to 1-9.

This algorithm works for all positive integer numbers, and the result is the single digit number that is the outcome of repeatedly summing up the original number's digits.

## A solution in Javascript

```javascript
function addDigits(num) {
    return 1 + (num - 1) % 9;
}
```
The idea is to find the pattern for the single digit that will be the outcome of repeatedly summing up a number's digits. Observe that for numbers 1-9, the single digit outcome is the number itself. For numbers 10-18 (i.e., 1+0, 1+1, 1+2, ..., 1+8), the single digit outcome is 1-9 again. This pattern repeats.

In the given code, we return the value computed from the formula `1 + (num - 1) % 9`. The formula derives from the observation mentioned above. Here's the explanation:

- Subtracting 1 shifts the sequence to range from 0 to 8 instead of 1 to 9.
- Taking num modulo 9 reveals the repeating 0-8 pattern.
- Adding 1 offsets the range back to 1-9.

This algorithm works for all positive integer numbers, and the result is the single digit number that is the outcome of repeatedly summing up the original number's digits.


# 3Sum Smaller

- slug: 3sum-smaller
- difficulty: Medium

Given an array of `n` integers `nums` and an integer `target`, find the number of index triplets `i`, `j`, `k` with `0 <= i < j < k < n` that satisfy the condition `nums[i] + nums[j] + nums[k] < target`.

**Example 1:**

**Input:** nums = \[-2,0,1,3\], target = 2
**Output:** 2
**Explanation:** Because there are two triplets which sums are less than 2:
\[-2,0,1\]
\[-2,0,3\]

**Example 2:**

**Input:** nums = \[\], target = 0
**Output:** 0

**Example 3:**

**Input:** nums = \[0\], target = 0
**Output:** 0

**Constraints:**

*   `n == nums.length`
*   `0 <= n <= 3500`
*   `-100 <= nums[i] <= 100`
*   `-100 <= target <= 100`

## A solution in Java

```java
public int threeSumSmaller(int[] nums, int target) {
    int count = 0;
    Arrays.sort(nums);
    for (int i = 0; i < nums.length; ++i) {
        int j = i + 1, k = nums.length - 1;
        while (j < k) {
            if (nums[i] + nums[j] + nums[k] < target) {
                count += k - j;
                ++j;
            } else {
                --k;
            }
        }
    }
    return count;
}
```
To solve this problem, we first sort the input array. Then we loop through each element in the array and use two pointers, `j` and `k`, initialized to the following element and the last element in the sorted array, respectively. We repeat the process until `j` is less than `k`. Inside the loop, we check if the sum of `nums[i]`, `nums[j]`, and `nums[k]` is less than the target. If it is, we add the difference `k - j` to the count and increment `j`. Otherwise, we decrement `k`. Finally, we return the count.

## A solution in C++

```cpp
int threeSumSmaller(vector<int>& nums, int target) {
    int count = 0;
    sort(nums.begin(), nums.end());
    for (int i = 0; i < nums.size(); ++i) {
        int j = i + 1, k = nums.size() - 1;
        while (j < k) {
            if (nums[i] + nums[j] + nums[k] < target) {
                count += k - j;
                ++j;
            } else {
                --k;
            }
        }
    }
    return count;
}
```
To solve this problem, we first sort the input array. Then we loop through each element in the array and use two pointers, `j` and `k`, initialized to the following element and the last element in the sorted array, respectively. We repeat the process until `j` is less than `k`. Inside the loop, we check if the sum of `nums[i]`, `nums[j]`, and `nums[k]` is less than the target. If it is, we add the difference `k - j` to the count and increment `j`. Otherwise, we decrement `k`. Finally, we return the count.

## A solution in Python

```python
def threeSumSmaller(nums, target):
    count = 0
    nums.sort()
    for i in range(len(nums)):
        j, k = i + 1, len(nums) - 1
        while j < k:
            if nums[i] + nums[j] + nums[k] < target:
                count += k - j
                j += 1
            else:
                k -= 1
    return count
```
To solve this problem, we first sort the input array. Then we loop through each element in the array and use two pointers, `j` and `k`, initialized to the following element and the last element in the sorted array, respectively. We repeat the process until `j` is less than `k`. Inside the loop, we check if the sum of `nums[i]`, `nums[j]`, and `nums[k]` is less than the target. If it is, we add the difference `k - j` to the count and increment `j`. Otherwise, we decrement `k`. Finally, we return the count.

## A solution in Javascript

```javascript
function threeSumSmaller(nums, target) {
    let count = 0;
    nums.sort((a, b) => a - b);
    for (let i = 0; i < nums.length; ++i) {
        let j = i + 1, k = nums.length - 1;
        while (j < k) {
            if (nums[i] + nums[j] + nums[k] < target) {
                count += k - j;
                ++j;
            } else {
                --k;
            }
        }
    }
    return count;
}
```
To solve this problem, we first sort the input array. Then we loop through each element in the array and use two pointers, `j` and `k`, initialized to the following element and the last element in the sorted array, respectively. We repeat the process until `j` is less than `k`. Inside the loop, we check if the sum of `nums[i]`, `nums[j]`, and `nums[k]` is less than the target. If it is, we add the difference `k - j` to the count and increment `j`. Otherwise, we decrement `k`. Finally, we return the count.


# Single Number III

- slug: single-number-iii
- difficulty: Medium

Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**.

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

**Example 1:**

**Input:** nums = \[1,2,1,3,2,5\]
**Output:** \[3,5\]
**Explanation: ** \[5, 3\] is also a valid answer.

**Example 2:**

**Input:** nums = \[-1,0\]
**Output:** \[-1,0\]

**Example 3:**

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

**Constraints:**

*   `2 <= nums.length <= 3 * 104`
*   `-231 <= nums[i] <= 231 - 1`
*   Each integer in `nums` will appear twice, only two integers will appear once.

## A solution in Java

```java
public int[] singleNumber(int[] nums) {
    int xor_all = 0;
    for (int num : nums) {
        xor_all ^= num;
    }

    int bit = xor_all & -xor_all;
    int n1 = 0;
    int n2 = 0;
    for (int num : nums) {
        if ((num & bit) != 0) {
            n1 ^= num;
        } else {
            n2 ^= num;
        }
    }

    return new int[]{n1, n2};
}
```
The algorithm uses XOR operation to find the two unique numbers. First, we XOR all numbers in the array (which cancels out the repeating numbers), and the result of this XOR operation is actually the XOR of the two unique numbers. Then, we find the rightmost bit that is set to 1 in this XOR result. This bit will be different for the two unique numbers.

Next, we split the numbers into two groups: one group has that bit set, and the other group doesn't. XOR all numbers in both groups separately, and the result of the XOR operation for each group will be one of the unique numbers. This is because, within each group, the equal numbers will cancel themselves out, leaving the unique numbers as the result.

This algorithm has a linear runtime complexity (O(n)) and uses constant extra space, as required.

## A solution in C++

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

vector<int> singleNumber(vector<int>& nums) {
    int xor_all = 0;
    for (int num : nums) {
        xor_all ^= num;
    }

    int bit = xor_all & (-xor_all);
    int n1 = 0;
    int n2 = 0;
    for (int num : nums) {
        if (num & bit) {
            n1 ^= num;
        } else {
            n2 ^= num;
        }
    }

    return vector<int>{n1, n2};
}
```
The algorithm uses XOR operation to find the two unique numbers. First, we XOR all numbers in the array (which cancels out the repeating numbers), and the result of this XOR operation is actually the XOR of the two unique numbers. Then, we find the rightmost bit that is set to 1 in this XOR result. This bit will be different for the two unique numbers.

Next, we split the numbers into two groups: one group has that bit set, and the other group doesn't. XOR all numbers in both groups separately, and the result of the XOR operation for each group will be one of the unique numbers. This is because, within each group, the equal numbers will cancel themselves out, leaving the unique numbers as the result.

This algorithm has a linear runtime complexity (O(n)) and uses constant extra space, as required.

## A solution in Python

```python
def singleNumber(nums):
    xor_all = 0
    for num in nums:
        xor_all ^= num

    bit = xor_all & -xor_all
    n1 = 0
    n2 = 0
    for num in nums:
        if num & bit:
            n1 ^= num
        else:
            n2 ^= num

    return n1, n2
```
The algorithm uses XOR operation to find the two unique numbers. First, we XOR all numbers in the array (which cancels out the repeating numbers), and the result of this XOR operation is actually the XOR of the two unique numbers. Then, we find the rightmost bit that is set to 1 in this XOR result. This bit will be different for the two unique numbers.

Next, we split the numbers into two groups: one group has that bit set, and the other group doesn't. XOR all numbers in both groups separately, and the result of the XOR operation for each group will be one of the unique numbers. This is because, within each group, the equal numbers will cancel themselves out, leaving the unique numbers as the result.

This algorithm has a linear runtime complexity (O(n)) and uses constant extra space, as required.

## A solution in Javascript

```javascript
function singleNumber(nums) {
    let xor_all = 0;
    for (const num of nums) {
        xor_all ^= num;
    }

    const bit = xor_all & -xor_all;
    let n1 = 0;
    let n2 = 0;
    for (const num of nums) {
        if (num & bit) {
            n1 ^= num;
        } else {
            n2 ^= num;
        }
    }

    return [n1, n2];
}
```
The algorithm uses XOR operation to find the two unique numbers. First, we XOR all numbers in the array (which cancels out the repeating numbers), and the result of this XOR operation is actually the XOR of the two unique numbers. Then, we find the rightmost bit that is set to 1 in this XOR result. This bit will be different for the two unique numbers.

Next, we split the numbers into two groups: one group has that bit set, and the other group doesn't. XOR all numbers in both groups separately, and the result of the XOR operation for each group will be one of the unique numbers. This is because, within each group, the equal numbers will cancel themselves out, leaving the unique numbers as the result.

This algorithm has a linear runtime complexity (O(n)) and uses constant extra space, as required.


# Graph Valid Tree

- slug: graph-valid-tree
- difficulty: Medium

You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the graph.

Return `true` _if the edges of the given graph make up a valid tree, and_ `false` _otherwise_.

**Example 1:**

**Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[0,3\],\[1,4\]\]
**Output:** true

**Example 2:**

**Input:** n = 5, edges = \[\[0,1\],\[1,2\],\[2,3\],\[1,3\],\[1,4\]\]
**Output:** false

**Constraints:**

*   `1 <= n <= 2000`
*   `0 <= edges.length <= 5000`
*   `edges[i].length == 2`
*   `0 <= ai, bi < n`
*   `ai != bi`
*   There are no self-loops or repeated edges.

## A solution in Java

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

public boolean isTree(int n, int[][] edges) {
    List<List<Integer>> neighbors = new ArrayList<>(n);
    for (int i = 0; i < n; i++) neighbors.add(new ArrayList<>());
    for (int[] edge : edges) {
        neighbors.get(edge[0]).add(edge[1]);
        neighbors.get(edge[1]).add(edge[0]);
    }
    boolean[] visited = new boolean[n];
    if(hasCycle(neighbors, visited, -1, 0)) return false;
    for (boolean visit : visited)
        if (!visit) return false;
    return true;
}

private boolean hasCycle(List<List<Integer>> neighbors, boolean[] visited, int parent, int node) {
    visited[node] = true;
    for (int neighbor : neighbors.get(node))
        if ((neighbor != parent && visited[neighbor]) || (!visited[neighbor] && hasCycle(neighbors, visited, node, neighbor))) return true;
    return false;
}
```
The algorithm uses depth-first search (DFS) to traverse the given graph. During traversal, it checks if there is a cycle (a node visited more than once). A valid tree should not have any cycles, and all nodes must be reachable.

1. Create a list of neighbors for each node.
2. Initialize a visited array to keep track of visited nodes.
3. Call the 'hasCycle' function to perform DFS and also check the existence of a cycle.
4. If a cycle exists, return false.
5. If all nodes have not been visited, return false.
6. If there is no cycle and all nodes have been visited, return true.

The 'hasCycle' function checks for the cycle recursively. When visiting a node, mark it as visited. For each neighbor of the current node, if the neighbor is not the parent and has been visited, return true as a cycle is found. If the neighbor is not visited, call the 'hasCycle' function recursively. If the recursion returns true, a cycle has been found. Else, return false as no cycle is found in the current neighbors.

## A solution in C++

```cpp
#include <vector>

bool isTree(int n, std::vector<std::vector<int>>& edges) {
    std::vector<std::vector<int>> neighbors(n);
    for (const auto& edge : edges) {
        neighbors[edge[0]].push_back(edge[1]);
        neighbors[edge[1]].push_back(edge[0]);
    }
    std::vector<bool> visited(n, false);
    if(hasCycle(neighbors, visited, -1, 0)) return false;
    for (const auto& visit : visited)
        if (!visit) return false;
    return true;
}

bool hasCycle(const std::vector<std::vector<int>>& neighbors, std::vector<bool>& visited, int parent, int node) {
    visited[node] = true;
    for (const auto& neighbor : neighbors[node])
        if ((neighbor != parent && visited[neighbor]) || (!visited[neighbor] && hasCycle(neighbors, visited, node, neighbor))) return true;
    return false;
}
```
The algorithm uses depth-first search (DFS) to traverse the given graph. During traversal, it checks if there is a cycle (a node visited more than once). A valid tree should not have any cycles, and all nodes must be reachable.

1. Create a list of neighbors for each node.
2. Initialize a visited array to keep track of visited nodes.
3. Call the 'hasCycle' function to perform DFS and also check the existence of a cycle.
4. If a cycle exists, return false.
5. If all nodes have not been visited, return false.
6. If there is no cycle and all nodes have been visited, return true.

The 'hasCycle' function checks for the cycle recursively. When visiting a node, mark it as visited. For each neighbor of the current node, if the neighbor is not the parent and has been visited, return true as a cycle is found. If the neighbor is not visited, call the 'hasCycle' function recursively. If the recursion returns true, a cycle has been found. Else, return false as no cycle is found in the current neighbors.

## A solution in Python

```python
from typing import List

def isTree(n: int, edges: List[List[int]]) -> bool:
    neighbors = [[] for _ in range(n)]
    for edge in edges:
        neighbors[edge[0]].append(edge[1])
        neighbors[edge[1]].append(edge[0])
    visited = [False] * n
    if hasCycle(neighbors, visited, -1, 0): return False
    return all(visited)

def hasCycle(neighbors: List[List[int]], visited: List[bool], parent: int, node: int) -> bool:
    visited[node] = True
    for neighbor in neighbors[node]:
        if (neighbor != parent and visited[neighbor]) or (not visited[neighbor] and hasCycle(neighbors, visited, node, neighbor)): return True
    return False
```
The algorithm uses depth-first search (DFS) to traverse the given graph. During traversal, it checks if there is a cycle (a node visited more than once). A valid tree should not have any cycles, and all nodes must be reachable.

1. Create a list of neighbors for each node.
2. Initialize a visited array to keep track of visited nodes.
3. Call the 'hasCycle' function to perform DFS and also check the existence of a cycle.
4. If a cycle exists, return false.
5. If all nodes have not been visited, return false.
6. If there is no cycle and all nodes have been visited, return true.

The 'hasCycle' function checks for the cycle recursively. When visiting a node, mark it as visited. For each neighbor of the current node, if the neighbor is not the parent and has been visited, return true as a cycle is found. If the neighbor is not visited, call the 'hasCycle' function recursively. If the recursion returns true, a cycle has been found. Else, return false as no cycle is found in the current neighbors.

## A solution in Javascript

```javascript
function isTree(n, edges) {
    const neighbors = Array.from({length: n}, () => []);
    for (const edge of edges) {
        neighbors[edge[0]].push(edge[1]);
        neighbors[edge[1]].push(edge[0]);
    }
    const visited = Array(n).fill(false);
    if(hasCycle(neighbors, visited, -1, 0)) return false;
    for (const visit of visited)
        if (!visit) return false;
    return true;
}

function hasCycle(neighbors, visited, parent, node) {
    visited[node] = true;
    for (const neighbour of neighbors[node])
        if ((neighbour !== parent && visited[neighbour]) || (!visited[neighbour] && hasCycle(neighbors, visited, node, neighbour))) return true;
    return false;
}
```
The algorithm uses depth-first search (DFS) to traverse the given graph. During traversal, it checks if there is a cycle (a node visited more than once). A valid tree should not have any cycles, and all nodes must be reachable.

1. Create a list of neighbors for each node.
2. Initialize a visited array to keep track of visited nodes.
3. Call the 'hasCycle' function to perform DFS and also check the existence of a cycle.
4. If a cycle exists, return false.
5. If all nodes have not been visited, return false.
6. If there is no cycle and all nodes have been visited, return true.

The 'hasCycle' function checks for the cycle recursively. When visiting a node, mark it as visited. For each neighbor of the current node, if the neighbor is not the parent and has been visited, return true as a cycle is found. If the neighbor is not visited, call the 'hasCycle' function recursively. If the recursion returns true, a cycle has been found. Else, return false as no cycle is found in the current neighbors.


# Ugly Number

- slug: ugly-number
- difficulty: Easy

An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.

Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_.

**Example 1:**

**Input:** n = 6
**Output:** true
**Explanation:** 6 = 2 \* 3

**Example 2:**

**Input:** n = 1
**Output:** true
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

**Example 3:**

**Input:** n = 14
**Output:** false
**Explanation:** 14 is not ugly since it includes the prime factor 7.

**Constraints:**

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

## A solution in Java

```java
public boolean isUgly(int n) {
    if (n <= 0) return false;
    while (n % 2 == 0) n /= 2;
    while (n % 3 == 0) n /= 3;
    while (n % 5 == 0) n /= 5;
    return n == 1;
}
```
The algorithm checks if the number is less than or equal to 0 because only positive integers can be ugly. If the input number is divisible by 2, 3, or 5, we keep dividing it by the respective factor in a loop until it's no longer divisible by that factor. After processing all factors (2, 3, 5), if the remaining number is 1, then the input number had only prime factors of 2, 3, and 5, hence it is an ugly number. Otherwise, it's not an ugly number.

## A solution in C++

```cpp
bool isUgly(int n) {
    if (n <= 0) return false;
    while (n % 2 == 0) n /= 2;
    while (n % 3 == 0) n /= 3;
    while (n % 5 == 0) n /= 5;
    return n == 1;
}
```
The algorithm checks if the number is less than or equal to 0 because only positive integers can be ugly. If the input number is divisible by 2, 3, or 5, we keep dividing it by the respective factor in a loop until it's no longer divisible by that factor. After processing all factors (2, 3, 5), if the remaining number is 1, then the input number had only prime factors of 2, 3, and 5, hence it is an ugly number. Otherwise, it's not an ugly number.

## A solution in Python

```python
def is_ugly(n: int) -> bool:
    if n <= 0:
        return False
    for factor in [2, 3, 5]:
        while n % factor == 0:
            n //= factor
    return n == 1
```
The algorithm checks if the number is less than or equal to 0 because only positive integers can be ugly. If the input number is divisible by 2, 3, or 5, we keep dividing it by the respective factor in a loop until it's no longer divisible by that factor. After processing all factors (2, 3, 5), if the remaining number is 1, then the input number had only prime factors of 2, 3, and 5, hence it is an ugly number. Otherwise, it's not an ugly number.

## A solution in Javascript

```javascript
function isUgly(n) {
    if (n <= 0) return false;
    while (n % 2 === 0) n /= 2;
    while (n % 3 === 0) n /= 3;
    while (n % 5 === 0) n /= 5;
    return n === 1;
}
```
The algorithm checks if the number is less than or equal to 0 because only positive integers can be ugly. If the input number is divisible by 2, 3, or 5, we keep dividing it by the respective factor in a loop until it's no longer divisible by that factor. After processing all factors (2, 3, 5), if the remaining number is 1, then the input number had only prime factors of 2, 3, and 5, hence it is an ugly number. Otherwise, it's not an ugly number.


# Ugly Number II

- slug: ugly-number-ii
- difficulty: Medium

An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.

Given an integer `n`, return _the_ `nth` _**ugly number**_.

**Example 1:**

**Input:** n = 10
**Output:** 12
**Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence of the first 10 ugly numbers.

**Example 2:**

**Input:** n = 1
**Output:** 1
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

**Constraints:**

*   `1 <= n <= 1690`

## A solution in Java

```java
public int nthUglyNumber(int n) {
    int[] uglyNumbers = new int[n];
    uglyNumbers[0] = 1;
    int i2 = 0, i3 = 0, i5 = 0;

    for (int i = 1; i < n; i++) {
        uglyNumbers[i] = Math.min(Math.min(uglyNumbers[i2] * 2, uglyNumbers[i3] * 3), uglyNumbers[i5] * 5);
        if (uglyNumbers[i] == uglyNumbers[i2] * 2) i2++;
        if (uglyNumbers[i] == uglyNumbers[i3] * 3) i3++;
        if (uglyNumbers[i] == uglyNumbers[i5] * 5) i5++;
    }

    return uglyNumbers[n - 1];
}
```
1. Initialize an array of size n and set the first element to 1 (the first ugly number).
2. Create three variables (i2, i3, and i5) to keep track of the current index of ugly numbers multiplied by 2, 3, and 5.
3. Iterate through the array from index 1 to n-1, calculating the next ugly number as the minimum of (uglyNumbers[i2] * 2, uglyNumbers[i3] * 3, and uglyNumbers[i5] * 5).
4. Update the indices (i2, i3, and i5) based on which ugly number was used in the minimum calculation.
5. The last element of the array is the nth ugly number.

## A solution in C++

```cpp
int nthUglyNumber(int n) {
    vector<int> uglyNumbers(n);
    uglyNumbers[0] = 1;
    int i2 = 0, i3 = 0, i5 = 0;

    for (int i = 1; i < n; i++) {
        uglyNumbers[i] = min({uglyNumbers[i2] * 2, uglyNumbers[i3] * 3, uglyNumbers[i5] * 5});
        if (uglyNumbers[i] == uglyNumbers[i2] * 2) i2++;
        if (uglyNumbers[i] == uglyNumbers[i3] * 3) i3++;
        if (uglyNumbers[i] == uglyNumbers[i5] * 5) i5++;
    }

    return uglyNumbers[n - 1];
}
```
1. Initialize an array of size n and set the first element to 1 (the first ugly number).
2. Create three variables (i2, i3, and i5) to keep track of the current index of ugly numbers multiplied by 2, 3, and 5.
3. Iterate through the array from index 1 to n-1, calculating the next ugly number as the minimum of (uglyNumbers[i2] * 2, uglyNumbers[i3] * 3, and uglyNumbers[i5] * 5).
4. Update the indices (i2, i3, and i5) based on which ugly number was used in the minimum calculation.
5. The last element of the array is the nth ugly number.

## A solution in Python

```python
def nthUglyNumber(n: int) -> int:
    ugly_numbers = [0] * n
    ugly_numbers[0] = 1
    i2, i3, i5 = 0, 0, 0

    for i in range(1, n):
        ugly_numbers[i] = min(ugly_numbers[i2] * 2, ugly_numbers[i3] * 3, ugly_numbers[i5] * 5)
        if ugly_numbers[i] == ugly_numbers[i2] * 2: i2 += 1
        if ugly_numbers[i] == ugly_numbers[i3] * 3: i3 += 1
        if ugly_numbers[i] == ugly_numbers[i5] * 5: i5 += 1

    return ugly_numbers[n - 1]

```
1. Initialize an array of size n and set the first element to 1 (the first ugly number).
2. Create three variables (i2, i3, and i5) to keep track of the current index of ugly numbers multiplied by 2, 3, and 5.
3. Iterate through the array from index 1 to n-1, calculating the next ugly number as the minimum of (uglyNumbers[i2] * 2, uglyNumbers[i3] * 3, and uglyNumbers[i5] * 5).
4. Update the indices (i2, i3, and i5) based on which ugly number was used in the minimum calculation.
5. The last element of the array is the nth ugly number.

## A solution in Javascript

```javascript
function nthUglyNumber(n) {
    let uglyNumbers = new Array(n);
    uglyNumbers[0] = 1;
    let i2 = 0, i3 = 0, i5 = 0;

    for (let i = 1; i < n; i++) {
        uglyNumbers[i] = Math.min(Math.min(uglyNumbers[i2] * 2, uglyNumbers[i3] * 3), uglyNumbers[i5] * 5);
        if (uglyNumbers[i] === uglyNumbers[i2] * 2) i2++;
        if (uglyNumbers[i] === uglyNumbers[i3] * 3) i3++;
        if (uglyNumbers[i] === uglyNumbers[i5] * 5) i5++;
    }

    return uglyNumbers[n - 1];
}
```
1. Initialize an array of size n and set the first element to 1 (the first ugly number).
2. Create three variables (i2, i3, and i5) to keep track of the current index of ugly numbers multiplied by 2, 3, and 5.
3. Iterate through the array from index 1 to n-1, calculating the next ugly number as the minimum of (uglyNumbers[i2] * 2, uglyNumbers[i3] * 3, and uglyNumbers[i5] * 5).
4. Update the indices (i2, i3, and i5) based on which ugly number was used in the minimum calculation.
5. The last element of the array is the nth ugly number.


# Paint House II

- slug: paint-house-ii
- difficulty: Hard

There are a row of `n` houses, each house can be painted with one of the `k` colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

The cost of painting each house with a certain color is represented by an `n x k` cost matrix costs.

*   For example, `costs[0][0]` is the cost of painting house `0` with color `0`; `costs[1][2]` is the cost of painting house `1` with color `2`, and so on...

Return _the minimum cost to paint all houses_.

**Example 1:**

**Input:** costs = \[\[1,5,3\],\[2,9,4\]\]
**Output:** 5
**Explanation:**
Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5;
Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.

**Example 2:**

**Input:** costs = \[\[1,3\],\[2,4\]\]
**Output:** 5

**Constraints:**

*   `costs.length == n`
*   `costs[i].length == k`
*   `1 <= n <= 100`
*   `2 <= k <= 20`
*   `1 <= costs[i][j] <= 20`

**Follow up:** Could you solve it in `O(nk)` runtime?

## A solution in Java

```java
public int minCost(int[][] costs) {
    if (costs == null || costs.length == 0) return 0;

    int n = costs.length;
    int k = costs[0].length;

    for (int i = 1; i < n; i++) {
        for (int j = 0; j < k; j++) {
            int minCost = Integer.MAX_VALUE;
            for (int l = 0; l < k; l++) {
                if (l == j) continue;
                minCost = Math.min(minCost, costs[i - 1][l]);
            }
            costs[i][j] += minCost;
        }
    }
    return Arrays.stream(costs[n - 1]).min().getAsInt();
}
```
The algorithm stores the minimum cost to paint each house up to the current house with each color. Then for each house, it iterates through all the colors and calculates the minimum cost for painting that house with each color. It skips the same color as the previous house because no two adjacent houses can have the same color. After processing all the houses, the minimum of the last row in `costs` is the minimum cost to paint all the houses.

## A solution in C++

```cpp
int minCost(vector<vector<int>>& costs) {
    if (costs.empty()) return 0;

    int n = costs.size();
    int k = costs[0].size();

    for (int i = 1; i < n; ++i) {
        for (int j = 0; j < k; ++j) {
            int minCost = INT_MAX;
            for (int l = 0; l < k; ++l) {
                if (l == j) continue;
                minCost = min(minCost, costs[i - 1][l]);
            }
            costs[i][j] += minCost;
        }
    }
    return *min_element(costs[n - 1].begin(), costs[n - 1].end());
}
```
The algorithm stores the minimum cost to paint each house up to the current house with each color. Then for each house, it iterates through all the colors and calculates the minimum cost for painting that house with each color. It skips the same color as the previous house because no two adjacent houses can have the same color. After processing all the houses, the minimum of the last row in `costs` is the minimum cost to paint all the houses.

## A solution in Python

```python
def min_cost(costs: List[List[int]]) -> int:
    if not costs:
        return 0

    n, k = len(costs), len(costs[0])

    for i in range(1, n):
        for j in range(k):
            min_cost = float("inf")
            for l in range(k):
                if l == j:
                    continue
                min_cost = min(min_cost, costs[i - 1][l])
            costs[i][j] += min_cost

    return min(costs[n - 1])
```
The algorithm stores the minimum cost to paint each house up to the current house with each color. Then for each house, it iterates through all the colors and calculates the minimum cost for painting that house with each color. It skips the same color as the previous house because no two adjacent houses can have the same color. After processing all the houses, the minimum of the last row in `costs` is the minimum cost to paint all the houses.

## A solution in Javascript

```javascript
function minCost(costs) {
    if (!costs || costs.length === 0) return 0;

    const n = costs.length;
    const k = costs[0].length;

    for (let i = 1; i < n; i++) {
        for (let j = 0; j < k; j++) {
            let minCost = Number.MAX_VALUE;
            for (let l = 0; l < k; l++) {
                if (l === j) continue;
                minCost = Math.min(minCost, costs[i - 1][l]);
            }
            costs[i][j] += minCost;
        }
    }
    return Math.min(...costs[n - 1]);
}
```
The algorithm stores the minimum cost to paint each house up to the current house with each color. Then for each house, it iterates through all the colors and calculates the minimum cost for painting that house with each color. It skips the same color as the previous house because no two adjacent houses can have the same color. After processing all the houses, the minimum of the last row in `costs` is the minimum cost to paint all the houses.


# Palindrome Permutation

- slug: palindrome-permutation
- difficulty: Easy

Given a string `s`, return `true` _if a permutation of the string could form a_ _**palindrome**_ _and_ `false` _otherwise_.

**Example 1:**

**Input:** s =  "code "
**Output:** false

**Example 2:**

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

**Example 3:**

**Input:** s =  "carerac "
**Output:** true

**Constraints:**

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

## A solution in Java

```java
public boolean canPermutePalindrome(String s) {
    HashMap<Character, Integer> count = new HashMap<>();
    for(char c : s.toCharArray()) {
        count.put(c, count.getOrDefault(c, 0) + 1);
    }
    int odd_count = 0;
    for(int value : count.values()) {
        if (value % 2 != 0) {
            odd_count++;
        }
    }
    return odd_count <= 1;
}
```
The algorithm counts the occurrences of each character in the string using a hash map (or dictionary for Python). Then, it iterates through the count values in the hash map and checks how many characters have odd occurrences. If the string can form a palindrome, there should be at most one character having an odd number of occurrences.

The logic is based on the fact that a string can form a palindrome if it meets the following condition: If the string length is even, there should be an even number of occurrences for each character. If the string length is odd, there should be only one character having odd occurrences and the rest should have even occurrences.

The algorithm simply returns true if the odd_count is less than or equal to 1, indicating the string can form a palindrome; otherwise, it returns false.

## A solution in C++

```cpp
bool canPermutePalindrome(string s) {
    unordered_map<char, int> count;
    for (char c : s) {
        count[c]++;
    }
    int odd_count = 0;
    for (auto it = count.begin(); it != count.end(); ++it) {
        if (it->second % 2) {
            odd_count++;
        }
    }
    return odd_count <= 1;
}
```
The algorithm counts the occurrences of each character in the string using a hash map (or dictionary for Python). Then, it iterates through the count values in the hash map and checks how many characters have odd occurrences. If the string can form a palindrome, there should be at most one character having an odd number of occurrences.

The logic is based on the fact that a string can form a palindrome if it meets the following condition: If the string length is even, there should be an even number of occurrences for each character. If the string length is odd, there should be only one character having odd occurrences and the rest should have even occurrences.

The algorithm simply returns true if the odd_count is less than or equal to 1, indicating the string can form a palindrome; otherwise, it returns false.

## A solution in Python

```python
def canPermutePalindrome(s: str) -> bool:
    count = {}
    for c in s:
        if c in count:
            count[c] += 1
        else:
            count[c] = 1
    odd_count = 0
    for value in count.values():
        if value % 2:
            odd_count += 1
    return odd_count <= 1
```
The algorithm counts the occurrences of each character in the string using a hash map (or dictionary for Python). Then, it iterates through the count values in the hash map and checks how many characters have odd occurrences. If the string can form a palindrome, there should be at most one character having an odd number of occurrences.

The logic is based on the fact that a string can form a palindrome if it meets the following condition: If the string length is even, there should be an even number of occurrences for each character. If the string length is odd, there should be only one character having odd occurrences and the rest should have even occurrences.

The algorithm simply returns true if the odd_count is less than or equal to 1, indicating the string can form a palindrome; otherwise, it returns false.

## A solution in Javascript

```javascript
function canPermutePalindrome(s) {
    const count = {}
    for (const c of s) {
        if (c in count) {
            count[c]++;
        } else {
            count[c] = 1;
        }
    }
    let odd_count = 0;
    for (const value of Object.values(count)) {
        if (value % 2) {
            odd_count++;
        }
    }
    return odd_count <= 1;
}
```
The algorithm counts the occurrences of each character in the string using a hash map (or dictionary for Python). Then, it iterates through the count values in the hash map and checks how many characters have odd occurrences. If the string can form a palindrome, there should be at most one character having an odd number of occurrences.

The logic is based on the fact that a string can form a palindrome if it meets the following condition: If the string length is even, there should be an even number of occurrences for each character. If the string length is odd, there should be only one character having odd occurrences and the rest should have even occurrences.

The algorithm simply returns true if the odd_count is less than or equal to 1, indicating the string can form a palindrome; otherwise, it returns false.


# Palindrome Permutation II

- slug: palindrome-permutation-ii
- difficulty: Medium

Given a string s, return _all the palindromic permutations (without duplicates) of it_.

You may return the answer in **any order**. If `s` has no palindromic permutation, return an empty list.

**Example 1:**

**Input:** s = "aabb"
**Output:** \["abba","baab"\]

**Example 2:**

**Input:** s = "abc"
**Output:** \[\]

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

public class Solution {
    public List<String> generatePalindromes(String s) {
        List<String> result = new ArrayList<>();
        Map<Character, Integer> charCount = new HashMap<>();
        for (char c : s.toCharArray()) {
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);
        }

        String midChar = "";
        List<Character> halfChars = new ArrayList<>();
        int numOdds = 0;
        for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
            if (entry.getValue() % 2 == 1) {
                numOdds++;
                midChar = String.valueOf(entry.getKey());
            }
            for (int i = 0; i < entry.getValue() / 2; i++) {
                halfChars.add(entry.getKey());
            }

            if (numOdds > 1) {
                return result;
            }
        }

        permute(0, halfChars, midChar, new ArrayList<>(), result);
        return result;
    }

    private void permute(int idx, List<Character> halfChars, String midChar, List<Character> current, List<String> result) {
        if (idx == halfChars.size()) {
            String firstHalf = "".valueOf(current.toArray(new Character[0]));
            result.add(firstHalf + midChar + new StringBuilder(firstHalf).reverse());
            return;
        }

        for (int i = 0; i < halfChars.size(); i++) {
            if (i > 0 && halfChars.get(i) == halfChars.get(i - 1)) {
                continue;
            }
            Character c = halfChars.remove(i);
            current.add(c);
            permute(idx + 1, halfChars, midChar, current, result);
            current.remove(current.size() - 1);
            halfChars.add(i, c);
        }
    }
}
```
1. Count the occurrences of each character in the given string `s`.
2. If there are more than one odd counts for any character, there can't be a palindrome, so return an empty list.
3. Create two parts of the palindrome, `halfStr` and `midChar`. The `halfStr` will contain half of `s` divided by character counts, and `midChar` will contain the middle character if `s` has an odd length.
4. Generate all unique permutations of `halfStr`.
5. For each permutation of `halfStr`, concatenate it with `midChar` and its reverse to create a palindrome and add it to the result list.
6. Return the result list.

## A solution in C++

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

using namespace std;

vector<string> generatePalindromes(string s) {
    unordered_map<char, int> charCount;
    for (const char &c : s) {
        charCount[c]++;
    }

    int numOdds = 0;
    string halfStr = "", midChar = "";
    for (const auto &entry : charCount) {
        if (entry.second % 2 == 1) {
            numOdds++;
            midChar = entry.first;
        }
        halfStr += string(entry.second / 2, entry.first);

        if (numOdds > 1) {
            return {};
        }
    }

    vector<string> result;
    sort(halfStr.begin(), halfStr.end());
    do {
        string palindrome = halfStr + midChar + string(halfStr.rbegin(), halfStr.rend());
        result.push_back(palindrome);
    } while (next_permutation(halfStr.begin(), halfStr.end()));

    return result;
}
```
1. Count the occurrences of each character in the given string `s`.
2. If there are more than one odd counts for any character, there can't be a palindrome, so return an empty list.
3. Create two parts of the palindrome, `halfStr` and `midChar`. The `halfStr` will contain half of `s` divided by character counts, and `midChar` will contain the middle character if `s` has an odd length.
4. Generate all unique permutations of `halfStr`.
5. For each permutation of `halfStr`, concatenate it with `midChar` and its reverse to create a palindrome and add it to the result list.
6. Return the result list.

## A solution in Python

```python
from collections import Counter
from itertools import permutations

def generatePalindromes(s):
    result = []
    char_count = Counter(s)

    mid_char = ""
    half_str = []
    num_ocurrences = 0

    for char, count in char_count.items():
        if count % 2 == 1:
            num_ocurrences += 1
            mid_char = char
        half_str.extend([char] * (count // 2))

        if num_ocurrences > 1:
            return result

    for perm in set(permutations(half_str)):
        palindrome = "".join(perm) + mid_char + "".join(reversed(perm))
        result.append(palindrome)

    return result
```
1. Count the occurrences of each character in the given string `s`.
2. If there are more than one odd counts for any character, there can't be a palindrome, so return an empty list.
3. Create two parts of the palindrome, `halfStr` and `midChar`. The `halfStr` will contain half of `s` divided by character counts, and `midChar` will contain the middle character if `s` has an odd length.
4. Generate all unique permutations of `halfStr`.
5. For each permutation of `halfStr`, concatenate it with `midChar` and its reverse to create a palindrome and add it to the result list.
6. Return the result list.

## A solution in Javascript

```javascript
function generatePalindromes(s) {
    let result = [];
    let charCount = new Map();
    for (const c of s) {
        charCount.set(c, (charCount.get(c) || 0) + 1);
    }

    let midChar = "";
    let halfChars = [];
    let numOdds = 0;
    charCount.forEach((count, char) => {
        if (count % 2 === 1) {
            numOdds++;
            midChar = char;
        }
        for (let i = 0; i < Math.floor(count / 2); i++) {
            halfChars.push(char);
        }

        if (numOdds > 1) {
            return [];
        }
    });

    function btPerm(idx, current) {
        if (idx === halfChars.length) {
            const firstHalf = current.join('');
            result.push(firstHalf + midChar + firstHalf.split('').reverse().join(''));
            return;
        }

        for (let i = 0; i < halfChars.length; i++) {
            if (i > 0 && halfChars[i] === halfChars[i - 1]) {
                continue;
            }
            const char = halfChars.splice(i, 1)[0];
            current.push(char);
            btPerm(idx + 1, current);
            current.pop();
            halfChars.splice(i, 0, char);
        }
    }

    halfChars.sort();
    btPerm(0, []);

    return result;
}
```
1. Count the occurrences of each character in the given string `s`.
2. If there are more than one odd counts for any character, there can't be a palindrome, so return an empty list.
3. Create two parts of the palindrome, `halfStr` and `midChar`. The `halfStr` will contain half of `s` divided by character counts, and `midChar` will contain the middle character if `s` has an odd length.
4. Generate all unique permutations of `halfStr`.
5. For each permutation of `halfStr`, concatenate it with `midChar` and its reverse to create a palindrome and add it to the result list.
6. Return the result list.


# Missing Number

- slug: missing-number
- difficulty: Easy

Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return _the only number in the range that is missing from the array._

**Example 1:**

**Input:** nums = \[3,0,1\]
**Output:** 2
**Explanation:** n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums.

**Example 2:**

**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the missing number in the range since it does not appear in nums.

**Example 3:**

**Input:** nums = \[9,6,4,2,3,5,7,0,1\]
**Output:** 8
**Explanation:** n = 9 since there are 9 numbers, so all numbers are in the range \[0,9\]. 8 is the missing number in the range since it does not appear in nums.

**Constraints:**

*   `n == nums.length`
*   `1 <= n <= 104`
*   `0 <= nums[i] <= n`
*   All the numbers of `nums` are **unique**.

**Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity?

## A solution in Java

```java
public int missingNumber(int[] nums) {
    int n = nums.length;
    int expectedSum = (n * (n + 1)) / 2;
    int actualSum = 0;
    for (int num : nums) {
        actualSum += num;
    }
    return expectedSum - actualSum;
}
```
The algorithm calculates the expected sum of integers in the range [0, n] using the formula n * (n + 1) / 2. Then, it calculates the actual sum of the integers in the given array. Finally, it returns the difference between the expected sum and the actual sum, which represents the missing number in the range.

## A solution in C++

```cpp
int missingNumber(vector<int>& nums) {
    int n = nums.size();
    int expected_sum = (n * (n + 1)) / 2;
    int actual_sum = 0;
    for (int num : nums) {
        actual_sum += num;
    }
    return expected_sum - actual_sum;
}
```
The algorithm calculates the expected sum of integers in the range [0, n] using the formula n * (n + 1) / 2. Then, it calculates the actual sum of the integers in the given array. Finally, it returns the difference between the expected sum and the actual sum, which represents the missing number in the range.

## A solution in Python

```python
def missingNumber(nums):
    n = len(nums)
    expected_sum = (n * (n + 1)) // 2
    actual_sum = sum(nums)
    return expected_sum - actual_sum
```
The algorithm calculates the expected sum of integers in the range [0, n] using the formula n * (n + 1) / 2. Then, it calculates the actual sum of the integers in the given array. Finally, it returns the difference between the expected sum and the actual sum, which represents the missing number in the range.

## A solution in Javascript

```javascript
function missingNumber(nums) {
    const n = nums.length;
    const expectedSum = (n * (n + 1)) / 2;
    const actualSum = nums.reduce((acc, num) => acc + num, 0);
    return expectedSum - actualSum;
}
```
The algorithm calculates the expected sum of integers in the range [0, n] using the formula n * (n + 1) / 2. Then, it calculates the actual sum of the integers in the given array. Finally, it returns the difference between the expected sum and the actual sum, which represents the missing number in the range.


# Alien Dictionary

- slug: alien-dictionary
- difficulty: Hard

There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.

You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language.

Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_.

**Example 1:**

**Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\]
**Output:**  "wertf "

**Example 2:**

**Input:** words = \[ "z ", "x "\]
**Output:**  "zx "

**Example 3:**

**Input:** words = \[ "z ", "x ", "z "\]
**Output:**  " "
**Explanation:** The order is invalid, so return ` " "`.

**Constraints:**

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

## A solution in Java

```java
import java.util.*;

public String alienOrder(String[] words) {
    Map<Character, Set<Character>> graph = new HashMap<>();
    Map<Character, Integer> inDegree = new HashMap<>();

    for (String word : words) {
        for (char c : word.toCharArray())
            inDegree.put(c, 0);
    }

    for (int i = 0; i < words.length - 1; i++) {
        String word1 = words[i], word2 = words[i + 1];

        boolean found = false;
        for (int j = 0; j < Math.min(word1.length(), word2.length()); j++) {
            char c1 = word1.charAt(j), c2 = word2.charAt(j);
            if (c1 != c2) {
                graph.putIfAbsent(c1, new HashSet<>());
                if (!graph.get(c1).contains(c2)) {
                    graph.get(c1).add(c2);
                    inDegree.put(c2, inDegree.get(c2) + 1);
                }
                found = true;
                break;
            }
        }

        if (!found && word1.length() > word2.length())
            return "";
    }

    Queue<Character> q = new LinkedList<>();
    for (Map.Entry<Character, Integer> entry : inDegree.entrySet())
        if (entry.getValue() == 0)
            q.offer(entry.getKey());

    StringBuilder result = new StringBuilder();
    while (!q.isEmpty()) {
        char c = q.poll();
        result.append(c);

        if (graph.containsKey(c)) {
            for (char neigh : graph.get(c)) {
                inDegree.put(neigh, inDegree.get(neigh) - 1);
                if (inDegree.get(neigh) == 0)
                    q.offer(neigh);
            }
        }
    }

    if (result.length() < inDegree.size())
        return "";

    return result.toString();
}
```
The algorithm uses the topological sorting algorithm with an adjacency list to represent the directed graph. The directed graph's vertices represent each unique character from the words array, and a directed edge between two vertices indicates that the first character appears before the second character in the alien language's dictionary.

It first initializes an adjacency list `graph`, an in-degree HashMap `inDegree` to store the in-degree of each character, and fills the HashMap with the unique characters from the words array, setting the initial in-degree of each character to 0. Then, it iterates through adjacent word pairs from the `words` array and adjacent character pairs from those word pairs, checking if they form an edge in the graph (i.e., the characters are different). If an edge is found, it is added to the graph, and the in-degree of the second character in the pair is incremented. In case we traverse through equal characters and later find the second string is shorter, we return an empty string as this indicates an invalid order.

To find the lexicographical order, we can use the topological sorting algorithm. We initialize a queue to store the characters with an in-degree of 0 (i.e. they have no incoming edges) and perform the following steps until the queue is empty:

1. Pop the front character from the queue and append it to the result string.
2. Iterate over all the neighbors of the popped character in the graph.
3. Decrement the in-degree of each neighbor.
4. Check if the in-degree of the neighbor is 0; if it is, push the character onto the queue.

Finally, if the length of the result string is less than the number of unique characters, return an empty string as it indicates there's no valid lexicographical order. Otherwise, return the result string.

## A solution in C++

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

std::string alienOrder(std::vector<std::string> &words) {
    std::unordered_map<char, std::unordered_set<char>> graph;
    std::unordered_map<char, int> inDegree;

    for (const std::string &word : words)
        for (char c : word)
            inDegree[c] = 0;

    for (int i = 0; i < words.size() - 1; i++) {
        std::string word1 = words[i], word2 = words[i + 1];

        bool found = false;
        for (int j = 0; j < std::min(word1.size(), word2.size()); j++) {
            char c1 = word1[j], c2 = word2[j];
            if (c1 != c2) {
                if (!graph[c1].count(c2)) {
                    graph[c1].insert(c2);
                    inDegree[c2]++;
                }
                found = true;
                break;
            }
        }

        if (!found && word1.size() > word2.size())
            return "";
    }

    std::queue<char> q;
    for (auto &[c, deg] : inDegree)
        if (deg == 0)
            q.push(c);

    std::string result;
    while (!q.empty()) {
        char c = q.front();
        q.pop();
        result += c;

        for (char neigh : graph[c]) {
            inDegree[neigh]--;
            if (inDegree[neigh] == 0)
                q.push(neigh);
        }
    }

    if (result.size() < inDegree.size())
        return "";

    return result;
}
```
The algorithm uses the topological sorting algorithm with an adjacency list to represent the directed graph. The directed graph's vertices represent each unique character from the words array, and a directed edge between two vertices indicates that the first character appears before the second character in the alien language's dictionary.

It first initializes an adjacency list `graph`, an in-degree HashMap `inDegree` to store the in-degree of each character, and fills the HashMap with the unique characters from the words array, setting the initial in-degree of each character to 0. Then, it iterates through adjacent word pairs from the `words` array and adjacent character pairs from those word pairs, checking if they form an edge in the graph (i.e., the characters are different). If an edge is found, it is added to the graph, and the in-degree of the second character in the pair is incremented. In case we traverse through equal characters and later find the second string is shorter, we return an empty string as this indicates an invalid order.

To find the lexicographical order, we can use the topological sorting algorithm. We initialize a queue to store the characters with an in-degree of 0 (i.e. they have no incoming edges) and perform the following steps until the queue is empty:

1. Pop the front character from the queue and append it to the result string.
2. Iterate over all the neighbors of the popped character in the graph.
3. Decrement the in-degree of each neighbor.
4. Check if the in-degree of the neighbor is 0; if it is, push the character onto the queue.

Finally, if the length of the result string is less than the number of unique characters, return an empty string as it indicates there's no valid lexicographical order. Otherwise, return the result string.

## A solution in Python

```python
from collections import deque, defaultdict, Counter

def alienOrder(words):
    graph = defaultdict(set)
    in_degree = Counter({c: 0 for word in words for c in word})

    for word1, word2 in zip(words, words[1:]):
        found = False
        for c1, c2 in zip(word1, word2):
            if c1 != c2:
                if c2 not in graph[c1]:
                    graph[c1].add(c2)
                    in_degree[c2] += 1
                found = True
                break
        if not found and len(word1) > len(word2):
            return ""

    q = deque([c for c in in_degree if in_degree[c] == 0])
    result = []
    while q:
        c = q.popleft()
        result.append(c)

        for neigh in graph[c]:
            in_degree[neigh] -= 1
            if in_degree[neigh] == 0:
                q.append(neigh)

    if len(result) < len(in_degree):
        return ""

    return "".join(result)
```
The algorithm uses the topological sorting algorithm with an adjacency list to represent the directed graph. The directed graph's vertices represent each unique character from the words array, and a directed edge between two vertices indicates that the first character appears before the second character in the alien language's dictionary.

It first initializes an adjacency list `graph`, an in-degree HashMap `inDegree` to store the in-degree of each character, and fills the HashMap with the unique characters from the words array, setting the initial in-degree of each character to 0. Then, it iterates through adjacent word pairs from the `words` array and adjacent character pairs from those word pairs, checking if they form an edge in the graph (i.e., the characters are different). If an edge is found, it is added to the graph, and the in-degree of the second character in the pair is incremented. In case we traverse through equal characters and later find the second string is shorter, we return an empty string as this indicates an invalid order.

To find the lexicographical order, we can use the topological sorting algorithm. We initialize a queue to store the characters with an in-degree of 0 (i.e. they have no incoming edges) and perform the following steps until the queue is empty:

1. Pop the front character from the queue and append it to the result string.
2. Iterate over all the neighbors of the popped character in the graph.
3. Decrement the in-degree of each neighbor.
4. Check if the in-degree of the neighbor is 0; if it is, push the character onto the queue.

Finally, if the length of the result string is less than the number of unique characters, return an empty string as it indicates there's no valid lexicographical order. Otherwise, return the result string.

## A solution in Javascript

```javascript
function alienOrder(words) {
    const graph = new Map();
    const inDegree = new Map();

    for (const word of words)
        for (const c of word)
            inDegree.set(c, 0);

    for (let i = 0; i < words.length - 1; i++) {
        const word1 = words[i], word2 = words[i + 1];

        let found = false;
        for (let j = 0; j < Math.min(word1.length, word2.length); j++) {
            const c1 = word1[j], c2 = word2[j];
            if (c1 !== c2) {
                if (!graph.has(c1)) graph.set(c1, new Set());
                if (!graph.get(c1).has(c2)) {
                    graph.get(c1).add(c2);
                    inDegree.set(c2, inDegree.get(c2) + 1);
                }
                found = true;
                break;
            }
        }

        if (!found && word1.length > word2.length)
            return "";
    }

    const q = [];
    for (const [c, deg] of inDegree.entries())
        if (deg === 0)
            q.push(c);

    let result = "";
    while (q.length) {
        const c = q.shift();
        result += c;

        if (graph.has(c)) {
            for (const neigh of graph.get(c)) {
                inDegree.set(neigh, inDegree.get(neigh) - 1);
                if (inDegree.get(neigh) === 0)
                    q.push(neigh);
            }
        }
    }

    if (result.length < inDegree.size)
        return "";

    return result;
}
```
The algorithm uses the topological sorting algorithm with an adjacency list to represent the directed graph. The directed graph's vertices represent each unique character from the words array, and a directed edge between two vertices indicates that the first character appears before the second character in the alien language's dictionary.

It first initializes an adjacency list `graph`, an in-degree HashMap `inDegree` to store the in-degree of each character, and fills the HashMap with the unique characters from the words array, setting the initial in-degree of each character to 0. Then, it iterates through adjacent word pairs from the `words` array and adjacent character pairs from those word pairs, checking if they form an edge in the graph (i.e., the characters are different). If an edge is found, it is added to the graph, and the in-degree of the second character in the pair is incremented. In case we traverse through equal characters and later find the second string is shorter, we return an empty string as this indicates an invalid order.

To find the lexicographical order, we can use the topological sorting algorithm. We initialize a queue to store the characters with an in-degree of 0 (i.e. they have no incoming edges) and perform the following steps until the queue is empty:

1. Pop the front character from the queue and append it to the result string.
2. Iterate over all the neighbors of the popped character in the graph.
3. Decrement the in-degree of each neighbor.
4. Check if the in-degree of the neighbor is 0; if it is, push the character onto the queue.

Finally, if the length of the result string is less than the number of unique characters, return an empty string as it indicates there's no valid lexicographical order. Otherwise, return the result string.


# Closest Binary Search Tree Value

- slug: closest-binary-search-tree-value
- difficulty: Easy

Given the `root` of a binary search tree and a `target` value, return _the value in the BST that is closest to the_ `target`. If there are multiple answers, print the smallest.

**Example 1:**

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

**Example 2:**

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

**Constraints:**

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

## A solution in Java

```java
class Solution {
    public int closestValue(TreeNode root, double target) {
        int closest = root.val;
        while (root != null) {
            if (Math.abs(target - closest) > Math.abs(target - root.val)) {
                closest = root.val;
            }
            root = target < root.val ? root.left : root.right;
        }
        return closest;
    }
}
```
The algorithm uses a while loop to traverse the binary search tree. During the iteration, we continuously update the closest variable with the current node's value if the current node's value is closer to the target than the previous closest value. The algorithm follows the binary search tree's property, taking the left branch if the target is less than the current node's value and the right branch if the target is greater than the current node's value. On reaching a null node, the algorithm terminates and returns the closest value found.

## A solution in C++

```cpp
class Solution {
public:
    int closestValue(TreeNode* root, double target) {
        int closest = root->val;
        while (root != nullptr) {
            if (abs(target - closest) > abs(target - root->val)) {
                closest = root->val;
            }
            root = target < root->val ? root->left : root->right;
        }
        return closest;
    }
};
```
The algorithm uses a while loop to traverse the binary search tree. During the iteration, we continuously update the closest variable with the current node's value if the current node's value is closer to the target than the previous closest value. The algorithm follows the binary search tree's property, taking the left branch if the target is less than the current node's value and the right branch if the target is greater than the current node's value. On reaching a null node, the algorithm terminates and returns the closest value found.

## A solution in Python

```python
class Solution:
    def closestValue(self, root: TreeNode, target: float) -> int:
        closest = root.val
        while root:
            if abs(target - closest) > abs(target - root.val):
                closest = root.val
            root = root.left if target < root.val else root.right
        return closest
```
The algorithm uses a while loop to traverse the binary search tree. During the iteration, we continuously update the closest variable with the current node's value if the current node's value is closer to the target than the previous closest value. The algorithm follows the binary search tree's property, taking the left branch if the target is less than the current node's value and the right branch if the target is greater than the current node's value. On reaching a null node, the algorithm terminates and returns the closest value found.

## A solution in Javascript

```javascript
var closestValue = function(root, target) {
    let closest = root.val;
    while (root !== null) {
        if (Math.abs(target - closest) > Math.abs(target - root.val)) {
            closest = root.val;
        }
        root = target < root.val ? root.left : root.right;
    }
    return closest;
};
```
The algorithm uses a while loop to traverse the binary search tree. During the iteration, we continuously update the closest variable with the current node's value if the current node's value is closer to the target than the previous closest value. The algorithm follows the binary search tree's property, taking the left branch if the target is less than the current node's value and the right branch if the target is greater than the current node's value. On reaching a null node, the algorithm terminates and returns the closest value found.