# Distribute Candies

- slug: distribute-candies
- difficulty: Easy

Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor.

The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.

Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_.

**Example 1:**

**Input:** candyType = \[1,1,2,2,3,3\]
**Output:** 3
**Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.

**Example 2:**

**Input:** candyType = \[1,1,2,3\]
**Output:** 2
**Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types \[1,2\], \[1,3\], or \[2,3\], she still can only eat 2 different types.

**Example 3:**

**Input:** candyType = \[6,6,6,6\]
**Output:** 1
**Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.

**Constraints:**

*   `n == candyType.length`
*   `2 <= n <= 104`
*   `n` is even.
*   `-105 <= candyType[i] <= 105`

## A solution in Java

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

public int maxNumberOfCandies(int[] candyType) {
    Set<Integer> uniqueCandies = new HashSet<>();
    for (int type : candyType) {
        uniqueCandies.add(type);
    }
    return Math.min(uniqueCandies.size(), candyType.length / 2);
}
```
The algorithm starts by first creating a set of unique candy types using a hash set (in C++ and Java) or a set (in Python and JavaScript). The uniqueCandies set will only store each type of candy once, no matter how many times it appears in the candyType array. After creating this set, the algorithm compares the number of unique types of candies (size of the set) with half the total number of candies (n / 2). The minimum of these two values is returned as the maximum number of different types of candies Alice can eat. This is because Alice can eat at most n / 2 candies, but if there are fewer unique candies than that, she will eat all the unique types available.

## A solution in C++

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

int maxNumberOfCandies(vector<int>& candyType) {
    unordered_set<int> uniqueCandies(candyType.begin(), candyType.end());
    return min(uniqueCandies.size(), candyType.size() / 2);
}
```
The algorithm starts by first creating a set of unique candy types using a hash set (in C++ and Java) or a set (in Python and JavaScript). The uniqueCandies set will only store each type of candy once, no matter how many times it appears in the candyType array. After creating this set, the algorithm compares the number of unique types of candies (size of the set) with half the total number of candies (n / 2). The minimum of these two values is returned as the maximum number of different types of candies Alice can eat. This is because Alice can eat at most n / 2 candies, but if there are fewer unique candies than that, she will eat all the unique types available.

## A solution in Python

```python
def maxNumberOfCandies(candyType):
    uniqueCandies = set(candyType)
    return min(len(uniqueCandies), len(candyType) // 2)
```
The algorithm starts by first creating a set of unique candy types using a hash set (in C++ and Java) or a set (in Python and JavaScript). The uniqueCandies set will only store each type of candy once, no matter how many times it appears in the candyType array. After creating this set, the algorithm compares the number of unique types of candies (size of the set) with half the total number of candies (n / 2). The minimum of these two values is returned as the maximum number of different types of candies Alice can eat. This is because Alice can eat at most n / 2 candies, but if there are fewer unique candies than that, she will eat all the unique types available.

## A solution in Javascript

```javascript
function maxNumberOfCandies(candyType) {
    const uniqueCandies = new Set(candyType);
    return Math.min(uniqueCandies.size, candyType.length / 2);
}
```
The algorithm starts by first creating a set of unique candy types using a hash set (in C++ and Java) or a set (in Python and JavaScript). The uniqueCandies set will only store each type of candy once, no matter how many times it appears in the candyType array. After creating this set, the algorithm compares the number of unique types of candies (size of the set) with half the total number of candies (n / 2). The minimum of these two values is returned as the maximum number of different types of candies Alice can eat. This is because Alice can eat at most n / 2 candies, but if there are fewer unique candies than that, she will eat all the unique types available.


# Out of Boundary Paths

- slug: out-of-boundary-paths
- difficulty: Medium

There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball.

Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`.

**Example 1:**

**Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
**Output:** 6

**Example 2:**

**Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
**Output:** 12

**Constraints:**

*   `1 <= m, n <= 50`
*   `0 <= maxMove <= 50`
*   `0 <= startRow < m`
*   `0 <= startColumn < n`

## A solution in Java

```java
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
    int MOD = 1000000007;
    int[][][] dp = new int[maxMove + 1][m][n];
    int[][] moves = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    for (int k = 1; k <= maxMove; k++) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                for (int[] move : moves) {
                    int ni = i + move[0], nj = j + move[1];
                    if (ni < 0 || ni >= m || nj < 0 || nj >= n) {
                        dp[k][i][j] = (dp[k][i][j] + 1) % MOD;
                    } else {
                        dp[k][i][j] = (dp[k][i][j] + dp[k - 1][ni][nj]) % MOD;
                    }
                }
            }
        }
    }
    return dp[maxMove][startRow][startColumn];
}
```
We use dynamic programming to accumulate the ways to move the ball up to the maximum allowed moves. The `dp` array has dimensions `maxMove + 1` by `m` by `n`, where `dp[k][i][j]` represents the number of ways the ball can reach position `(i, j)` in exactly `k` moves.

We loop through moves from `1` to `maxMove`, and then loop through each cell of the grid. For each cell, we check each possible move direction. If moving in that direction causes the ball to cross the grid boundary (i.e., the new coordinates are outside of the grid), we increment the number of ways to move in exactly `k` moves by `1`. If the new coordinates are inside the grid, we add the number of ways to move to the new position in exactly `k - 1` moves to our current ways. We do this modulo `10^9 + 7` to prevent integer overflow.

Finally, we return the number of ways to move the ball out of the grid boundary in exactly `maxMove` moves, which is stored at `dp[maxMove][startRow][startColumn]`.

## A solution in C++

```cpp
int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
    int MOD = 1e9 + 7;
    vector<vector<vector<int>>> dp(maxMove + 1, vector<vector<int>>(m, vector<int>(n, 0)));
    int moves[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    for (int k = 1; k <= maxMove; k++) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                for (auto move : moves) {
                    int ni = i + move[0], nj = j + move[1];
                    if (ni < 0 || ni >= m || nj < 0 || nj >= n) {
                        dp[k][i][j] = (dp[k][i][j] + 1) % MOD;
                    } else {
                        dp[k][i][j] = (dp[k][i][j] + dp[k - 1][ni][nj]) % MOD;
                    }
                }
            }
        }
    }
    return dp[maxMove][startRow][startColumn];
}
```
We use dynamic programming to accumulate the ways to move the ball up to the maximum allowed moves. The `dp` array has dimensions `maxMove + 1` by `m` by `n`, where `dp[k][i][j]` represents the number of ways the ball can reach position `(i, j)` in exactly `k` moves.

We loop through moves from `1` to `maxMove`, and then loop through each cell of the grid. For each cell, we check each possible move direction. If moving in that direction causes the ball to cross the grid boundary (i.e., the new coordinates are outside of the grid), we increment the number of ways to move in exactly `k` moves by `1`. If the new coordinates are inside the grid, we add the number of ways to move to the new position in exactly `k - 1` moves to our current ways. We do this modulo `10^9 + 7` to prevent integer overflow.

Finally, we return the number of ways to move the ball out of the grid boundary in exactly `maxMove` moves, which is stored at `dp[maxMove][startRow][startColumn]`.

## A solution in Python

```python
def findPaths(m, n, maxMove, startRow, startColumn):
    MOD = 10**9 + 7
    dp = [[[0]* n for _ in range(m)] for _ in range(maxMove + 1)]
    moves = ((-1, 0), (1, 0), (0, -1), (0, 1))

    for k in range(1, maxMove + 1):
        for i in range(m):
            for j in range(n):
                for move in moves:
                    ni, nj = i + move[0], j + move[1]
                    if ni < 0 or ni >= m or nj < 0 or nj >= n:
                        dp[k][i][j] = (dp[k][i][j] + 1) % MOD
                    else:
                        dp[k][i][j] = (dp[k][i][j] + dp[k - 1][ni][nj]) % MOD

    return dp[maxMove][startRow][startColumn]
```
We use dynamic programming to accumulate the ways to move the ball up to the maximum allowed moves. The `dp` array has dimensions `maxMove + 1` by `m` by `n`, where `dp[k][i][j]` represents the number of ways the ball can reach position `(i, j)` in exactly `k` moves.

We loop through moves from `1` to `maxMove`, and then loop through each cell of the grid. For each cell, we check each possible move direction. If moving in that direction causes the ball to cross the grid boundary (i.e., the new coordinates are outside of the grid), we increment the number of ways to move in exactly `k` moves by `1`. If the new coordinates are inside the grid, we add the number of ways to move to the new position in exactly `k - 1` moves to our current ways. We do this modulo `10^9 + 7` to prevent integer overflow.

Finally, we return the number of ways to move the ball out of the grid boundary in exactly `maxMove` moves, which is stored at `dp[maxMove][startRow][startColumn]`.

## A solution in Javascript

```javascript
function findPaths(m, n, maxMove, startRow, startColumn) {
    const MOD = 1e9 + 7;
    let dp = new Array(maxMove + 1).fill(0).map(() => new Array(m).fill(0).map(() => new Array(n).fill(0)));
    let moves = [[-1, 0], [1, 0], [0, -1], [0, 1]];

    for (let k = 1; k <= maxMove; k++) {
        for (let i = 0; i < m; i++) {
            for (let j = 0; j < n; j++) {
                for (let move of moves) {
                    let ni = i + move[0], nj = j + move[1];
                    if (ni < 0 || ni >= m || nj < 0 || nj >= n) {
                        dp[k][i][j] = (dp[k][i][j] + 1) % MOD;
                    } else {
                        dp[k][i][j] = (dp[k][i][j] + dp[k - 1][ni][nj]) % MOD;
                    }
                }
            }
        }
    }
    return dp[maxMove][startRow][startColumn];
}
```
We use dynamic programming to accumulate the ways to move the ball up to the maximum allowed moves. The `dp` array has dimensions `maxMove + 1` by `m` by `n`, where `dp[k][i][j]` represents the number of ways the ball can reach position `(i, j)` in exactly `k` moves.

We loop through moves from `1` to `maxMove`, and then loop through each cell of the grid. For each cell, we check each possible move direction. If moving in that direction causes the ball to cross the grid boundary (i.e., the new coordinates are outside of the grid), we increment the number of ways to move in exactly `k` moves by `1`. If the new coordinates are inside the grid, we add the number of ways to move to the new position in exactly `k - 1` moves to our current ways. We do this modulo `10^9 + 7` to prevent integer overflow.

Finally, we return the number of ways to move the ball out of the grid boundary in exactly `maxMove` moves, which is stored at `dp[maxMove][startRow][startColumn]`.


# Shortest Unsorted Continuous Subarray

- slug: shortest-unsorted-continuous-subarray
- difficulty: Medium

Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return _the shortest such subarray and output its length_.

**Example 1:**

**Input:** nums = \[2,6,4,8,10,9,15\]
**Output:** 5
**Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order.

**Example 2:**

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

**Example 3:**

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

**Constraints:**

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

**Follow up:** Can you solve it in `O(n)` time complexity?

## A solution in Java

```java
import java.util.Arrays;

public int findUnsortedSubarray(int[] nums) {
    int[] sortedNums = nums.clone();
    Arrays.sort(sortedNums);
    int start = 0, end = nums.length - 1;
    while (start < nums.length && nums[start] == sortedNums[start]) start++;
    while (end > start && nums[end] == sortedNums[end]) end--;
    return end - start + 1;
}
```
1. Create a copy of the input array and sort it in ascending order.
2. Initialize two variables, `start` and `end`, to check the boundaries of the unsorted subarray.
3. Loop through the array, comparing the sorted copy and the original array. When we encounter a mismatch at some index, we break the loop and store the index in `start`. This `start` index is the beginning of the unsorted subarray.
4. Similarly, we start from the end of the array and find the first mismatch. We store this index in `end`. This `end` index is the boundary of the unsorted subarray.
5. Calculate the length of the unsorted subarray as `end - start + 1`.

## A solution in C++

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

int findUnsortedSubarray(vector<int>& nums) {
    vector<int> sorted_nums(nums);
    sort(sorted_nums.begin(), sorted_nums.end());
    int start = 0, end = nums.size() - 1;
    while (start < nums.size() && nums[start] == sorted_nums[start]) start++;
    while (end > start && nums[end] == sorted_nums[end]) end--;
    return end - start + 1;
}
```
1. Create a copy of the input array and sort it in ascending order.
2. Initialize two variables, `start` and `end`, to check the boundaries of the unsorted subarray.
3. Loop through the array, comparing the sorted copy and the original array. When we encounter a mismatch at some index, we break the loop and store the index in `start`. This `start` index is the beginning of the unsorted subarray.
4. Similarly, we start from the end of the array and find the first mismatch. We store this index in `end`. This `end` index is the boundary of the unsorted subarray.
5. Calculate the length of the unsorted subarray as `end - start + 1`.

## A solution in Python

```python
def findUnsortedSubarray(nums):
    sorted_nums = sorted(nums)
    start, end = 0, len(nums) - 1
    while start < len(nums) and nums[start] == sorted_nums[start]:
        start += 1
    while end > start and nums[end] == sorted_nums[end]:
        end -= 1
    return end - start + 1
```
1. Create a copy of the input array and sort it in ascending order.
2. Initialize two variables, `start` and `end`, to check the boundaries of the unsorted subarray.
3. Loop through the array, comparing the sorted copy and the original array. When we encounter a mismatch at some index, we break the loop and store the index in `start`. This `start` index is the beginning of the unsorted subarray.
4. Similarly, we start from the end of the array and find the first mismatch. We store this index in `end`. This `end` index is the boundary of the unsorted subarray.
5. Calculate the length of the unsorted subarray as `end - start + 1`.

## A solution in Javascript

```javascript
function findUnsortedSubarray(nums) {
    const sortedNums = [...nums].sort((a, b) => a - b);
    let start = 0, end = nums.length - 1;
    while (start < nums.length && nums[start] === sortedNums[start]) start++;
    while (end > start && nums[end] === sortedNums[end]) end--;
    return end - start + 1;
}
```
1. Create a copy of the input array and sort it in ascending order.
2. Initialize two variables, `start` and `end`, to check the boundaries of the unsorted subarray.
3. Loop through the array, comparing the sorted copy and the original array. When we encounter a mismatch at some index, we break the loop and store the index in `start`. This `start` index is the beginning of the unsorted subarray.
4. Similarly, we start from the end of the array and find the first mismatch. We store this index in `end`. This `end` index is the boundary of the unsorted subarray.
5. Calculate the length of the unsorted subarray as `end - start + 1`.


# Kill Process

- slug: kill-process
- difficulty: Medium

You have `n` processes forming a rooted tree structure. You are given two integer arrays `pid` and `ppid`, where `pid[i]` is the ID of the `ith` process and `ppid[i]` is the ID of the `ith` process's parent process.

Each process has only **one parent process** but may have multiple children processes. Only one process has `ppid[i] = 0`, which means this process has **no parent process** (the root of the tree).

When a process is **killed**, all of its children processes will also be killed.

Given an integer `kill` representing the ID of a process you want to kill, return _a list of the IDs of the processes that will be killed. You may return the answer in **any order**._

**Example 1:**

**Input:** pid = \[1,3,10,5\], ppid = \[3,0,5,3\], kill = 5
**Output:** \[5,10\]
**Explanation:** The processes colored in red are the processes that should be killed.

**Example 2:**

**Input:** pid = \[1\], ppid = \[0\], kill = 1
**Output:** \[1\]

**Constraints:**

*   `n == pid.length`
*   `n == ppid.length`
*   `1 <= n <= 5 * 104`
*   `1 <= pid[i] <= 5 * 104`
*   `0 <= ppid[i] <= 5 * 104`
*   Only one process has no parent.
*   All the values of `pid` are **unique**.
*   `kill` is **guaranteed** to be in `pid`.

## A solution in Java

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

public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
    Map<Integer, List<Integer>> children = new HashMap<>();
    for (int i = 0; i < pid.size(); i++) {
        children.computeIfAbsent(ppid.get(i), k -> new ArrayList<>()).add(pid.get(i));
    }

    List<Integer> killed = new ArrayList<>();
    dfs(kill, children, killed);
    return killed;
}

private void dfs(int id, Map<Integer, List<Integer>> children, List<Integer> killed) {
    killed.add(id);
    for (int child : children.getOrDefault(id, new ArrayList<>())) {
        dfs(child, children, killed);
    }
}
```
We use a hash map (unordered_map in C++, HashMap in Java, defaultdict in Python, Map in JavaScript) to store the children of each process. We iterate through the `pid` and `ppid` arrays to construct a tree-like data structure in the `children` map.

We then perform a depth-first search (DFS) starting from the `kill` process to traverse the tree and add all the processes to the `killed` list. The DFS function is implemented in a recursive manner, where we first add the current process id to the list `killed` and then iterate through its children.

We call the `dfs` function with the `kill` process id to construct the `killed` list and then return it.

## A solution in C++

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

vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
    unordered_map<int, vector<int>> children;
    for (int i = 0; i < pid.size(); i++) {
        children[ppid[i]].push_back(pid[i]);
    }

    vector<int> killed;
    function<void(int)> dfs = [&](int id) {
        killed.push_back(id);
        for (int child : children[id]) {
            dfs(child);
        }
    };
    dfs(kill);

    return killed;
}
```
We use a hash map (unordered_map in C++, HashMap in Java, defaultdict in Python, Map in JavaScript) to store the children of each process. We iterate through the `pid` and `ppid` arrays to construct a tree-like data structure in the `children` map.

We then perform a depth-first search (DFS) starting from the `kill` process to traverse the tree and add all the processes to the `killed` list. The DFS function is implemented in a recursive manner, where we first add the current process id to the list `killed` and then iterate through its children.

We call the `dfs` function with the `kill` process id to construct the `killed` list and then return it.

## A solution in Python

```python
from collections import defaultdict

def killProcess(pid, ppid, kill):
    children = defaultdict(list)
    for i in range(len(pid)):
        children[ppid[i]].append(pid[i])

    def dfs(id, killed):
        killed.append(id)
        for child in children[id]:
            dfs(child, killed)

    killed = []
    dfs(kill, killed)
    return killed
```
We use a hash map (unordered_map in C++, HashMap in Java, defaultdict in Python, Map in JavaScript) to store the children of each process. We iterate through the `pid` and `ppid` arrays to construct a tree-like data structure in the `children` map.

We then perform a depth-first search (DFS) starting from the `kill` process to traverse the tree and add all the processes to the `killed` list. The DFS function is implemented in a recursive manner, where we first add the current process id to the list `killed` and then iterate through its children.

We call the `dfs` function with the `kill` process id to construct the `killed` list and then return it.

## A solution in Javascript

```javascript
function killProcess(pid, ppid, kill) {
  const children = new Map();
  for (let i = 0; i < pid.length; i++) {
    if (!children.has(ppid[i])) children.set(ppid[i], []);
    children.get(ppid[i]).push(pid[i]);
  }

  const killed = [];
  function dfs(id) {
    killed.push(id);
    const childList = children.get(id) || [];
    for (const child of childList) {
      dfs(child);
    }
  }
  dfs(kill);

  return killed;
}
```
We use a hash map (unordered_map in C++, HashMap in Java, defaultdict in Python, Map in JavaScript) to store the children of each process. We iterate through the `pid` and `ppid` arrays to construct a tree-like data structure in the `children` map.

We then perform a depth-first search (DFS) starting from the `kill` process to traverse the tree and add all the processes to the `killed` list. The DFS function is implemented in a recursive manner, where we first add the current process id to the list `killed` and then iterate through its children.

We call the `dfs` function with the `kill` process id to construct the `killed` list and then return it.


# Delete Operation for Two Strings

- slug: delete-operation-for-two-strings
- difficulty: Medium

Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_.

In one **step**, you can delete exactly one character in either string.

**Example 1:**

**Input:** word1 =  "sea ", word2 =  "eat "
**Output:** 2
**Explanation:** You need one step to make  "sea " to  "ea " and another step to make  "eat " to  "ea ".

**Example 2:**

**Input:** word1 =  "leetcode ", word2 =  "etco "
**Output:** 4

**Constraints:**

*   `1 <= word1.length, word2.length <= 500`
*   `word1` and `word2` consist of only lowercase English letters.

## A solution in Java

```java
public int minDistance(String word1, String word2) {
    int m = word1.length(), n = word2.length();
    int[][] dp = new int[m+1][n+1];

    for(int i = 0; i <= m; i++) {
        for(int j = 0; j <= n; j++) {
            if(i == 0 || j == 0)
                dp[i][j] = i + j;
            else if(word1.charAt(i-1) == word2.charAt(j-1))
                dp[i][j] = dp[i-1][j-1];
            else
                dp[i][j] = 1 + Math.min(dp[i-1][j], dp[i][j-1]);
        }
    }

    return dp[m][n];
}
```
The algorithm uses dynamic programming (DP) to solve the problem. It first initializes a 2D DP array `dp` with dimensions `m+1` by `n+1` where `m` is the length of `word1` and `n` is the length of `word2`. The DP entry `dp[i][j]` represents the minimum number of steps required to make the prefixes `word1[0...i-1]` and `word2[0...j-1]` equal.

The algorithm then populates the DP table using the following rules:
1. If either `i` or `j` is 0, then `dp[i][j] = i + j` since it needs to delete all characters from the other string.
2. If `word1[i-1]` is the same as `word2[j-1]`, then `dp[i][j] = dp[i-1][j-1]`.
3. Else, `dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])`, as we can either remove `word1[i-1]` or `word2[j-1]`.

Finally, the algorithm returns the value `dp[m][n]` as it represents the minimum number of steps required to make the two input strings equal.

## A solution in C++

```cpp
int minDistance(std::string word1, std::string word2) {
    int m = word1.length(), n = word2.length();
    std::vector<std::vector<int>> dp(m+1, std::vector<int>(n+1, 0));

    for(int i = 0; i <= m; i++) {
        for(int j = 0; j <= n; j++) {
            if(i == 0 || j == 0)
                dp[i][j] = i + j;
            else if(word1[i-1] == word2[j-1])
                dp[i][j] = dp[i-1][j-1];
            else
                dp[i][j] = 1 + std::min(dp[i-1][j], dp[i][j-1]);
        }
    }

    return dp[m][n];
}
```
The algorithm uses dynamic programming (DP) to solve the problem. It first initializes a 2D DP array `dp` with dimensions `m+1` by `n+1` where `m` is the length of `word1` and `n` is the length of `word2`. The DP entry `dp[i][j]` represents the minimum number of steps required to make the prefixes `word1[0...i-1]` and `word2[0...j-1]` equal.

The algorithm then populates the DP table using the following rules:
1. If either `i` or `j` is 0, then `dp[i][j] = i + j` since it needs to delete all characters from the other string.
2. If `word1[i-1]` is the same as `word2[j-1]`, then `dp[i][j] = dp[i-1][j-1]`.
3. Else, `dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])`, as we can either remove `word1[i-1]` or `word2[j-1]`.

Finally, the algorithm returns the value `dp[m][n]` as it represents the minimum number of steps required to make the two input strings equal.

## A solution in Python

```python
def minDistance(word1, word2):
    m, n = len(word1), len(word2)
    dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]

    for i in range(m+1):
        for j in range(n+1):
            if i == 0 or j == 0:
                dp[i][j] = i + j
            elif word1[i-1] == word2[j-1]:
                dp[i][j] = dp[i-1][j-1]
            else:
                dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])

    return dp[m][n]
```
The algorithm uses dynamic programming (DP) to solve the problem. It first initializes a 2D DP array `dp` with dimensions `m+1` by `n+1` where `m` is the length of `word1` and `n` is the length of `word2`. The DP entry `dp[i][j]` represents the minimum number of steps required to make the prefixes `word1[0...i-1]` and `word2[0...j-1]` equal.

The algorithm then populates the DP table using the following rules:
1. If either `i` or `j` is 0, then `dp[i][j] = i + j` since it needs to delete all characters from the other string.
2. If `word1[i-1]` is the same as `word2[j-1]`, then `dp[i][j] = dp[i-1][j-1]`.
3. Else, `dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])`, as we can either remove `word1[i-1]` or `word2[j-1]`.

Finally, the algorithm returns the value `dp[m][n]` as it represents the minimum number of steps required to make the two input strings equal.

## A solution in Javascript

```javascript
function minDistance(word1, word2) {
    let m = word1.length, n = word2.length;
    let dp = new Array(m + 1).fill().map(() => new Array(n + 1).fill(0));

    for(let i = 0; i <= m; i++) {
        for(let j = 0; j <= n; j++) {
            if(i === 0 || j === 0)
                dp[i][j] = i + j;
            else if(word1.charAt(i-1) === word2.charAt(j-1))
                dp[i][j] = dp[i-1][j-1];
            else
                dp[i][j] = 1 + Math.min(dp[i-1][j], dp[i][j-1]);
        }
    }

    return dp[m][n];
}
```
The algorithm uses dynamic programming (DP) to solve the problem. It first initializes a 2D DP array `dp` with dimensions `m+1` by `n+1` where `m` is the length of `word1` and `n` is the length of `word2`. The DP entry `dp[i][j]` represents the minimum number of steps required to make the prefixes `word1[0...i-1]` and `word2[0...j-1]` equal.

The algorithm then populates the DP table using the following rules:
1. If either `i` or `j` is 0, then `dp[i][j] = i + j` since it needs to delete all characters from the other string.
2. If `word1[i-1]` is the same as `word2[j-1]`, then `dp[i][j] = dp[i-1][j-1]`.
3. Else, `dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])`, as we can either remove `word1[i-1]` or `word2[j-1]`.

Finally, the algorithm returns the value `dp[m][n]` as it represents the minimum number of steps required to make the two input strings equal.


# Erect the Fence

- slug: erect-the-fence
- difficulty: Hard

You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden.

Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**.

Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**.

**Example 1:**

**Input:** trees = \[\[1,1\],\[2,2\],\[2,0\],\[2,4\],\[3,3\],\[4,2\]\]
**Output:** \[\[1,1\],\[2,0\],\[4,2\],\[3,3\],\[2,4\]\]
**Explanation:** All the trees will be on the perimeter of the fence except the tree at \[2, 2\], which will be inside the fence.

**Example 2:**

**Input:** trees = \[\[1,2\],\[2,2\],\[4,2\]\]
**Output:** \[\[4,2\],\[2,2\],\[1,2\]\]
**Explanation:** The fence forms a line that passes through all the trees.

**Constraints:**

*   `1 <= trees.length <= 3000`
*   `trees[i].length == 2`
*   `0 <= xi, yi <= 100`
*   All the given positions are **unique**.

## A solution in Java

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

public class Solution {
    private static int[][] fence(int[][] trees) {
        Arrays.sort(trees, (p, q) -> p[0] == q[0] ? p[1] - q[1] : p[0] - q[0]);
        List<int[]> hull = new ArrayList<>();
        for (int[] p : trees) {
            while (hull.size() >= 2 && crossProduct(hull.get(hull.size() - 2), hull.get(hull.size() - 1), p) > 0) {
                hull.remove(hull.size() - 1);
            }
            hull.add(p);
        }
        for (int i = trees.length - 1; i >= 0; i--) {
            int[] p = trees[i];
            while (hull.size() >= 2 && crossProduct(hull.get(hull.size() - 2), hull.get(hull.size() - 1), p) > 0) {
                hull.remove(hull.size() - 1);
            }
            hull.add(p);
        }
        return hull.toArray(new int[hull.size()][]);
    }

    private static int crossProduct(int[] p, int[] q, int[] r) {
        return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]);
    }
}
```
We use the **Graham's Scan Algorithm** to find the convex hull or the trees that form the fence perimeter. This algorithm works in O(n log n) time complexity.

1. First, we sort the trees based on their x coordinates. If two trees have the same x coordinate, they are sorted by their y coordinates.
2. We create an empty list called `hull` to store the trees that belong to the convex hull.
3. Iterate through the sorted `trees` and:
   a. For each tree `p`, we check if `hull` has at least two trees and the cross product of the last two trees and `p` is greater than 0.
   b. If the cross product is greater than 0, then the last tree in the `hull` doesn't belong to the convex hull, so we remove it.
   c. Add tree `p` to the `hull`.
4. Now we iterate through the sorted `trees` in reverse order and repeat steps 3a-3c.
5. At the end, the `hull` contains the coordinates of the trees that form the fence perimeter.

## A solution in C++

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

using namespace std;

bool compare(const vector<int>& p, const vector<int>& q) {
    return p[0] < q[0] || (p[0] == q[0] && p[1] < q[1]);
}

int cross_product(const vector<int>& p, const vector<int>& q, const vector<int>& r) {
    return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]);
}

vector<vector<int>> fence(vector<vector<int>>& trees) {
    sort(trees.begin(), trees.end(), compare);
    vector<vector<int>> hull;
    for (const auto& p : trees) {
        while (hull.size() >= 2 && cross_product(hull[hull.size() - 2], hull[hull.size() - 1], p) > 0) {
            hull.pop_back();
        }
        hull.push_back(p);
    }
    for (int i = trees.size() - 1; i >= 0; --i) {
        const auto& p = trees[i];
        while (hull.size() >= 2 && cross_product(hull[hull.size() - 2], hull[hull.size() - 1], p) > 0) {
            hull.pop_back();
        }
        hull.push_back(p);
    }
    return hull;
}
```
We use the **Graham's Scan Algorithm** to find the convex hull or the trees that form the fence perimeter. This algorithm works in O(n log n) time complexity.

1. First, we sort the trees based on their x coordinates. If two trees have the same x coordinate, they are sorted by their y coordinates.
2. We create an empty list called `hull` to store the trees that belong to the convex hull.
3. Iterate through the sorted `trees` and:
   a. For each tree `p`, we check if `hull` has at least two trees and the cross product of the last two trees and `p` is greater than 0.
   b. If the cross product is greater than 0, then the last tree in the `hull` doesn't belong to the convex hull, so we remove it.
   c. Add tree `p` to the `hull`.
4. Now we iterate through the sorted `trees` in reverse order and repeat steps 3a-3c.
5. At the end, the `hull` contains the coordinates of the trees that form the fence perimeter.

## A solution in Python

```python
def cross_product(p, q, r):
    return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])

def fence(trees):
    trees.sort(key=lambda p: (p[0], p[1]))
    hull = []
    for p in trees:
        while len(hull) >= 2 and cross_product(hull[-2], hull[-1], p) > 0:
            hull.pop()
        hull.append(p)

    for p in reversed(trees):
        while len(hull) >= 2 and cross_product(hull[-2], hull[-1], p) > 0:
            hull.pop()
        hull.append(p)

    return hull
```
We use the **Graham's Scan Algorithm** to find the convex hull or the trees that form the fence perimeter. This algorithm works in O(n log n) time complexity.

1. First, we sort the trees based on their x coordinates. If two trees have the same x coordinate, they are sorted by their y coordinates.
2. We create an empty list called `hull` to store the trees that belong to the convex hull.
3. Iterate through the sorted `trees` and:
   a. For each tree `p`, we check if `hull` has at least two trees and the cross product of the last two trees and `p` is greater than 0.
   b. If the cross product is greater than 0, then the last tree in the `hull` doesn't belong to the convex hull, so we remove it.
   c. Add tree `p` to the `hull`.
4. Now we iterate through the sorted `trees` in reverse order and repeat steps 3a-3c.
5. At the end, the `hull` contains the coordinates of the trees that form the fence perimeter.

## A solution in Javascript

```javascript
function crossProduct(p, q, r) {
    return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]);
}

function fence(trees) {
    trees.sort((p, q) => p[0] === q[0] ? p[1] - q[1] : p[0] - q[0]);
    const hull = [];
    for (const p of trees) {
        while (hull.length >= 2 && crossProduct(hull[hull.length - 2], hull[hull.length - 1], p) > 0) {
            hull.pop();
        }
        hull.push(p);
    }
    for (let i = trees.length - 1; i >= 0; i--) {
        const p = trees[i];
        while (hull.length >= 2 && crossProduct(hull[hull.length - 2], hull[hull.length - 1], p) > 0) {
            hull.pop();
        }
        hull.push(p);
    }
    return hull;
}
```
We use the **Graham's Scan Algorithm** to find the convex hull or the trees that form the fence perimeter. This algorithm works in O(n log n) time complexity.

1. First, we sort the trees based on their x coordinates. If two trees have the same x coordinate, they are sorted by their y coordinates.
2. We create an empty list called `hull` to store the trees that belong to the convex hull.
3. Iterate through the sorted `trees` and:
   a. For each tree `p`, we check if `hull` has at least two trees and the cross product of the last two trees and `p` is greater than 0.
   b. If the cross product is greater than 0, then the last tree in the `hull` doesn't belong to the convex hull, so we remove it.
   c. Add tree `p` to the `hull`.
4. Now we iterate through the sorted `trees` in reverse order and repeat steps 3a-3c.
5. At the end, the `hull` contains the coordinates of the trees that form the fence perimeter.


# Design In-Memory File System

- slug: design-in-memory-file-system
- difficulty: Hard

Design a data structure that simulates an in-memory file system.

Implement the FileSystem class:

*   `FileSystem()` Initializes the object of the system.
*   `List ls(String path)`

    *   If `path` is a file path, returns a list that only contains this file's name.
    *   If `path` is a directory path, returns the list of file and directory names **in this directory**.

    The answer should in **lexicographic order**.
*   `void mkdir(String path)` Makes a new directory according to the given `path`. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well.
*   `void addContentToFile(String filePath, String content)`
    *   If `filePath` does not exist, creates that file containing given `content`.
    *   If `filePath` already exists, appends the given `content` to original content.
*   `String readContentFromFile(String filePath)` Returns the content in the file at `filePath`.

**Example 1:**

**Input**
\[ "FileSystem ",  "ls ",  "mkdir ",  "addContentToFile ",  "ls ",  "readContentFromFile "\]
\[\[\], \[ "/ "\], \[ "/a/b/c "\], \[ "/a/b/c/d ",  "hello "\], \[ "/ "\], \[ "/a/b/c/d "\]\]
**Output**
\[null, \[\], null, null, \[ "a "\],  "hello "\]

**Explanation**
FileSystem fileSystem = new FileSystem();
fileSystem.ls( "/ ");                         // return \[\]
fileSystem.mkdir( "/a/b/c ");
fileSystem.addContentToFile( "/a/b/c/d ",  "hello ");
fileSystem.ls( "/ ");                         // return \[ "a "\]
fileSystem.readContentFromFile( "/a/b/c/d "); // return  "hello "

**Constraints:**

*   `1 <= path.length, filePath.length <= 100`
*   `path` and `filePath` are absolute paths which begin with `'/'` and do not end with `'/'` except that the path is just `"/ "`.
*   You can assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory.
*   You can assume that all operations will be passed valid parameters, and users will not attempt to retrieve file content or list a directory or file that does not exist.
*   `1 <= content.length <= 50`
*   At most `300` calls will be made to `ls`, `mkdir`, `addContentToFile`, and `readContentFromFile`.

## A solution in Java

```java
import java.util.*;

class FileSystem {
    class Node {
        boolean isFile = false;
        String content = "";
        Map<String, Node> children = new TreeMap<>();
    }

    Node root;

    public FileSystem() {
        root = new Node();
    }

    public List<String> ls(String path) {
        Node node = root;
        List<String> path_parts = splitPath(path);

        for (String part : path_parts) {
            node = node.children.get(part);
        }

        if (node.isFile) {
            return Collections.singletonList(path_parts.get(path_parts.size() - 1));
        } else {
            return new ArrayList<>(node.children.keySet());
        }
    }

    public void mkdir(String path) {
        Node node = root;
        List<String> path_parts = splitPath(path);

        for (String part : path_parts) {
            node.children.putIfAbsent(part, new Node());
            node = node.children.get(part);
        }
    }

    public void addContentToFile(String filePath, String content) {
        Node node = root;
        List<String> path_parts = splitPath(filePath);

        for (String part : path_parts) {
            node.children.putIfAbsent(part, new Node());
            node = node.children.get(part);
        }

        node.isFile = true;
        node.content += content;
    }

    public String readContentFromFile(String filePath) {
        Node node = root;
        List<String> path_parts = splitPath(filePath);

        for (String part : path_parts) {
            node = node.children.get(part);
        }

        return node.content;
    }

    private List<String> splitPath(String path) {
        List<String> parts = new ArrayList<>();
        String[] tokens = path.split("/");
        for (String token : tokens) {
            if (!token.isEmpty()) {
                parts.add(token);
            }
        }
        return parts;
    }
}
```
The algorithm uses a Trie-like data structure to represent the file system. Each node in the Trie can represent both a file and a folder. We use two hash maps to store folder and file content respectively. When performing CRUD operations (ls, mkdir, addContentToFile, readContentFromFile), we traverse the Trie based on the path and find the corresponding node, then perform the operation accordingly. When returning the string lists or file content, we sort folder names lexicographically.

## A solution in C++

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

class FileSystem {
    struct Node {
        bool is_file = false;
        std::string content;
        std::map<std::string, Node*> children;
    };

    Node* root;

public:
    FileSystem() {
        root = new Node();
    }

    std::vector<std::string> ls(std::string path) {
        Node* node = root;
        std::vector<std::string> path_parts = split_path(path);

        for (const std::string& part : path_parts) {
            node = node->children[part];
        }

        if (node->is_file) {
            return {path_parts.back()};
        } else {
            std::vector<std::string> files;
            for (const auto& child : node->children) {
                files.push_back(child.first);
            }
            std::sort(files.begin(), files.end());
            return files;
        }
    }

    void mkdir(std::string path) {
        Node* node = root;
        std::vector<std::string> path_parts = split_path(path);

        for (const std::string& part : path_parts) {
            if (node->children.find(part) == node->children.end()) {
                node->children[part] = new Node();
            }
            node = node->children[part];
        }
    }

    void addContentToFile(std::string filePath, std::string content) {
        Node* node = root;
        std::vector<std::string> path_parts = split_path(filePath);

        for (const std::string& part : path_parts) {
            if (node->children.find(part) == node->children.end()) {
                node->children[part] = new Node();
            }
            node = node->children[part];
        }

        node->is_file = true;
        node->content += content;
    }

    std::string readContentFromFile(std::string filePath) {
        Node* node = root;
        std::vector<std::string> path_parts = split_path(filePath);

        for (const std::string& part : path_parts) {
            node = node->children[part];
        }

        return node->content;
    }

private:
    std::vector<std::string> split_path(const std::string& path) {
        std::vector<std::string> parts;
        std::istringstream ss(path);
        std::string part;

        while (std::getline(ss, part, '/')) {
            if (!part.empty()) {
                parts.push_back(part);
            }
        }

        return parts;
    }
};
```
The algorithm uses a Trie-like data structure to represent the file system. Each node in the Trie can represent both a file and a folder. We use two hash maps to store folder and file content respectively. When performing CRUD operations (ls, mkdir, addContentToFile, readContentFromFile), we traverse the Trie based on the path and find the corresponding node, then perform the operation accordingly. When returning the string lists or file content, we sort folder names lexicographically.

## A solution in Python

```python
class FileSystem:
    class Node:
        def __init__(self):
            self.is_file = False
            self.content = ""
            self.children = {}

    def __init__(self):
        self.root = self.Node()

    def ls(self, path: str):
        node = self.root
        path_parts = self.split_path(path)

        for part in path_parts:
            node = node.children[part]

        if node.is_file:
            return path_parts[-1:]
        else:
            return sorted(node.children.keys())

    def mkdir(self, path: str):
        node = self.root
        path_parts = self.split_path(path)

        for part in path_parts:
            if part not in node.children:
                node.children[part] = self.Node()
            node = node.children[part]

    def addContentToFile(self, filePath: str, content: str):
        node = self.root
        path_parts = self.split_path(filePath)

        for part in path_parts:
            if part not in node.children:
                node.children[part] = self.Node()
            node = node.children[part]

        node.is_file = True
        node.content += content

    def readContentFromFile(self, filePath: str) -> str:
        node = self.root
        path_parts = self.split_path(filePath)

        for part in path_parts:
            node = node.children[part]

        return node.content

    @staticmethod
    def split_path(path: str):
        return [part for part in path.split("/") if part]

```
The algorithm uses a Trie-like data structure to represent the file system. Each node in the Trie can represent both a file and a folder. We use two hash maps to store folder and file content respectively. When performing CRUD operations (ls, mkdir, addContentToFile, readContentFromFile), we traverse the Trie based on the path and find the corresponding node, then perform the operation accordingly. When returning the string lists or file content, we sort folder names lexicographically.

## A solution in Javascript

```javascript
class FileSystem {
    constructor() {
        this.root = new this.Node();
    }

    ls(path) {
        let node = this.root;
        const pathParts = this.splitPath(path);

        for (const part of pathParts) {
            node = node.children[part];
        }

        if (node.isFile) {
            return [pathParts[pathParts.length - 1]];
        } else {
            return Object.keys(node.children).sort();
        }
    }

    mkdir(path) {
        let node = this.root;
        const pathParts = this.splitPath(path);

        for (const part of pathParts) {
            if (!node.children[part]) {
                node.children[part] = new this.Node();
            }
            node = node.children[part];
        }
    }

    addContentToFile(filePath, content) {
        let node = this.root;
        const pathParts = this.splitPath(filePath);

        for (const part of pathParts) {
            if (!node.children[part]) {
                node.children[part] = new this.Node();
            }
            node = node.children[part];
        }

        node.isFile = true;
        node.content += content;
    }

    readContentFromFile(filePath) {
        let node = this.root;
        const pathParts = this.splitPath(filePath);

        for (const part of pathParts) {
            node = node.children[part];
        }

        return node.content;
    }

    splitPath(path) {
        return path.split('/').filter(part => part);
    }

    Node() {
        this.isFile = false;
        this.content = '';
        this.children = {};
    }
}
```
The algorithm uses a Trie-like data structure to represent the file system. Each node in the Trie can represent both a file and a folder. We use two hash maps to store folder and file content respectively. When performing CRUD operations (ls, mkdir, addContentToFile, readContentFromFile), we traverse the Trie based on the path and find the corresponding node, then perform the operation accordingly. When returning the string lists or file content, we sort folder names lexicographically.


# N-ary Tree Preorder Traversal

- slug: n-ary-tree-preorder-traversal
- difficulty: Easy

Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_.

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

**Example 1:**

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

**Example 2:**

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

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 104]`.
*   `0 <= Node.val <= 104`
*   The height of the n-ary tree is less than or equal to `1000`.

**Follow up:** Recursive solution is trivial, could you do it iteratively?

## A solution in Java

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

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

    public Node() {}

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

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

public List<Integer> preorder(Node root) {
    List<Integer> result = new ArrayList<>();
    if (root == null) return result;
    Stack<Node> nodes = new Stack<>();
    nodes.push(root);

    while (!nodes.isEmpty()) {
        Node current = nodes.pop();
        result.add(current.val);
        for (int i = current.children.size() - 1; i >= 0; i--) {
            nodes.push(current.children.get(i));
        }
    }
    return result;
}
```
The problem asks for an iterative solution, although a recursive solution would be trivial. Therefore, this solution uses a stack data structure to perform the preorder traversal of the n-ary tree.

1. Initialize an empty list called `result` to store the traversed node values.
2. If `root` is null, return the empty `result`.
3. Initialize a stack called `nodes` and push `root` onto the stack.
4. While the stack is not empty, perform the following steps:
   a. Pop the top node from the stack and store it in a variable called `current`.
   b. Add `current`'s value to the `result`.
   c. Reverse iterate through `current`'s children, pushing them onto the stack.
5. Once the stack is empty, return the `result`.

The algorithm's time complexity is O(n), where n is the number of nodes in the tree. This is because each node gets pushed onto and popped from the stack exactly once. The space complexity is also O(n), as at worst, the stack will store all the nodes in the tree.

## A solution in C++

```cpp
#include <vector>

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

    Node() {}

    Node(int _val) {
        val = _val;
    }

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

vector<int> preorder(Node* root) {
    vector<int> result;
    if (root == nullptr) return result;
    stack<Node*> nodes;
    nodes.push(root);

    while (!nodes.empty()) {
        Node* current = nodes.top();
        nodes.pop();
        result.push_back(current->val);
        for (int i = current->children.size() - 1; i >= 0; i--) {
            nodes.push(current->children[i]);
        }
    }
    return result;
}
```
The problem asks for an iterative solution, although a recursive solution would be trivial. Therefore, this solution uses a stack data structure to perform the preorder traversal of the n-ary tree.

1. Initialize an empty list called `result` to store the traversed node values.
2. If `root` is null, return the empty `result`.
3. Initialize a stack called `nodes` and push `root` onto the stack.
4. While the stack is not empty, perform the following steps:
   a. Pop the top node from the stack and store it in a variable called `current`.
   b. Add `current`'s value to the `result`.
   c. Reverse iterate through `current`'s children, pushing them onto the stack.
5. Once the stack is empty, return the `result`.

The algorithm's time complexity is O(n), where n is the number of nodes in the tree. This is because each node gets pushed onto and popped from the stack exactly once. The space complexity is also O(n), as at worst, the stack will store all the nodes in the tree.

## A solution in Python

```python
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children

def preorder(root):
    result = []
    if not root:
        return result
    nodes = [root]

    while nodes:
        current = nodes.pop()
        result.append(current.val)
        nodes.extend(reversed(current.children))
    return result
```
The problem asks for an iterative solution, although a recursive solution would be trivial. Therefore, this solution uses a stack data structure to perform the preorder traversal of the n-ary tree.

1. Initialize an empty list called `result` to store the traversed node values.
2. If `root` is null, return the empty `result`.
3. Initialize a stack called `nodes` and push `root` onto the stack.
4. While the stack is not empty, perform the following steps:
   a. Pop the top node from the stack and store it in a variable called `current`.
   b. Add `current`'s value to the `result`.
   c. Reverse iterate through `current`'s children, pushing them onto the stack.
5. Once the stack is empty, return the `result`.

The algorithm's time complexity is O(n), where n is the number of nodes in the tree. This is because each node gets pushed onto and popped from the stack exactly once. The space complexity is also O(n), as at worst, the stack will store all the nodes in the tree.

## A solution in Javascript

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

var preorder = function(root) {
    const result = [];
    if (!root) return result;
    const nodes = [root];

    while (nodes.length > 0) {
        const current = nodes.pop();
        result.push(current.val);
        for (let i = current.children.length - 1; i >= 0; i--) {
            nodes.push(current.children[i]);
        }
    }
    return result;
};
```
The problem asks for an iterative solution, although a recursive solution would be trivial. Therefore, this solution uses a stack data structure to perform the preorder traversal of the n-ary tree.

1. Initialize an empty list called `result` to store the traversed node values.
2. If `root` is null, return the empty `result`.
3. Initialize a stack called `nodes` and push `root` onto the stack.
4. While the stack is not empty, perform the following steps:
   a. Pop the top node from the stack and store it in a variable called `current`.
   b. Add `current`'s value to the `result`.
   c. Reverse iterate through `current`'s children, pushing them onto the stack.
5. Once the stack is empty, return the `result`.

The algorithm's time complexity is O(n), where n is the number of nodes in the tree. This is because each node gets pushed onto and popped from the stack exactly once. The space complexity is also O(n), as at worst, the stack will store all the nodes in the tree.


# N-ary Tree Postorder Traversal

- slug: n-ary-tree-postorder-traversal
- difficulty: Easy

Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_.

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

**Example 1:**

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

**Example 2:**

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

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 104]`.
*   `0 <= Node.val <= 104`
*   The height of the n-ary tree is less than or equal to `1000`.

**Follow up:** Recursive solution is trivial, could you do it iteratively?

## A solution in Java

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

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

    Stack<Node> stk = new Stack<>();
    stk.push(root);

    while (!stk.isEmpty()) {
        Node current = stk.pop();
        result.add(current.val);

        for (Node child : current.children)
            stk.push(child);
    }

    Collections.reverse(result);
    return result;
}
```
The algorithm for iterative postorder traversal of an n-ary tree is as follows:

1. Create an empty stack and push the root node onto it.
2. While the stack is not empty:
    a. Pop the top node from the stack and add its value to the result list.
    b. Iterate through the node's children, pushing them onto the stack.
3. Reverse the result list and return it.

This algorithm ensures a depth-first traversal of the tree, visiting each node's children before the node itself (postorder traversal). By reversing the result list at the end, the desired postorder list is obtained.

## A solution in C++

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

vector<int> postorder(Node* root) {
    vector<int> result;
    if (!root) return result;

    stack<Node*> stk;
    stk.push(root);

    while (!stk.empty()) {
        Node* current = stk.top();
        stk.pop();
        result.push_back(current->val);

        for (auto child : current->children)
            stk.push(child);
    }

    reverse(result.begin(), result.end());
    return result;
}
```
The algorithm for iterative postorder traversal of an n-ary tree is as follows:

1. Create an empty stack and push the root node onto it.
2. While the stack is not empty:
    a. Pop the top node from the stack and add its value to the result list.
    b. Iterate through the node's children, pushing them onto the stack.
3. Reverse the result list and return it.

This algorithm ensures a depth-first traversal of the tree, visiting each node's children before the node itself (postorder traversal). By reversing the result list at the end, the desired postorder list is obtained.

## A solution in Python

```python
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children or []

def postorder(root):
    result = []
    if not root:
        return result

    stk = [root]

    while stk:
        current = stk.pop()
        result.append(current.val)

        for child in current.children:
            stk.append(child)

    return result[::-1]
```
The algorithm for iterative postorder traversal of an n-ary tree is as follows:

1. Create an empty stack and push the root node onto it.
2. While the stack is not empty:
    a. Pop the top node from the stack and add its value to the result list.
    b. Iterate through the node's children, pushing them onto the stack.
3. Reverse the result list and return it.

This algorithm ensures a depth-first traversal of the tree, visiting each node's children before the node itself (postorder traversal). By reversing the result list at the end, the desired postorder list is obtained.

## A solution in Javascript

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

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

    let stk = [root];

    while (stk.length > 0) {
        let current = stk.pop();
        result.push(current.val);

        for (let child of current.children)
            stk.push(child);
    }

    return result.reverse();
}
```
The algorithm for iterative postorder traversal of an n-ary tree is as follows:

1. Create an empty stack and push the root node onto it.
2. While the stack is not empty:
    a. Pop the top node from the stack and add its value to the result list.
    b. Iterate through the node's children, pushing them onto the stack.
3. Reverse the result list and return it.

This algorithm ensures a depth-first traversal of the tree, visiting each node's children before the node itself (postorder traversal). By reversing the result list at the end, the desired postorder list is obtained.


# Tag Validator

- slug: tag-validator
- difficulty: Hard

Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.

A code snippet is valid if all the following rules hold:

1.  The code must be wrapped in a **valid closed tag**. Otherwise, the code is invalid.
2.  A **closed tag** (not necessarily valid) has exactly the following format : `TAG_CONTENT`. Among them, is the start tag, and is the end tag. The TAG\_NAME in start and end tags should be the same. A closed tag is **valid** if and only if the TAG\_NAME and TAG\_CONTENT are valid.
3.  A **valid** `TAG_NAME` only contain **upper-case letters**, and has length in range \[1,9\]. Otherwise, the `TAG_NAME` is **invalid**.
4.  A **valid** `TAG_CONTENT` may contain other **valid closed tags**, **cdata** and any characters (see note1) **EXCEPT** unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG\_NAME. Otherwise, the `TAG_CONTENT` is **invalid**.
5.  A start tag is unmatched if no end tag exists with the same TAG\_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.
6.  A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or ``, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid).``
``` *   The cdata has the following format : . The range of `CDATA_CONTENT` is defined as the characters between ``and the **first subsequent** `]]>`.`` ``*   `CDATA_CONTENT` may contain **any characters**. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as **regular characters**.`` ```

``` ``  **Example 1:**  **Input:** code =  "  This is the first line ]]>   " **Output:** true **Explanation:**  The code is wrapped in a closed tag :    and   .  The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata.  Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true.  **Example 2:**  **Input:** code =  "  >>  ![cdata[]] ]>]]>]]>>]   " **Output:** true **Explanation:** We first separate the code into : start_tag|tag_content|end_tag. start_tag -> ** "**   **"** end_tag -> ** "**   **"** tag_content could also be separated into : text1|cdata|text2. text1 -> ** ">>  ![cdata[]]  "** cdata -> ** "]>]]> "**, where the CDATA_CONTENT is ** "**  **]> "** text2 -> ** "]]>>] "** The reason why start_tag is NOT ** "**  **>> "** is because of the rule 6. The reason why cdata is NOT ** "]>]]>]]> "** is because of the rule 7.  **Example 3:**  **Input:** code =  "    " **Output:** false **Explanation:** Unbalanced. If  " " is closed, then  " **" must be unmatched, and vice versa.**  **  **Constraints:**  *   `1 <= code.length <= 500` *   `code` consists of English letters, digits, `'<'`, `'>'`, `'/'`, `'!'`, `'['`, `']'`, `'.'`, and `' '`.  **`` ```

## A solution in Java

```java
private static boolean isValid(String code, int[] i) {
    if (i[0] >= code.length()) return false;
    if (code.charAt(i[0]) != '<') return false;
    int nameLength = 0;
    for (++i[0]; i[0] < code.length() && nameLength < 9 && Character.isUpperCase(code.charAt(i[0])); ++i[0]) ++nameLength;
    if (nameLength < 1 || nameLength > 9 || code.charAt(i[0]++) != '>') return false;

    while (i[0] < code.length() && code.charAt(i[0]) != '<') ++i[0];
    if (i[0] >= code.length()) return false;

    if (!code.substring(i[0], i[0] + nameLength + 3).equals("</" + code.substring(i[0] - nameLength - 1, i[0] - 1) + ">"))
        return false;
    i[0] += nameLength + 3;
    return true;
}

public static boolean validateCodeSnippet(String code) {
    int[] i = {0};
    return isValid(code, i) && i[0] == code.length();
}
```
The algorithm iterates through the code snippet and checks for valid start tags and end tags. It checks for the following conditions:
1. The code snippet begins with a start tag and ends with a matching end tag.
2. A start tag starts with `<` followed by uppercase alphabet letters and ends with `>`.
3. An end tag is a string like `</TAG_NAME>` with no extra characters after the tag name, and TAG_NAME in the end tag is the same as the start tag.
4. Valid tags don't have any other tags inside them but can have single or double quotes as a regular text element.

We use helper functions `is_valid` or `isValid` in each language to traverse the code string and match start tags with their corresponding end tags. It returns a boolean value indicating if the code is valid or not, and also updates the current index of the string traversal, which is passed as a reference or a mutable object.

The main function `validate_code_snippet` or `validateCodeSnippet` calls the helper function and checks if the returned boolean value is True and the updated index is equal to the length of the code string, which means the entire code snippet was traversed and validated successfully. If both conditions are met, the code snippet is valid, otherwise it is invalid.

## A solution in C++

```cpp
bool is_valid(const std::string& code, size_t &i) {
    if (i >= code.size()) return false;
    if (code[i] != '<') return false;
    int name_len = 0;
    for (++i; i < code.size() && name_len < 9 && isupper(code[i]); ++i) ++name_len;
    if (name_len < 1 || name_len > 9 || code[i++] != '>') return false;

    while (i < code.size() && code[i] != '<') ++i;
    if (i >= code.size()) return false;

    if (code.substr(i, name_len + 3) != "</" + code.substr(i - name_len - 1, name_len) + ">")
        return false;
    i += name_len + 3;
    return true;
}

bool validateCodeSnippet(const std::string &code) {
    size_t i = 0;
    return is_valid(code, i) && i == code.size();
}
```
The algorithm iterates through the code snippet and checks for valid start tags and end tags. It checks for the following conditions:
1. The code snippet begins with a start tag and ends with a matching end tag.
2. A start tag starts with `<` followed by uppercase alphabet letters and ends with `>`.
3. An end tag is a string like `</TAG_NAME>` with no extra characters after the tag name, and TAG_NAME in the end tag is the same as the start tag.
4. Valid tags don't have any other tags inside them but can have single or double quotes as a regular text element.

We use helper functions `is_valid` or `isValid` in each language to traverse the code string and match start tags with their corresponding end tags. It returns a boolean value indicating if the code is valid or not, and also updates the current index of the string traversal, which is passed as a reference or a mutable object.

The main function `validate_code_snippet` or `validateCodeSnippet` calls the helper function and checks if the returned boolean value is True and the updated index is equal to the length of the code string, which means the entire code snippet was traversed and validated successfully. If both conditions are met, the code snippet is valid, otherwise it is invalid.

## A solution in Python

```python
def is_valid(code, i):
    if i >= len(code) or code[i] != '<':
        return False, i
    i += 1
    name_start = i
    while i < len(code) and code[i].isupper():
        i += 1
    name_len = i - name_start
    if name_len < 1 or name_len > 9 or code[i] != '>':
        return False, i
    i += 1

    while i < len(code) and code[i] != '<':
        i += 1
    if i + 2 + name_len >= len(code) or code[i:i + 2 + name_len] != '</' + code[name_start:i] + '>':
        return False, i
    return True, i + 2 + name_len

def validate_code_snippet(code):
    is_valid_code, i = is_valid(code, 0)
    return is_valid_code and i == len(code)
```
The algorithm iterates through the code snippet and checks for valid start tags and end tags. It checks for the following conditions:
1. The code snippet begins with a start tag and ends with a matching end tag.
2. A start tag starts with `<` followed by uppercase alphabet letters and ends with `>`.
3. An end tag is a string like `</TAG_NAME>` with no extra characters after the tag name, and TAG_NAME in the end tag is the same as the start tag.
4. Valid tags don't have any other tags inside them but can have single or double quotes as a regular text element.

We use helper functions `is_valid` or `isValid` in each language to traverse the code string and match start tags with their corresponding end tags. It returns a boolean value indicating if the code is valid or not, and also updates the current index of the string traversal, which is passed as a reference or a mutable object.

The main function `validate_code_snippet` or `validateCodeSnippet` calls the helper function and checks if the returned boolean value is True and the updated index is equal to the length of the code string, which means the entire code snippet was traversed and validated successfully. If both conditions are met, the code snippet is valid, otherwise it is invalid.

## A solution in Javascript

```javascript
function isValid(code, i) {
    if (!code || i.value >= code.length) return false;
    if (code[i.value] != '<') return false;
    let nameLength = 0;
    for (++i.value; i.value < code.length && nameLength < 9 && /^[A-Z]$/.test(code[i.value]); ++i.value) ++nameLength;
    if (nameLength < 1 || nameLength > 9 || code[i.value++] != '>') return false;

    while (i.value < code.length && code[i.value] != '<') ++i.value;
    if (i.value >= code.length) return false;

    if (code.substring(i.value, i.value + nameLength + 3) != "</" + code.substring(i.value - nameLength - 1, i.value-1) + ">")
        return false;
    i.value += nameLength + 3;
    return true;
}

function validateCodeSnippet(code) {
    let i = {value: 0};
    return isValid(code, i) && i.value == code.length;
}
```
The algorithm iterates through the code snippet and checks for valid start tags and end tags. It checks for the following conditions:
1. The code snippet begins with a start tag and ends with a matching end tag.
2. A start tag starts with `<` followed by uppercase alphabet letters and ends with `>`.
3. An end tag is a string like `</TAG_NAME>` with no extra characters after the tag name, and TAG_NAME in the end tag is the same as the start tag.
4. Valid tags don't have any other tags inside them but can have single or double quotes as a regular text element.

We use helper functions `is_valid` or `isValid` in each language to traverse the code string and match start tags with their corresponding end tags. It returns a boolean value indicating if the code is valid or not, and also updates the current index of the string traversal, which is passed as a reference or a mutable object.

The main function `validate_code_snippet` or `validateCodeSnippet` calls the helper function and checks if the returned boolean value is True and the updated index is equal to the length of the code string, which means the entire code snippet was traversed and validated successfully. If both conditions are met, the code snippet is valid, otherwise it is invalid.


# Fraction Addition and Subtraction

- slug: fraction-addition-and-subtraction
- difficulty: Medium

Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format.

The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`.

**Example 1:**

**Input:** expression =  "-1/2+1/2 "
**Output:**  "0/1 "

**Example 2:**

**Input:** expression =  "-1/2+1/2+1/3 "
**Output:**  "1/3 "

**Example 3:**

**Input:** expression =  "1/3-1/2 "
**Output:**  "-1/6 "

**Constraints:**

*   The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output.
*   Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted.
*   The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above.
*   The number of given fractions will be in the range `[1, 10]`.
*   The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.

## A solution in Java

```java
public class Solution {
    public String fractionAddition(String expression) {
        int A = 0, B = 1;
        int i = 0;
        while(i < expression.length()) {
            int sign = expression.charAt(i++) == '+' ? 1 : -1;
            int num = 0, den = 0;
            while (i < expression.length() && Character.isDigit(expression.charAt(i))) {
                num = num * 10 + (expression.charAt(i++) - '0');
            }
            i++; // skip '/'
            while (i < expression.length() && Character.isDigit(expression.charAt(i))) {
                den = den * 10 + (expression.charAt(i++) - '0');
            }
            A = A * den + B * num * sign;
            B *= den;
            int GCD = gcd(Math.abs(A), Math.abs(B));
            A /= GCD;
            B /= GCD;
        }
        return A + "/" + B;
    }

    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}
```

    The algorithm first initializes the result fraction A/B to 0/1. It then iterates over the input expression, parsing and adjusting signs of each fraction it encounters. Each fraction's numerator and denominator are found by parsing the characters in the expression. The current sum A/B is updated with the current fraction by the equation:

```
A = A * den + B * num * sign
B *= den
```
After updating A/B, the greatest common divisor (GCD) of A and B, found using the Euclidean algorithm, is used to reduce the fraction.

The process is repeated until the whole string input expression is processed. At the end, the irreducible fraction is returned in the format A/B.

## A solution in C++

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

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

string fractionAddition(string expression) {
    stringstream ss(expression);
    int num, den, A = 0, B = 1;
    char ch;

    while (ss >> num >> ch >> den) {
        A = A * den + B * num;
        B *= den;
        int GCD = gcd(abs(A), abs(B));
        A /= GCD;
        B /= GCD;
    }

    return to_string(A) + "/" + to_string(B);
}
```

    The algorithm first initializes the result fraction A/B to 0/1. It then iterates over the input expression, parsing and adjusting signs of each fraction it encounters. Each fraction's numerator and denominator are found by parsing the characters in the expression. The current sum A/B is updated with the current fraction by the equation:

```
A = A * den + B * num * sign
B *= den
```
After updating A/B, the greatest common divisor (GCD) of A and B, found using the Euclidean algorithm, is used to reduce the fraction.

The process is repeated until the whole string input expression is processed. At the end, the irreducible fraction is returned in the format A/B.

## A solution in Python

```python
from fractions import Fraction

def fractionAddition(expression: str) -> str:
    fractions = expression.replace('+', ' +').replace('-', ' -').split()
    result = sum(Fraction(fraction) for fraction in fractions)
    return f"{result.numerator}/{result.denominator}"
```

    The algorithm first initializes the result fraction A/B to 0/1. It then iterates over the input expression, parsing and adjusting signs of each fraction it encounters. Each fraction's numerator and denominator are found by parsing the characters in the expression. The current sum A/B is updated with the current fraction by the equation:

```
A = A * den + B * num * sign
B *= den
```
After updating A/B, the greatest common divisor (GCD) of A and B, found using the Euclidean algorithm, is used to reduce the fraction.

The process is repeated until the whole string input expression is processed. At the end, the irreducible fraction is returned in the format A/B.

## A solution in Javascript

```javascript
function gcd(a, b) {
    return b === 0 ? a : gcd(b, a % b);
}

function fractionAddition(expression) {
    let A = 0, B = 1;
    let i = 0;
    while (i < expression.length) {
        const sign = expression[i++] === '+' ? 1 : -1;
        let num = 0, den = 0;
        while (i < expression.length && !isNaN(expression[i])) {
            num = num * 10 + parseInt(expression[i++]);
        }
        i++; // skip '/'
        while (i < expression.length && !isNaN(expression[i])) {
            den = den * 10 + parseInt(expression[i++]);
        }
        A = A * den + B * num * sign;
        B *= den;
        const GCD = gcd(Math.abs(A), Math.abs(B));
        A /= GCD;
        B /= GCD;
    }
    return `${A}/${B}`;
}
```

    The algorithm first initializes the result fraction A/B to 0/1. It then iterates over the input expression, parsing and adjusting signs of each fraction it encounters. Each fraction's numerator and denominator are found by parsing the characters in the expression. The current sum A/B is updated with the current fraction by the equation:

```
A = A * den + B * num * sign
B *= den
```
After updating A/B, the greatest common divisor (GCD) of A and B, found using the Euclidean algorithm, is used to reduce the fraction.

The process is repeated until the whole string input expression is processed. At the end, the irreducible fraction is returned in the format A/B.


# Valid Square

- slug: valid-square
- difficulty: Medium

Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_.

The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order.

A **valid square** has four equal sides with positive length and four equal angles (90-degree angles).

**Example 1:**

**Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,1\]
**Output:** true

**Example 2:**

**Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,12\]
**Output:** false

**Example 3:**

**Input:** p1 = \[1,0\], p2 = \[-1,0\], p3 = \[0,1\], p4 = \[0,-1\]
**Output:** true

**Constraints:**

*   `p1.length == p2.length == p3.length == p4.length == 2`
*   `-104 <= xi, yi <= 104`

## A solution in Java

```java
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
    Set<Integer> dist = new HashSet<>();
    int[][] points = {p1, p2, p3, p4};

    for (int i = 0; i < 4; i++) {
        for (int j = i + 1; j < 4; j++) {
            dist.add((points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1]));
        }
    }

    return dist.size() == 2 && !dist.contains(0);
}
```
1. Create a function to calculate the distance between two points in 2D space.
2. Create a set to store unique distances between points.
3. Iterate through all distinct pairs of points, calculating the distance between them and adding the result to the set.
4. Check if the size of the set is 2, meaning that there are exactly two unique distances, and that the smallest distance is not 0, indicating that no two points are the same.
5. If the above conditions are met, the four points form a square. Otherwise, they do not.

## A solution in C++

```cpp
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
    set<int> dist;
    vector<vector<int>> points{p1, p2, p3, p4};

    for (int i = 0; i < 4; i++) {
        for (int j = i + 1; j < 4; j++) {
            dist.insert(pow(points[i][0] - points[j][0], 2) + pow(points[i][1] - points[j][1], 2));
        }
    }

    return dist.size() == 2 && *dist.begin() != 0;
}
```
1. Create a function to calculate the distance between two points in 2D space.
2. Create a set to store unique distances between points.
3. Iterate through all distinct pairs of points, calculating the distance between them and adding the result to the set.
4. Check if the size of the set is 2, meaning that there are exactly two unique distances, and that the smallest distance is not 0, indicating that no two points are the same.
5. If the above conditions are met, the four points form a square. Otherwise, they do not.

## A solution in Python

```python
def validSquare(p1, p2, p3, p4):
    def dist_sq(p, q):
        return (p[0] - q[0])**2 + (p[1] - q[1])**2

    points = [p1, p2, p3, p4]
    dists = set()

    for i in range(4):
        for j in range(i + 1, 4):
            dists.add(dist_sq(points[i], points[j]))

    return len(dists) == 2 and 0 not in dists
```
1. Create a function to calculate the distance between two points in 2D space.
2. Create a set to store unique distances between points.
3. Iterate through all distinct pairs of points, calculating the distance between them and adding the result to the set.
4. Check if the size of the set is 2, meaning that there are exactly two unique distances, and that the smallest distance is not 0, indicating that no two points are the same.
5. If the above conditions are met, the four points form a square. Otherwise, they do not.

## A solution in Javascript

```javascript
function validSquare(p1, p2, p3, p4) {
    function distSq(p, q) {
        return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2;
    }

    let points = [p1, p2, p3, p4];
    let dists = new Set();

    for (let i = 0; i < 4; i++) {
        for (let j = i + 1; j < 4; j++) {
            dists.add(distSq(points[i], points[j]));
        }
    }

    return dists.size === 2 && !dists.has(0);
}
```
1. Create a function to calculate the distance between two points in 2D space.
2. Create a set to store unique distances between points.
3. Iterate through all distinct pairs of points, calculating the distance between them and adding the result to the set.
4. Check if the size of the set is 2, meaning that there are exactly two unique distances, and that the smallest distance is not 0, indicating that no two points are the same.
5. If the above conditions are met, the four points form a square. Otherwise, they do not.


# Longest Harmonious Subsequence

- slug: longest-harmonious-subsequence
- difficulty: Easy

We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`.

Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_.

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

**Example 1:**

**Input:** nums = \[1,3,2,2,5,2,3,7\]
**Output:** 5
**Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\].

**Example 2:**

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

**Example 3:**

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

**Constraints:**

*   `1 <= nums.length <= 2 * 104`
*   `-109 <= nums[i] <= 109`

## A solution in Java

```java
import java.util.HashMap;

public int findLHS(int[] nums) {
    HashMap<Integer, Integer> count = new HashMap<>();
    for (int num : nums)
        count.put(num, count.getOrDefault(num, 0) + 1);

    int longest_sequence = 0;
    for (int key : count.keySet()) {
        if (count.containsKey(key + 1))
            longest_sequence = Math.max(longest_sequence, count.get(key) + count.get(key + 1));
    }

    return longest_sequence;
}
```
1. Create a hashmap to count the occurrences of each number in the input array.
2. Iterate through the uniquq elements in the hashmap.
3. For each element, check if there exists an element that is 1 greater, and if so, record the sum of the element count and the count of the element 1 greater.
4. Keep track of the maximum harmony sequence found during this iteration.
5. Return the length of the longest harmonious sequence found.

## A solution in C++

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

int findLHS(vector<int>& nums) {
    unordered_map<int, int> count;
    for (int num : nums)
        count[num]++;

    int longest_sequence = 0;
    for (auto &elem : count) {
        if (count.find(elem.first + 1) != count.end())
            longest_sequence = max(longest_sequence, elem.second + count[elem.first + 1]);
    }

    return longest_sequence;
}
```
1. Create a hashmap to count the occurrences of each number in the input array.
2. Iterate through the uniquq elements in the hashmap.
3. For each element, check if there exists an element that is 1 greater, and if so, record the sum of the element count and the count of the element 1 greater.
4. Keep track of the maximum harmony sequence found during this iteration.
5. Return the length of the longest harmonious sequence found.

## A solution in Python

```python
def findLHS(nums):
    count = {}
    for num in nums:
        count[num] = count.get(num, 0) + 1

    longest_sequence = 0
    for key in count:
        if key + 1 in count:
            longest_sequence = max(longest_sequence, count[key] + count[key + 1])

    return longest_sequence
```
1. Create a hashmap to count the occurrences of each number in the input array.
2. Iterate through the uniquq elements in the hashmap.
3. For each element, check if there exists an element that is 1 greater, and if so, record the sum of the element count and the count of the element 1 greater.
4. Keep track of the maximum harmony sequence found during this iteration.
5. Return the length of the longest harmonious sequence found.

## A solution in Javascript

```javascript
function findLHS(nums) {
    const count = new Map();
    for (const num of nums) {
        count.set(num, (count.get(num) || 0) + 1);
    }

    let longest_sequence = 0;
    for (const key of count.keys()) {
        if (count.has(key + 1)) {
            longest_sequence = Math.max(longest_sequence, count.get(key) + count.get(key + 1));
        }
    }

    return longest_sequence;
}
```
1. Create a hashmap to count the occurrences of each number in the input array.
2. Iterate through the uniquq elements in the hashmap.
3. For each element, check if there exists an element that is 1 greater, and if so, record the sum of the element count and the count of the element 1 greater.
4. Keep track of the maximum harmony sequence found during this iteration.
5. Return the length of the longest harmonious sequence found.


# Range Addition II

- slug: range-addition-ii
- difficulty: Easy

You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`.

Count and return _the number of maximum integers in the matrix after performing all the operations_.

**Example 1:**

**Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\]\]
**Output:** 4
**Explanation:** The maximum integer in M is 2, and there are four of it in M. So return 4.

**Example 2:**

**Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\]\]
**Output:** 4

**Example 3:**

**Input:** m = 3, n = 3, ops = \[\]
**Output:** 9

**Constraints:**

*   `1 <= m, n <= 4 * 104`
*   `0 <= ops.length <= 104`
*   `ops[i].length == 2`
*   `1 <= ai <= m`
*   `1 <= bi <= n`

## A solution in Java

```java
public int maxCount(int m, int n, int[][] ops) {
    for (int[] op : ops) {
        m = Math.min(m, op[0]);
        n = Math.min(n, op[1]);
    }
    return m * n;
}
```
The algorithm consists of iterating through each operation in the ops array and updating the values of m and n to be the minimum of their current value and the corresponding values in the operation. This is because the maximum integers will always be in the top-left corner of the matrix (0 <= x < ai and 0 <= y < bi). Once all operations have been considered, we multiply the final values of m and n to get the count of maximum integers in the matrix.

## A solution in C++

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

int maxCount(int m, int n, vector<vector<int>>& ops) {
    for (vector<int>& op : ops) {
        m = min(m, op[0]);
        n = min(n, op[1]);
    }
    return m * n;
}
```
The algorithm consists of iterating through each operation in the ops array and updating the values of m and n to be the minimum of their current value and the corresponding values in the operation. This is because the maximum integers will always be in the top-left corner of the matrix (0 <= x < ai and 0 <= y < bi). Once all operations have been considered, we multiply the final values of m and n to get the count of maximum integers in the matrix.

## A solution in Python

```python
def maxCount(m: int, n: int, ops: List[List[int]]) -> int:
    for op in ops:
        m = min(m, op[0])
        n = min(n, op[1])
    return m * n
```
The algorithm consists of iterating through each operation in the ops array and updating the values of m and n to be the minimum of their current value and the corresponding values in the operation. This is because the maximum integers will always be in the top-left corner of the matrix (0 <= x < ai and 0 <= y < bi). Once all operations have been considered, we multiply the final values of m and n to get the count of maximum integers in the matrix.

## A solution in Javascript

```javascript
function maxCount(m, n, ops) {
    for (let op of ops) {
        m = Math.min(m, op[0]);
        n = Math.min(n, op[1]);
    }
    return m * n;
}
```
The algorithm consists of iterating through each operation in the ops array and updating the values of m and n to be the minimum of their current value and the corresponding values in the operation. This is because the maximum integers will always be in the top-left corner of the matrix (0 <= x < ai and 0 <= y < bi). Once all operations have been considered, we multiply the final values of m and n to get the count of maximum integers in the matrix.