# Longest Word in Dictionary through Deleting

- slug: longest-word-in-dictionary-through-deleting
- difficulty: Medium

Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

**Example 1:**

**Input:** s =  "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:**  "apple "

**Example 2:**

**Input:** s =  "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:**  "a "

**Constraints:**

*   `1 <= s.length <= 1000`
*   `1 <= dictionary.length <= 1000`
*   `1 <= dictionary[i].length <= 1000`
*   `s` and `dictionary[i]` consist of lowercase English letters.

## A solution in Java

```java
import java.util.Arrays;

public String findLongestWord(String s, String[] dictionary) {
    String longest = "";
    Arrays.sort(dictionary);
    for (String word : dictionary) {
        if (isSubsequence(s, word)) {
            if (word.length() > longest.length()) {
                longest = word;
            }
        }
    }
    return longest;
}

private boolean isSubsequence(String s, String word) {
    int i = 0, j = 0;
    while (i < s.length() && j < word.length()) {
        if (s.charAt(i) == word.charAt(j)) {
            j++;
        }
        i++;
    }
    return j == word.length();
}
```
1. First, sort the dictionary so that word comparison will be in lexicographical order.
2. Define a helper function `isSubsequence` which checks if a given word can be formed by deleting some of the given string characters.
3. Iterate through the dictionary and for each word, check if it can be formed using the helper function. If a word can be formed and its length is longer than the current longest word, set it as the new longest word.
4. Return the longest word found, or an empty string if no match was found.

## A solution in C++

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

bool isSubsequence(const std::string &s, const std::string &word) {
    int i = 0, j = 0;
    while (i < s.size() && j < word.size()) {
        if (s[i] == word[j]) {
            j++;
        }
        i++;
    }
    return j == word.size();
}

std::string findLongestWord(std::string s, std::vector<std::string> &dictionary) {
    std::string longest = "";
    std::sort(dictionary.begin(), dictionary.end());
    for (const std::string &word : dictionary) {
        if (isSubsequence(s, word)) {
            if (word.size() > longest.size()) {
                longest = word;
            }
        }
    }
    return longest;
}
```
1. First, sort the dictionary so that word comparison will be in lexicographical order.
2. Define a helper function `isSubsequence` which checks if a given word can be formed by deleting some of the given string characters.
3. Iterate through the dictionary and for each word, check if it can be formed using the helper function. If a word can be formed and its length is longer than the current longest word, set it as the new longest word.
4. Return the longest word found, or an empty string if no match was found.

## A solution in Python

```python
def findLongestWord(s, dictionary):
    def is_subsequence(target, source):
        iter_source = iter(source)
        return all(char in iter_source for char in target)

    dictionary = sorted(dictionary)
    longest = ''
    for word in dictionary:
        if is_subsequence(word, s) and len(word) > len(longest):
            longest = word
    return longest
```
1. First, sort the dictionary so that word comparison will be in lexicographical order.
2. Define a helper function `isSubsequence` which checks if a given word can be formed by deleting some of the given string characters.
3. Iterate through the dictionary and for each word, check if it can be formed using the helper function. If a word can be formed and its length is longer than the current longest word, set it as the new longest word.
4. Return the longest word found, or an empty string if no match was found.

## A solution in Javascript

```javascript
function findLongestWord(s, dictionary) {
    function isSubsequence(s, word) {
        let i = 0, j = 0;
        while (i < s.length && j < word.length) {
            if (s[i] === word[j]) {
                j++;
            }
            i++;
        }
        return j === word.length;
    }

    dictionary.sort();
    let longest = '';
    for (let word of dictionary) {
        if (isSubsequence(s, word)) {
            if (word.length > longest.length) {
                longest = word;
            }
        }
    }
    return longest;
}
```
1. First, sort the dictionary so that word comparison will be in lexicographical order.
2. Define a helper function `isSubsequence` which checks if a given word can be formed by deleting some of the given string characters.
3. Iterate through the dictionary and for each word, check if it can be formed using the helper function. If a word can be formed and its length is longer than the current longest word, set it as the new longest word.
4. Return the longest word found, or an empty string if no match was found.


# Contiguous Array

- slug: contiguous-array
- difficulty: Medium

Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`.

**Example 1:**

**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1.

**Example 2:**

**Input:** nums = \[0,1,0\]
**Output:** 2
**Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `nums[i]` is either `0` or `1`.

## A solution in Java

```java
public int findMaxLength(int[] nums) {
    HashMap<Integer, Integer> counts = new HashMap<>();
    counts.put(0, -1);
    int max_len = 0, count = 0;
    for (int i = 0; i < nums.length; i++) {
        count += (nums[i] == 1) ? 1 : -1;
        if (counts.containsKey(count))
            max_len = Math.max(max_len, i - counts.get(count));
        else
            counts.put(count, i);
    }
    return max_len;
}
```
This algorithm iterates through the given binary array and maintains a running count. It uses a hash table called "counts" to store the count-value pairs in which the count is the key and its index is the value. We initialize the hash table with a pair {0: -1} to handle the edge case when the first few elements form a valid subarray.

For each element in the array, we increment the count by 1 if the element is 1 or decrement by 1 if it is 0. The count then represents the difference between 1's and 0's in the array up to the current index.

Then, we check if the current count is present in the hash table. If it is, that means we have encountered an equal number of 1's and 0's between the current index and the index stored under the current count in the hash table, so we compare this subarray's length with the previously stored max length of a valid subarray. Finally, we store the current count and index in the hash table if it isn't already present.

## A solution in C++

```cpp
int findMaxLength(vector<int>& nums) {
    unordered_map<int, int> counts;
    counts[0] = -1;
    int max_len = 0, count = 0;
    for (int i = 0; i < nums.size(); i++) {
        count += (nums[i] == 1) ? 1 : -1;
        if (counts.count(count))
            max_len = max(max_len, i - counts[count]);
        else
            counts[count] = i;
    }
    return max_len;
}
```
This algorithm iterates through the given binary array and maintains a running count. It uses a hash table called "counts" to store the count-value pairs in which the count is the key and its index is the value. We initialize the hash table with a pair {0: -1} to handle the edge case when the first few elements form a valid subarray.

For each element in the array, we increment the count by 1 if the element is 1 or decrement by 1 if it is 0. The count then represents the difference between 1's and 0's in the array up to the current index.

Then, we check if the current count is present in the hash table. If it is, that means we have encountered an equal number of 1's and 0's between the current index and the index stored under the current count in the hash table, so we compare this subarray's length with the previously stored max length of a valid subarray. Finally, we store the current count and index in the hash table if it isn't already present.

## A solution in Python

```python
def findMaxLength(nums):
    counts = {0: -1}
    max_len = count = 0
    for i, num in enumerate(nums):
        count += 1 if num == 1 else -1
        if count in counts:
            max_len = max(max_len, i - counts[count])
        else:
            counts[count] = i
    return max_len
```
This algorithm iterates through the given binary array and maintains a running count. It uses a hash table called "counts" to store the count-value pairs in which the count is the key and its index is the value. We initialize the hash table with a pair {0: -1} to handle the edge case when the first few elements form a valid subarray.

For each element in the array, we increment the count by 1 if the element is 1 or decrement by 1 if it is 0. The count then represents the difference between 1's and 0's in the array up to the current index.

Then, we check if the current count is present in the hash table. If it is, that means we have encountered an equal number of 1's and 0's between the current index and the index stored under the current count in the hash table, so we compare this subarray's length with the previously stored max length of a valid subarray. Finally, we store the current count and index in the hash table if it isn't already present.

## A solution in Javascript

```javascript
function findMaxLength(nums) {
    let counts = new Map();
    counts.set(0, -1);
    let max_len = 0, count = 0;
    for (let i = 0; i < nums.length; i++) {
        count += (nums[i] === 1) ? 1 : -1;
        if (counts.has(count))
            max_len = Math.max(max_len, i - counts.get(count));
        else
            counts.set(count, i);
    }
    return max_len;
}
```
This algorithm iterates through the given binary array and maintains a running count. It uses a hash table called "counts" to store the count-value pairs in which the count is the key and its index is the value. We initialize the hash table with a pair {0: -1} to handle the edge case when the first few elements form a valid subarray.

For each element in the array, we increment the count by 1 if the element is 1 or decrement by 1 if it is 0. The count then represents the difference between 1's and 0's in the array up to the current index.

Then, we check if the current count is present in the hash table. If it is, that means we have encountered an equal number of 1's and 0's between the current index and the index stored under the current count in the hash table, so we compare this subarray's length with the previously stored max length of a valid subarray. Finally, we store the current count and index in the hash table if it isn't already present.


# Beautiful Arrangement

- slug: beautiful-arrangement
- difficulty: Medium

Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true:

*   `perm[i]` is divisible by `i`.
*   `i` is divisible by `perm[i]`.

Given an integer `n`, return _the **number** of the **beautiful arrangements** that you can construct_.

**Example 1:**

**Input:** n = 2
**Output:** 2
**Explanation:**
The first beautiful arrangement is \[1,2\]:
    - perm\[1\] = 1 is divisible by i = 1
    - perm\[2\] = 2 is divisible by i = 2
The second beautiful arrangement is \[2,1\]:
    - perm\[1\] = 2 is divisible by i = 1
    - i = 2 is divisible by perm\[2\] = 1

**Example 2:**

**Input:** n = 1
**Output:** 1

**Constraints:**

*   `1 <= n <= 15`

## A solution in Java

```java
int countArrangement(int n) {
    int[] res = new int[]{0};
    boolean[] visited = new boolean[n+1];
    helper(n, 1, visited, res);
    return res[0];
}

void helper(int n, int idx, boolean[] visited, int[] res) {
    if (idx > n) {
        res[0]++;
    }

    for(int i=1; i<=n; i++){
        if (!visited[i] && (idx % i == 0 || i % idx == 0)) {
            visited[i] = true;
            helper(n, idx+1, visited, res);
            visited[i] = false;
        }
    }
}
```
This problem can be solved using a backtracking algorithm. We can start by creating a helper function (a recursive function) that will iterate through all possibilities. The base case for the recursion is when the current index (idx) is greater than the given integer n. When this condition is met, increment the result (res) by 1.

In the helper function, iterate a loop for each integer i (1 <= i <= n). Check if i is not visited (visited[i] == false) and if i is divisible by idx or idx is divisible by i. If either of these conditions is true, mark i as visited and call the helper function recursively with the index incremented by 1. After the recursive call, unmark i as visited to backtrack to the previous state.

Initially, pass an array or vector of visited flags, which are all initialized to false along with the integer n and index 1 to the helper function. The helper function will traverse all possibilities and return the result (res) as the final count of beautiful arrangements.

## A solution in C++

```cpp
int countArrangement(int n) {
    int res=0;
    vector<bool> visited(n+1,false);
    helper(n,1,visited,res);
    return res;
}

void helper(int n, int idx, vector<bool>& visited, int& res) {
    if (idx > n) {
        ++res;
    }

    for(int i=1; i<=n; i++){
        if (!visited[i] && (idx % i == 0 || i % idx == 0)) {
            visited[i] = true;
            helper(n, idx+1, visited, res);
            visited[i] = false;
        }
    }
}
```
This problem can be solved using a backtracking algorithm. We can start by creating a helper function (a recursive function) that will iterate through all possibilities. The base case for the recursion is when the current index (idx) is greater than the given integer n. When this condition is met, increment the result (res) by 1.

In the helper function, iterate a loop for each integer i (1 <= i <= n). Check if i is not visited (visited[i] == false) and if i is divisible by idx or idx is divisible by i. If either of these conditions is true, mark i as visited and call the helper function recursively with the index incremented by 1. After the recursive call, unmark i as visited to backtrack to the previous state.

Initially, pass an array or vector of visited flags, which are all initialized to false along with the integer n and index 1 to the helper function. The helper function will traverse all possibilities and return the result (res) as the final count of beautiful arrangements.

## A solution in Python

```python
def countArrangement(n: int) -> int:
    def helper(idx: int, visited: List[bool], n: int) -> int:
        if idx > n:
            return 1

        count = 0
        for i in range(1, n+1):
            if not visited[i] and (idx % i == 0 or i % idx == 0):
                visited[i] = True
                count += helper(idx+1, visited, n)
                visited[i] = False

        return count

    visited = [False] * (n+1)
    return helper(1, visited, n)
```
This problem can be solved using a backtracking algorithm. We can start by creating a helper function (a recursive function) that will iterate through all possibilities. The base case for the recursion is when the current index (idx) is greater than the given integer n. When this condition is met, increment the result (res) by 1.

In the helper function, iterate a loop for each integer i (1 <= i <= n). Check if i is not visited (visited[i] == false) and if i is divisible by idx or idx is divisible by i. If either of these conditions is true, mark i as visited and call the helper function recursively with the index incremented by 1. After the recursive call, unmark i as visited to backtrack to the previous state.

Initially, pass an array or vector of visited flags, which are all initialized to false along with the integer n and index 1 to the helper function. The helper function will traverse all possibilities and return the result (res) as the final count of beautiful arrangements.

## A solution in Javascript

```javascript
function countArrangement(n) {
    let res=0;
    let visited=Array(n+1).fill(false);
    helper(n,1,visited);
    return res;

    function helper(n, idx, visited) {
        if (idx > n) {
            ++res;
        }

        for(let i=1; i<=n; i++){
            if (!visited[i] && (idx % i === 0 || i % idx === 0)) {
                visited[i] = true;
                helper(n, idx+1, visited);
                visited[i] = false;
            }
        }
    }
}
```
This problem can be solved using a backtracking algorithm. We can start by creating a helper function (a recursive function) that will iterate through all possibilities. The base case for the recursion is when the current index (idx) is greater than the given integer n. When this condition is met, increment the result (res) by 1.

In the helper function, iterate a loop for each integer i (1 <= i <= n). Check if i is not visited (visited[i] == false) and if i is divisible by idx or idx is divisible by i. If either of these conditions is true, mark i as visited and call the helper function recursively with the index incremented by 1. After the recursive call, unmark i as visited to backtrack to the previous state.

Initially, pass an array or vector of visited flags, which are all initialized to false along with the integer n and index 1 to the helper function. The helper function will traverse all possibilities and return the result (res) as the final count of beautiful arrangements.


# Word Abbreviation

- slug: word-abbreviation
- difficulty: Hard

Given an array of **distinct** strings `words`, return _the minimal possible **abbreviations** for every word_.

The following are the rules for a string abbreviation:

1.  The **initial** abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.
2.  If more than one word shares the **same** abbreviation, then perform the following operation:
    *   **Increase** the prefix (characters in the first part) of each of their abbreviations by `1`.
        *   For example, say you start with the words `[ "abcdef ", "abndef "]` both initially abbreviated as `"a4f "`. Then, a sequence of operations would be `[ "a4f ", "a4f "]` -> `[ "ab3f ", "ab3f "]` -> `[ "abc2f ", "abn2f "]`.
    *   This operation is repeated until every abbreviation is **unique**.
3.  At the end, if an abbreviation did not make a word shorter, then keep it as the original word.

**Example 1:**

**Input:** words = \["like","god","internal","me","internet","interval","intension","face","intrusion"\]
**Output:** \["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"\]

**Example 2:**

**Input:** words = \["aa","aaa"\]
**Output:** \["aa","aaa"\]

**Constraints:**

*   `1 <= words.length <= 400`
*   `2 <= words[i].length <= 400`
*   `words[i]` consists of lowercase English letters.
*   All the strings of `words` are **unique**.

## A solution in Java

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

public String[] wordsAbbreviation(String[] words) {
    int n = words.length;
    String[] abbr = new String[n];
    int[] prefixLen = new int[n];

    for (int i = 0; i < n; i++) {
        abbr[i] = abbrev(words[i], 1);
        prefixLen[i] = 1;
    }

    for (int i = 0; i < n; i++) {
        while (true) {
            Map<String, int[]> groups = new HashMap<>();
            for (int j = 0; j < n; j++) {
                if (abbr[i].equals(abbr[j])) {
                    if (!groups.containsKey(abbr[j])) {
                        groups.put(abbr[j], new int[]{0, 0});
                    }
                    groups.get(abbr[j])[0]++;
                    groups.get(abbr[j])[1] = j;
                }
            }
            if (groups.get(abbr[i])[0] == 1) {
                break;
            }
            abbr[groups.get(abbr[i])[1]] = abbrev(words[groups.get(abbr[i])[1]], ++prefixLen[groups.get(abbr[i])[1]]);
            abbr[i] = abbrev(words[i], ++prefixLen[i]);
        }
    }

    return abbr;
}

private String abbrev(String s, int k) {
    int n = s.length();
    if (k >= n - 2) {
        return s;
    }
    return s.substring(0, k + 1) + Integer.toString(n - k - 2) + s.charAt(n - 1);
}
```
1. Initialize abbreviation lists and prefix lengths for each word.
2. For each word, calculate its initial abbreviation based on the rule 1.
3. Check if there are any words that share the same abbreviation.
4. If there are, increase the prefix of those words as stated in rule 2 and update the abbreviation.
5. Repeat steps 3 and 4 until every abbreviation is unique.
6. Once all abbreviations are unique, return the list of abbreviations.

## A solution in C++

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

std::string abbrev(const std::string& s, int k) {
    int n = s.length();
    if (k >= n - 2) {
        return s;
    }
    return s.substr(0, k + 1) + std::to_string(n - k - 2) + s.back();
}

std::vector<std::string> wordsAbbreviation(std::vector<std::string>& words) {
    int n = words.size();
    std::vector<std::string> abbr;
    std::vector<int> prefixLen(n, 1);

    for (int i = 0; i < n; ++i) {
        abbr.push_back(abbrev(words[i], 1));
    }

    for (int i = 0; i < n; ++i) {
        while (true) {
            std::unordered_map<std::string, std::vector<int>> groups;
            for (int j = i + 1; j < n; ++j) {
                if (abbr[i] == abbr[j]) {
                    groups[abbr[j]].push_back(j);
                }
            }
            if (groups.empty()) {
                break;
            }
            for (const auto &group : groups) {
                for (int id : group.second) {
                    abbr[id] = abbrev(words[id], ++prefixLen[id]);
                }
            }
            abbr[i] = abbrev(words[i], ++prefixLen[i]);
        }
    }

    return abbr;
}
```
1. Initialize abbreviation lists and prefix lengths for each word.
2. For each word, calculate its initial abbreviation based on the rule 1.
3. Check if there are any words that share the same abbreviation.
4. If there are, increase the prefix of those words as stated in rule 2 and update the abbreviation.
5. Repeat steps 3 and 4 until every abbreviation is unique.
6. Once all abbreviations are unique, return the list of abbreviations.

## A solution in Python

```python
def wordsAbbreviation(words):
    def abbrev(word, k):
        return word[:k+1] + str(len(word) - k - 2) + word[-1] if k < len(word) - 2 else word

    n = len(words)
    abbr = [abbrev(word, 1) for word in words]
    prefix_len = [1] * n

    for i in range(n):
        while abbr.count(abbr[i]) > 1:
            groups = {}
            for j in range(i + 1, n):
                if abbr[i] == abbr[j]:
                    if abbr[j] not in groups:
                        groups[abbr[j]] = []
                    groups[abbr[j]].append(j)
            for group_members in groups.values():
                for j in group_members:
                    abbr[j] = abbrev(words[j], prefix_len[j] + 1)
                    prefix_len[j] += 1
            abbr[i] = abbrev(words[i], prefix_len[i] + 1)
            prefix_len[i] += 1

    return abbr
```
1. Initialize abbreviation lists and prefix lengths for each word.
2. For each word, calculate its initial abbreviation based on the rule 1.
3. Check if there are any words that share the same abbreviation.
4. If there are, increase the prefix of those words as stated in rule 2 and update the abbreviation.
5. Repeat steps 3 and 4 until every abbreviation is unique.
6. Once all abbreviations are unique, return the list of abbreviations.

## A solution in Javascript

```javascript
function wordsAbbreviation(words) {
    function abbrev(word, k) {
        return k < word.length - 2 ? word.slice(0, k + 1) + (word.length - k - 2) + word.slice(-1) : word;
    }

    const n = words.length;
    const abbr = words.map(word => abbrev(word, 1));
    const prefixLen = new Array(n).fill(1);

    for (let i = 0; i < n; i++) {
        while (abbr.filter(a => a === abbr[i]).length > 1) {
            const groups = {};
            for (let j = i + 1; j < n; j++) {
                if (abbr[i] === abbr[j]) {
                    if (!groups[abbr[j]]) {
                        groups[abbr[j]] = [];
                    }
                    groups[abbr[j]].push(j);
                }
            }
            for (const groupMembers of Object.values(groups)) {
                for (const j of groupMembers) {
                    abbr[j] = abbrev(words[j], prefixLen[j] + 1);
                    prefixLen[j]++;
                }
            }
            abbr[i] = abbrev(words[i], prefixLen[i] + 1);
            prefixLen[i]++;
        }
    }

    return abbr;
}
```
1. Initialize abbreviation lists and prefix lengths for each word.
2. For each word, calculate its initial abbreviation based on the rule 1.
3. Check if there are any words that share the same abbreviation.
4. If there are, increase the prefix of those words as stated in rule 2 and update the abbreviation.
5. Repeat steps 3 and 4 until every abbreviation is unique.
6. Once all abbreviations are unique, return the list of abbreviations.


# Random Pick with Weight

- slug: random-pick-with-weight
- difficulty: Medium

You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.

You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.

*   For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).

**Example 1:**

**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]

**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.

**Example 2:**

**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]

**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.

Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.

**Constraints:**

*   `1 <= w.length <= 104`
*   `1 <= w[i] <= 105`
*   `pickIndex` will be called at most `104` times.

## A solution in Java

```java
public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public ListNode swapNodes(ListNode head, int k) {
    ListNode first = head, second = head, temp = head;
    for (int i = 0; i < k - 1; i++) {
        temp = temp.next;
    }
    first = temp;
    temp = temp.next;
    while (temp != null) {
        temp = temp.next;
        second = second.next;
    }
    int tmp = first.val;
    first.val = second.val;
    second.val = tmp;

    return head;
}
```
1. Set three pointers (first, second, and temp) to point to the head of the linked list.
2. Move the temp pointer forward by (k - 1) times to point to the kth node from the beginning.
3. Set the first pointer to point to the temp (kth node from the beginning).
4. Move the temp pointer to the next node, while moving second pointer to the next node as the temp pointer reaches the end of the list.
5. When the temp pointer reaches the end of the list, the second pointer will be at the kth node from the end of the list.
6. Swap the values of the nodes pointed by the first and second pointers.
7. Return the head of the modified linked list.

## A solution in C++

```cpp
#include <iostream>

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode* swapNodes(ListNode* head, int k) {
    ListNode *first = head, *second = head, *temp = head;
    for (int i = 0; i < k - 1; i++) {
        temp = temp->next;
    }
    first = temp;
    temp = temp->next;
    while (temp) {
        temp = temp->next;
        second = second->next;
    }
    std::swap(first->val, second->val);
    return head;
}
```
1. Set three pointers (first, second, and temp) to point to the head of the linked list.
2. Move the temp pointer forward by (k - 1) times to point to the kth node from the beginning.
3. Set the first pointer to point to the temp (kth node from the beginning).
4. Move the temp pointer to the next node, while moving second pointer to the next node as the temp pointer reaches the end of the list.
5. When the temp pointer reaches the end of the list, the second pointer will be at the kth node from the end of the list.
6. Swap the values of the nodes pointed by the first and second pointers.
7. Return the head of the modified linked list.

## A solution in Python

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

def swapNodes(head, k):
    first, second, temp = head, head, head
    for _ in range(k - 1):
        temp = temp.next
    first = temp
    temp = temp.next
    while temp:
        temp = temp.next
        second = second.next

    first.val, second.val = second.val, first.val
    return head
```
1. Set three pointers (first, second, and temp) to point to the head of the linked list.
2. Move the temp pointer forward by (k - 1) times to point to the kth node from the beginning.
3. Set the first pointer to point to the temp (kth node from the beginning).
4. Move the temp pointer to the next node, while moving second pointer to the next node as the temp pointer reaches the end of the list.
5. When the temp pointer reaches the end of the list, the second pointer will be at the kth node from the end of the list.
6. Swap the values of the nodes pointed by the first and second pointers.
7. Return the head of the modified linked list.

## A solution in Javascript

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

function swapNodes(head, k) {
    let first = head, second = head, temp = head;
    for (let i = 0; i < k - 1; i++) {
        temp = temp.next;
    }
    first = temp;
    temp = temp.next;
    while (temp !== null) {
        temp = temp.next;
        second = second.next;
    }

    [first.val, second.val] = [second.val, first.val];
    return head;
}
```
1. Set three pointers (first, second, and temp) to point to the head of the linked list.
2. Move the temp pointer forward by (k - 1) times to point to the kth node from the beginning.
3. Set the first pointer to point to the temp (kth node from the beginning).
4. Move the temp pointer to the next node, while moving second pointer to the next node as the temp pointer reaches the end of the list.
5. When the temp pointer reaches the end of the list, the second pointer will be at the kth node from the end of the list.
6. Swap the values of the nodes pointed by the first and second pointers.
7. Return the head of the modified linked list.


# Minesweeper

- slug: minesweeper
- difficulty: Medium

Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!

You are given an `m x n` char matrix `board` representing the game board where:

*   `'M'` represents an unrevealed mine,
*   `'E'` represents an unrevealed empty square,
*   `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),
*   digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and
*   `'X'` represents a revealed mine.

You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`).

Return _the board after revealing this position according to the following rules_:

1.  If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`.
2.  If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively.
3.  If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines.
4.  Return the board when no more squares will be revealed.

**Example 1:**

**Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]

**Example 2:**

**Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]

**Constraints:**

*   `m == board.length`
*   `n == board[i].length`
*   `1 <= m, n <= 50`
*   `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`.
*   `click.length == 2`
*   `0 <= clickr < m`
*   `0 <= clickc < n`
*   `board[clickr][clickc]` is either `'M'` or `'E'`.

## A solution in Java

    The algorithm starts by checking if the clicked cell contains a mine ('M'). If it does, the cell is updated with an 'X' to show it's been clicked.

If there's no mine, the algorithm calculates the number of adjacent mines. If there are one or more mines, the cell is updated with the number of adjacent mines. If there are 0 mines, the cell is updated with 'B' for Blank and its adjacent cells are recursively checked.

The algorithm keeps revealing the cells according to the rules until it reaches the boundary or cells that have already been revealed.

## A solution in C++

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

void reveal(vector<vector<char>>& board, int row, int col, vector<vector<int>>& directions) {
    if (row < 0 || row >= board.size() || col < 0 || col >= board[0].size() || board[row][col] != 'E') return;

    int mines = 0;
    for (auto& dir : directions) {
        int newRow = row + dir[0], newCol = col + dir[1];
        if (newRow >= 0 && newRow < board.size() && newCol >= 0 && newCol < board[0].size() && board[newRow][newCol] == 'M') mines++;
    }

    if (mines > 0) {
        board[row][col] = '0' + mines;
    } else {
        board[row][col] = 'B';
        for (auto& dir : directions) {
            reveal(board, row + dir[0], col + dir[1], directions);
        }
    }
}

vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
    int row = click[0], col = click[1];

...
}

```
The algorithm starts by checking if the clicked cell contains a mine ('M'). If it does, the cell is updated with an 'X' to show it's been clicked.

If there's no mine, the algorithm calculates the number of adjacent mines. If there are one or more mines, the cell is updated with the number of adjacent mines. If there are 0 mines, the cell is updated with 'B' for Blank and its adjacent cells are recursively checked.

The algorithm keeps revealing the cells according to the rules until it reaches the boundary or cells that have already been revealed.

## A solution in Python

```python
from typing import List

def reveal(board: List[List[str]], row: int, col: int, directions: List[List[int]]) -> None:
    if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]) or board[row][col] != 'E':
        return

    mines = 0
    for dir in directions:
        newRow, newCol = row + dir[0], col + dir[1]
        if newRow >= 0 and newRow < len(board) and newCol >= 0 and newCol < len(board[0]) and board[newRow][newCol] == 'M':
            mines += 1

    if mines > 0:
        board[row][col] = str(mines)
    else:
        board[row][col] = 'B'
        for dir in directions:
            reveal(board, row + dir[0], col + dir[1], directions)

def updateBoard(board: List[List[str]], click: List[int]) -> List[List[str]]:
    row, col = click

    if board[row][col] == 'M':
        board[row][col] = 'X'
    else:
        directions = [[1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1], [0, 1], [1, 1]]
        reveal(board, row, col, directions)

    return board
```
The algorithm starts by checking if the clicked cell contains a mine ('M'). If it does, the cell is updated with an 'X' to show it's been clicked.

If there's no mine, the algorithm calculates the number of adjacent mines. If there are one or more mines, the cell is updated with the number of adjacent mines. If there are 0 mines, the cell is updated with 'B' for Blank and its adjacent cells are recursively checked.

The algorithm keeps revealing the cells according to the rules until it reaches the boundary or cells that have already been revealed.

## A solution in Javascript

    The algorithm starts by checking if the clicked cell contains a mine ('M'). If it does, the cell is updated with an 'X' to show it's been clicked.

If there's no mine, the algorithm calculates the number of adjacent mines. If there are one or more mines, the cell is updated with the number of adjacent mines. If there are 0 mines, the cell is updated with 'B' for Blank and its adjacent cells are recursively checked.

The algorithm keeps revealing the cells according to the rules until it reaches the boundary or cells that have already been revealed.


# Minimum Absolute Difference in BST

- slug: minimum-absolute-difference-in-bst
- difficulty: Easy

Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_.

**Example 1:**

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

**Example 2:**

**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1

**Constraints:**

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

**Note:** This question is the same as 783: [https://leetcode.com/problems/minimum-distance-between-bst-nodes/](https://leetcode.com/problems/minimum-distance-between-bst-nodes/)

## A solution in Java

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

public class Solution {
    private int result = Integer.MAX_VALUE;
    private TreeNode prev;

    public int getMinimumDifference(TreeNode root) {
        inorderTraversal(root);
        return result;
    }

    private void inorderTraversal(TreeNode node) {
        if (node == null) return;
        inorderTraversal(node.left);
        if (prev != null) {
            result = Math.min(result, node.val - prev.val);
        }
        prev = node;
        inorderTraversal(node.right);
    }
}
```
The algorithm uses an in-order traversal of the binary search tree to find the minimum absolute difference between the values of any two different nodes in the tree. Since it's an in-order traversal, we are going through the nodes in ascending order, which makes it easier to calculate and compare differences. During the traversal, we maintain a `prev` variable that stores the previously visited node to calculate the difference with the current node. If the difference between the current node and the previous node is smaller than the current result, we update the result accordingly. At the end of the traversal, the result will be the minimum absolute difference between any two different nodes in the tree.

## A solution in C++

```cpp
#include <algorithm>
#include <climits>

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

class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        int result = INT_MAX, prev = -1;
        minimumDifference(root, result, prev);
        return result;
    }

    void minimumDifference(TreeNode* node, int& result, int& prev) {
        if (!node) return;
        minimumDifference(node->left, result, prev);
        if (prev != -1) {
            result = std::min(result, node->val - prev);
        }
        prev = node->val;
        minimumDifference(node->right, result, prev);
    }
};
```
The algorithm uses an in-order traversal of the binary search tree to find the minimum absolute difference between the values of any two different nodes in the tree. Since it's an in-order traversal, we are going through the nodes in ascending order, which makes it easier to calculate and compare differences. During the traversal, we maintain a `prev` variable that stores the previously visited node to calculate the difference with the current node. If the difference between the current node and the previous node is smaller than the current result, we update the result accordingly. At the end of the traversal, the result will be the minimum absolute difference between any two different nodes in the tree.

## A solution in Python

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

class Solution:
    def getMinimumDifference(self, root: TreeNode) -> int:
        result = float('inf')
        prev = None

        def inorderTraversal(node):
            nonlocal result, prev
            if node is None:
                return
            inorderTraversal(node.left)
            if prev is not None:
                result = min(result, node.val - prev.val)
            prev = node
            inorderTraversal(node.right)

        inorderTraversal(root)
        return result
```
The algorithm uses an in-order traversal of the binary search tree to find the minimum absolute difference between the values of any two different nodes in the tree. Since it's an in-order traversal, we are going through the nodes in ascending order, which makes it easier to calculate and compare differences. During the traversal, we maintain a `prev` variable that stores the previously visited node to calculate the difference with the current node. If the difference between the current node and the previous node is smaller than the current result, we update the result accordingly. At the end of the traversal, the result will be the minimum absolute difference between any two different nodes in the tree.

## A solution in Javascript

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

function getMinimumDifference(root) {
    let result = Number.MAX_VALUE, prev = null;

    function inorderTraversal(node) {
        if (!node) return;
        inorderTraversal(node.left);
        if (prev) {
            result = Math.min(result, node.val - prev.val);
        }
        prev = node;
        inorderTraversal(node.right);
    }

    inorderTraversal(root);
    return result;
}
```
The algorithm uses an in-order traversal of the binary search tree to find the minimum absolute difference between the values of any two different nodes in the tree. Since it's an in-order traversal, we are going through the nodes in ascending order, which makes it easier to calculate and compare differences. During the traversal, we maintain a `prev` variable that stores the previously visited node to calculate the difference with the current node. If the difference between the current node and the previous node is smaller than the current result, we update the result accordingly. At the end of the traversal, the result will be the minimum absolute difference between any two different nodes in the tree.


# Lonely Pixel I

- slug: lonely-pixel-i
- difficulty: Medium

Given an `m x n` `picture` consisting of black `'B'` and white `'W'` pixels, return _the number of **black** lonely pixels_.

A black lonely pixel is a character `'B'` that located at a specific position where the same row and same column don't have **any other** black pixels.

**Example 1:**

**Input:** picture = \[\[ "W ", "W ", "B "\],\[ "W ", "B ", "W "\],\[ "B ", "W ", "W "\]\]
**Output:** 3
**Explanation:** All the three 'B's are black lonely pixels.

**Example 2:**

**Input:** picture = \[\[ "B ", "B ", "B "\],\[ "B ", "B ", "W "\],\[ "B ", "B ", "B "\]\]
**Output:** 0

**Constraints:**

*   `m == picture.length`
*   `n == picture[i].length`
*   `1 <= m, n <= 500`
*   `picture[i][j]` is `'W'` or `'B'`.

## A solution in Java

```java
public int findLonelyPixel(char[][] picture) {
    int m = picture.length, n = picture[0].length;
    int[] row = new int[m], col = new int[n];

    for(int i = 0; i < m; ++i) {
        for(int j = 0; j < n; ++j) {
            if(picture[i][j] == 'B') {
                row[i]++;
                col[j]++;
            }
        }
    }

    int lonely = 0;
    for(int i = 0; i < m; ++i) {
        for(int j = 0; j < n; ++j) {
            if(picture[i][j] == 'B' && row[i] == 1 && col[j] == 1) {
                lonely++;
            }
        }
    }

    return lonely;
}
```
The algorithm for each of the above implementations is the same, so I will explain it at a high level. In this problem, we are given a picture of black and white pixels, and we want to find the number of black lonely pixels. A black lonely pixel is a pixel that has no other adjacent black pixels in the same row or column.

To count the number of black pixels in each row and column, we can create two arrays: one for rows (with the length equal to the number of rows in the picture) and one for columns (with the length equal to the number of columns in the picture). We then traverse through the picture, and for each black pixel we see, we increment the respective row and column counts in our row and column arrays.

After we have counted the number of black pixels in each row and column, we can traverse the picture again to find lonely pixels. For each black pixel, we check if it is a lonely pixel by confirming that the row count and the column count for that pixel are both equal to 1. If we find such a pixel, we increment the lonely count.

At the end, we return the total count of lonely pixels found during the traversal.

This algorithm runs in O(m * n) time, where m is the number of rows and n is the number of columns in the picture.

## A solution in C++

```cpp
int findLonelyPixel(vector<vector<char>>& picture) {
    int m = picture.size(), n = picture[0].size();
    vector<int> row(m, 0), col(n, 0);

    for(int i = 0; i < m; ++i) {
        for(int j = 0; j < n; ++j) {
            if(picture[i][j] == 'B') {
                row[i]++;
                col[j]++;
            }
        }
    }

    int lonely = 0;
    for(int i = 0; i < m; ++i) {
        for(int j = 0; j < n; ++j) {
            if(picture[i][j] == 'B' && row[i] == 1 && col[j] == 1) {
                lonely++;
            }
        }
    }

    return lonely;
}
```
The algorithm for each of the above implementations is the same, so I will explain it at a high level. In this problem, we are given a picture of black and white pixels, and we want to find the number of black lonely pixels. A black lonely pixel is a pixel that has no other adjacent black pixels in the same row or column.

To count the number of black pixels in each row and column, we can create two arrays: one for rows (with the length equal to the number of rows in the picture) and one for columns (with the length equal to the number of columns in the picture). We then traverse through the picture, and for each black pixel we see, we increment the respective row and column counts in our row and column arrays.

After we have counted the number of black pixels in each row and column, we can traverse the picture again to find lonely pixels. For each black pixel, we check if it is a lonely pixel by confirming that the row count and the column count for that pixel are both equal to 1. If we find such a pixel, we increment the lonely count.

At the end, we return the total count of lonely pixels found during the traversal.

This algorithm runs in O(m * n) time, where m is the number of rows and n is the number of columns in the picture.

## A solution in Python

```python
def findLonelyPixel(picture):
    m, n = len(picture), len(picture[0])
    row, col = [0] * m, [0] * n

    for i in range(m):
        for j in range(n):
            if picture[i][j] == 'B':
                row[i] += 1
                col[j] += 1

    lonely = 0
    for i in range(m):
        for j in range(n):
            if picture[i][j] == 'B' and row[i] == 1 and col[j] == 1:
                lonely += 1

    return lonely
```
The algorithm for each of the above implementations is the same, so I will explain it at a high level. In this problem, we are given a picture of black and white pixels, and we want to find the number of black lonely pixels. A black lonely pixel is a pixel that has no other adjacent black pixels in the same row or column.

To count the number of black pixels in each row and column, we can create two arrays: one for rows (with the length equal to the number of rows in the picture) and one for columns (with the length equal to the number of columns in the picture). We then traverse through the picture, and for each black pixel we see, we increment the respective row and column counts in our row and column arrays.

After we have counted the number of black pixels in each row and column, we can traverse the picture again to find lonely pixels. For each black pixel, we check if it is a lonely pixel by confirming that the row count and the column count for that pixel are both equal to 1. If we find such a pixel, we increment the lonely count.

At the end, we return the total count of lonely pixels found during the traversal.

This algorithm runs in O(m * n) time, where m is the number of rows and n is the number of columns in the picture.

## A solution in Javascript

```javascript
function findLonelyPixel(picture) {
    let m = picture.length, n = picture[0].length;
    let row = new Array(m).fill(0), col = new Array(n).fill(0);

    for(let i = 0; i < m; ++i) {
        for(let j = 0; j < n; ++j) {
            if(picture[i][j] == 'B') {
                row[i]++;
                col[j]++;
            }
        }
    }

    let lonely = 0;
    for(let i = 0; i < m; ++i) {
        for(let j = 0; j < n; ++j) {
            if(picture[i][j] == 'B' && row[i] == 1 && col[j] == 1) {
                lonely++;
            }
        }
    }

    return lonely;
}
```
The algorithm for each of the above implementations is the same, so I will explain it at a high level. In this problem, we are given a picture of black and white pixels, and we want to find the number of black lonely pixels. A black lonely pixel is a pixel that has no other adjacent black pixels in the same row or column.

To count the number of black pixels in each row and column, we can create two arrays: one for rows (with the length equal to the number of rows in the picture) and one for columns (with the length equal to the number of columns in the picture). We then traverse through the picture, and for each black pixel we see, we increment the respective row and column counts in our row and column arrays.

After we have counted the number of black pixels in each row and column, we can traverse the picture again to find lonely pixels. For each black pixel, we check if it is a lonely pixel by confirming that the row count and the column count for that pixel are both equal to 1. If we find such a pixel, we increment the lonely count.

At the end, we return the total count of lonely pixels found during the traversal.

This algorithm runs in O(m * n) time, where m is the number of rows and n is the number of columns in the picture.


# K-diff Pairs in an Array

- slug: k-diff-pairs-in-an-array
- difficulty: Medium

Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_.

A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true:

*   `0 <= i, j < nums.length`
*   `i != j`
*   `nums[i] - nums[j] == k`

**Notice** that `|val|` denotes the absolute value of `val`.

**Example 1:**

**Input:** nums = \[3,1,4,1,5\], k = 2
**Output:** 2
**Explanation:** There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of **unique** pairs.

**Example 2:**

**Input:** nums = \[1,2,3,4,5\], k = 1
**Output:** 4
**Explanation:** There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

**Example 3:**

**Input:** nums = \[1,3,1,5,4\], k = 0
**Output:** 1
**Explanation:** There is one 0-diff pair in the array, (1, 1).

**Constraints:**

*   `1 <= nums.length <= 104`
*   `-107 <= nums[i] <= 107`
*   `0 <= k <= 107`

## A solution in Java

```java
import java.util.HashMap;
import java.util.HashSet;

public int findPairs(int[] nums, int k) {
    if (k < 0) return 0;
    HashSet<Integer> starters = new HashSet<>();
    HashMap<Integer, Integer> occurrences = new HashMap<>();
    for (int num : nums) {
        if (occurrences.containsKey(num + k)) starters.add(num);
        if (occurrences.containsKey(num - k)) starters.add(num - k);
        occurrences.put(num, occurrences.getOrDefault(num, 0) + 1);
    }
    return starters.size();
}
```
1. If k is less than 0, return 0 as there are no pairs with a negative difference.
2. Initialize an empty set called `starters` to store the unique starting elements of k-diff pairs.
3. Initialize an empty map called `occurrences` to store the occurrences of each number in the input array.
4. Iterate through the input array, and for each number, check if the number + k exists in occurrences, and the number - k exists in occurrences.
5. If either condition is true, add the corresponding starting element of the k-diff pair to the starters set, and update the occurrences map with the current number.
6. After iterating through the input array, return the size of the starters set, as it represents the number of unique k-diff pairs.

## A solution in C++

```cpp
#include <unordered_set>
#include <unordered_map>
int findPairs(vector<int>& nums, int k) {
    if (k < 0) return 0;
    unordered_set<int> starters;
    unordered_map<int, int> occurrences;
    for (int num : nums) {
        if (occurrences.count(num + k)) starters.insert(num);
        if (occurrences.count(num - k)) starters.insert(num - k);
        occurrences[num]++;
    }
    return starters.size();
}
```
1. If k is less than 0, return 0 as there are no pairs with a negative difference.
2. Initialize an empty set called `starters` to store the unique starting elements of k-diff pairs.
3. Initialize an empty map called `occurrences` to store the occurrences of each number in the input array.
4. Iterate through the input array, and for each number, check if the number + k exists in occurrences, and the number - k exists in occurrences.
5. If either condition is true, add the corresponding starting element of the k-diff pair to the starters set, and update the occurrences map with the current number.
6. After iterating through the input array, return the size of the starters set, as it represents the number of unique k-diff pairs.

## A solution in Python

```python
def find_pairs(nums, k):
    if k < 0:
        return 0
    starters = set()
    occurrences = {}
    for num in nums:
        if num + k in occurrences:
            starters.add(num)
        if num - k in occurrences:
            starters.add(num - k)
        occurrences[num] = occurrences.get(num, 0) + 1
    return len(starters)
```
1. If k is less than 0, return 0 as there are no pairs with a negative difference.
2. Initialize an empty set called `starters` to store the unique starting elements of k-diff pairs.
3. Initialize an empty map called `occurrences` to store the occurrences of each number in the input array.
4. Iterate through the input array, and for each number, check if the number + k exists in occurrences, and the number - k exists in occurrences.
5. If either condition is true, add the corresponding starting element of the k-diff pair to the starters set, and update the occurrences map with the current number.
6. After iterating through the input array, return the size of the starters set, as it represents the number of unique k-diff pairs.

## A solution in Javascript

```javascript
function findPairs(nums, k) {
    if (k < 0) return 0;
    let starters = new Set();
    let occurrences = new Map();
    for (let num of nums) {
        if (occurrences.has(num + k)) starters.add(num);
        if (occurrences.has(num - k)) starters.add(num - k);
        occurrences.set(num, (occurrences.get(num) || 0) + 1);
    }
    return starters.size;
}
```
1. If k is less than 0, return 0 as there are no pairs with a negative difference.
2. Initialize an empty set called `starters` to store the unique starting elements of k-diff pairs.
3. Initialize an empty map called `occurrences` to store the occurrences of each number in the input array.
4. Iterate through the input array, and for each number, check if the number + k exists in occurrences, and the number - k exists in occurrences.
5. If either condition is true, add the corresponding starting element of the k-diff pair to the starters set, and update the occurrences map with the current number.
6. After iterating through the input array, return the size of the starters set, as it represents the number of unique k-diff pairs.


# Lonely Pixel II

- slug: lonely-pixel-ii
- difficulty: Medium

Given an `m x n` `picture` consisting of black `'B'` and white `'W'` pixels and an integer target, return _the number of **black** lonely pixels_.

A black lonely pixel is a character `'B'` that located at a specific position `(r, c)` where:

*   Row `r` and column `c` both contain exactly `target` black pixels.
*   For all rows that have a black pixel at column `c`, they should be exactly the same as row `r`.

**Example 1:**

**Input:** picture = \[\[ "W ", "B ", "W ", "B ", "B ", "W "\],\[ "W ", "B ", "W ", "B ", "B ", "W "\],\[ "W ", "B ", "W ", "B ", "B ", "W "\],\[ "W ", "W ", "B ", "W ", "B ", "W "\]\], target = 3
**Output:** 6
**Explanation:** All the green 'B' are the black pixels we need (all 'B's at column 1 and 3).
Take 'B' at row r = 0 and column c = 1 as an example:
 - Rule 1, row r = 0 and column c = 1 both have exactly target = 3 black pixels.
 - Rule 2, the rows have black pixel at column c = 1 are row 0, row 1 and row 2. They are exactly the same as row r = 0.

**Example 2:**

**Input:** picture = \[\[ "W ", "W ", "B "\],\[ "W ", "W ", "B "\],\[ "W ", "W ", "B "\]\], target = 1
**Output:** 0

**Constraints:**

*   `m == picture.length`
*   `n == picture[i].length`
*   `1 <= m, n <= 200`
*   `picture[i][j]` is `'W'` or `'B'`.
*   `1 <= target <= min(m, n)`

## A solution in Java

```java
public int findBlackPixel(char[][] picture, int target) {
    int m = picture.length;
    int n = picture[0].length;
    int[] rows = new int[m];
    int[] cols = new int[n];
    Map<String, Integer> rowCounts = new HashMap<>();
    for (int i = 0; i < m; ++i) {
        StringBuilder row = new StringBuilder();
        for (int j = 0; j < n; ++j) {
            if (picture[i][j] == 'B') {
                rows[i]++;
                cols[j]++;
            }
            row.append(picture[i][j]);
        }
        String rowStr = row.toString();
        if (rows[i] == target)
            rowCounts.put(rowStr, rowCounts.getOrDefault(rowStr, 0) + 1);
    }
    int ans = 0;
    for (Map.Entry<String, Integer> entry : rowCounts.entrySet()) {
        String row = entry.getKey();
        int count = entry.getValue();
        if (count == target) {
            for (int j = 0; j < n; ++j) {
                if (row.charAt(j) == 'B' && cols[j] == target)
                    ans += count;
            }
        }
    }
    return ans;
}
```
1. Count the number of 'B' pixels in each row and column, and store the string representation of each valid row (rows containing `target` 'B' pixels) with a count in a hashmap.
2. Iterate over the valid rows with their counts, and for each of them check the columns where 'B' is present. If that column also has exactly `target` 'B' pixels, increment the answer by the count of that row.
3. Return the answer (total number of lonely black pixels).

## A solution in C++

```cpp
int findBlackPixel(vector<vector<char>>& picture, int target) {
    int m = picture.size();
    int n = picture[0].size();
    vector<int> rows(m, 0), cols(n, 0);
    unordered_map<string, int> rowCounts;
    for (int i = 0; i < m; ++i) {
        string row;
        for (int j = 0; j < n; ++j) {
            if (picture[i][j] == 'B') {
                rows[i]++;
                cols[j]++;
            }
            row.push_back(picture[i][j]);
        }
        if (rows[i] == target)
            rowCounts[row]++;
    }
    int ans = 0;
    for (auto &[row, count] : rowCounts) {
        if (count == target) {
            for (int j = 0; j < n; ++j) {
                if (row[j] == 'B' && cols[j] == target)
                    ans += count;
            }
        }
    }
    return ans;
}
```
1. Count the number of 'B' pixels in each row and column, and store the string representation of each valid row (rows containing `target` 'B' pixels) with a count in a hashmap.
2. Iterate over the valid rows with their counts, and for each of them check the columns where 'B' is present. If that column also has exactly `target` 'B' pixels, increment the answer by the count of that row.
3. Return the answer (total number of lonely black pixels).

## A solution in Python

```python
def findBlackPixel(picture, target):
    m, n = len(picture), len(picture[0])
    rows = [0] * m
    cols = [0] * n
    rowCounts = {}
    for i in range(m):
        row = ""
        for j in range(n):
            if picture[i][j] == 'B':
                rows[i] += 1
                cols[j] += 1
            row += picture[i][j]
        if rows[i] == target:
            rowCounts[row] = rowCounts.get(row, 0) + 1
    ans = 0
    for row, count in rowCounts.items():
        if count == target:
            for j in range(n):
                if row[j] == 'B' and cols[j] == target:
                    ans += count
    return ans
```
1. Count the number of 'B' pixels in each row and column, and store the string representation of each valid row (rows containing `target` 'B' pixels) with a count in a hashmap.
2. Iterate over the valid rows with their counts, and for each of them check the columns where 'B' is present. If that column also has exactly `target` 'B' pixels, increment the answer by the count of that row.
3. Return the answer (total number of lonely black pixels).

## A solution in Javascript

```javascript
function findBlackPixel(picture, target) {
    const m = picture.length;
    const n = picture[0].length;
    const rows = new Array(m).fill(0);
    const cols = new Array(n).fill(0);
    const rowCounts = new Map();
    for (let i = 0; i < m; ++i) {
        let row = "";
        for (let j = 0; j < n; ++j) {
            if (picture[i][j] === 'B') {
                rows[i]++;
                cols[j]++;
            }
            row += picture[i][j];
        }
        if (rows[i] === target)
            rowCounts.set(row, (rowCounts.get(row) || 0) + 1);
    }
    let ans = 0;
    for (let [row, count] of rowCounts.entries()) {
        if (count === target) {
            for (let j = 0; j < n; ++j) {
                if (row[j] === 'B' && cols[j] === target)
                    ans += count;
            }
        }
    }
    return ans;
}
```
1. Count the number of 'B' pixels in each row and column, and store the string representation of each valid row (rows containing `target` 'B' pixels) with a count in a hashmap.
2. Iterate over the valid rows with their counts, and for each of them check the columns where 'B' is present. If that column also has exactly `target` 'B' pixels, increment the answer by the count of that row.
3. Return the answer (total number of lonely black pixels).


# Encode and Decode TinyURL

- slug: encode-and-decode-tinyurl
- difficulty: Medium

> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).

TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL.

There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

Implement the `Solution` class:

*   `Solution()` Initializes the object of the system.
*   `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`.
*   `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object.

**Example 1:**

**Input:** url =  "https://leetcode.com/problems/design-tinyurl "
**Output:**  "https://leetcode.com/problems/design-tinyurl "

**Explanation:**
Solution obj = new Solution();
string tiny = obj.encode(url); // returns the encoded tiny url.
string ans = obj.decode(tiny); // returns the original url after decoding it.

**Constraints:**

*   `1 <= url.length <= 104`
*   `url` is guranteed to be a valid URL.

## A solution in Java

```java
import java.util.HashMap;
import java.util.Random;

public class Solution {
    HashMap<String, String> urlMap = new HashMap<>();
    String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public String encode(String longUrl) {
        StringBuilder keyBuilder;
        String key;

        do {
            keyBuilder = new StringBuilder();

            for (int i = 0; i < 6; i++) {
                keyBuilder.append(alphabet.charAt(new Random().nextInt(alphabet.length())));
            }

            key = keyBuilder.toString();
        } while (urlMap.containsKey(key));

        urlMap.put(key, longUrl);
        return "http://tinyurl.com/" + key;
    }

    public String decode(String shortUrl) {
        return urlMap.get(shortUrl.substring(19));
    }
}
```
The algorithm generates a random 6-character key using a combination of lowercase, uppercase letters, and digits. It then checks if the generated key already exists in the mapping. If not, it adds the long URL and its corresponding key into the mapping. The shortened URL is created by appending the key to a fixed base URL (e.g., "http://tinyurl.com/"). When decoding, it obtains the key from the given shortened URL and looks up the original long URL from the mapping. This algorithm ensures that every long URL has its unique shortened URL, and it's capable of encoding and decoding URLs successfully.

## A solution in C++

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

class Solution {
public:
    std::unordered_map<std::string, std::string> map;
    std::string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    // Encodes a URL to a shortened URL.
    std::string encode(std::string longUrl) {
        std::string key;
        while (true) {
            key.clear();
            for (int i = 0; i < 6; i++) {
                key += alphabet[rand() % alphabet.length()];
            }
            if (map.count(key) == 0) {
                map[key] = longUrl;
                break;
            }
        }
        return "http://tinyurl.com/" + key;
    }

    // Decodes a shortened URL to its original URL.
    std::string decode(std::string shortUrl) {
        return map[shortUrl.substr(19, 6)];
    }
};
```
The algorithm generates a random 6-character key using a combination of lowercase, uppercase letters, and digits. It then checks if the generated key already exists in the mapping. If not, it adds the long URL and its corresponding key into the mapping. The shortened URL is created by appending the key to a fixed base URL (e.g., "http://tinyurl.com/"). When decoding, it obtains the key from the given shortened URL and looks up the original long URL from the mapping. This algorithm ensures that every long URL has its unique shortened URL, and it's capable of encoding and decoding URLs successfully.

## A solution in Python

```python
import random
import string

class Solution:
    def __init__(self):
        self.url_map = {}
        self.alphabet = string.ascii_letters + string.digits

    def encode(self, longUrl: str) -> str:
        key = ''.join(random.choices(self.alphabet, k=6))

        while key in self.url_map:
            key = ''.join(random.choices(self.alphabet, k=6))

        self.url_map[key] = longUrl
        return "http://tinyurl.com/" + key

    def decode(self, shortUrl: str) -> str:
        return self.url_map[shortUrl[-6:]]
```
The algorithm generates a random 6-character key using a combination of lowercase, uppercase letters, and digits. It then checks if the generated key already exists in the mapping. If not, it adds the long URL and its corresponding key into the mapping. The shortened URL is created by appending the key to a fixed base URL (e.g., "http://tinyurl.com/"). When decoding, it obtains the key from the given shortened URL and looks up the original long URL from the mapping. This algorithm ensures that every long URL has its unique shortened URL, and it's capable of encoding and decoding URLs successfully.

## A solution in Javascript

```javascript
class Solution {
    constructor() {
        this.urlMap = new Map();
        this.alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    }

    encode(longUrl) {
        let key;

        do {
            key = Array.from({ length: 6 }, () => this.alphabet.charAt(Math.floor(Math.random() * this.alphabet.length))).join('');
        } while (this.urlMap.has(key));

        this.urlMap.set(key, longUrl);

        return 'http://tinyurl.com/' + key;
    }

    decode(shortUrl) {
        return this.urlMap.get(shortUrl.substr(-6));
    }
}
```
The algorithm generates a random 6-character key using a combination of lowercase, uppercase letters, and digits. It then checks if the generated key already exists in the mapping. If not, it adds the long URL and its corresponding key into the mapping. The shortened URL is created by appending the key to a fixed base URL (e.g., "http://tinyurl.com/"). When decoding, it obtains the key from the given shortened URL and looks up the original long URL from the mapping. This algorithm ensures that every long URL has its unique shortened URL, and it's capable of encoding and decoding URLs successfully.


# Construct Binary Tree from String

- slug: construct-binary-tree-from-string
- difficulty: Medium

You need to construct a binary tree from a string consisting of parenthesis and integers.

The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.

You always start to construct the **left** child node of the parent first if it exists.

**Example 1:**

**Input:** s =  "4(2(3)(1))(6(5)) "
**Output:** \[4,2,6,3,1,5\]

**Example 2:**

**Input:** s =  "4(2(3)(1))(6(5)(7)) "
**Output:** \[4,2,6,3,1,5,7\]

**Example 3:**

**Input:** s =  "-4(2(3)(1))(6(5)(7)) "
**Output:** \[-4,2,6,3,1,5,7\]

**Constraints:**

*   `0 <= s.length <= 3 * 104`
*   `s` consists of digits, `'('`, `')'`, and `'-'` only.

## A solution in Java

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

public class Solution {
    public TreeNode str2tree(String s) {
        MyInteger idx = new MyInteger(0);
        return str2treeHelper(s, idx);
    }

    private TreeNode str2treeHelper(String s, MyInteger idx) {
        if (idx.get() >= s.length()) return null;

        int sign = 1;
        if (s.charAt(idx.get()) == '-') {
            sign = -1;
            idx.increment();
        }

        int num = 0;
        while (idx.get() < s.length() && Character.isDigit(s.charAt(idx.get()))) {
            num = num * 10 + (s.charAt(idx.get()) - '0');
            idx.increment();
        }

        TreeNode node = new TreeNode(sign * num);

        if (idx.get() < s.length() && s.charAt(idx.get()) == '(') {
            idx.increment();
            node.left = str2treeHelper(s, idx);
            idx.increment();
        }
        if (idx.get() < s.length() && s.charAt(idx.get()) == '(') {
            idx.increment();
            node.right = str2treeHelper(s, idx);
            idx.increment();
        }

        return node;
    }
}

class MyInteger {
    private int value;

    MyInteger(int value) {
        this.value = value;
    }

    int get() {
        return value;
    }

    void increment() {
        value++;
    }
}
```
The algorithm uses a recursive helper function (`str2treeHelper`) that constructs the binary tree nodes by traversing the input string `s`. The helper function updates the index (`idx`) at each recursive call and creates a TreeNode for each parenthesis pair encountered.

1. If `idx` is greater than or equal to the string length, return `null`.
2. Check the sign of the current number (if a negative sign is found) and update the `sign` and `idx`.
3. Extract the current number and update the `idx`.
4. Create a new TreeNode with the current number's value.
5. If the current character at `idx` is '(', move to the next character and call the `str2treeHelper` to construct the left child node. Increment `idx` after constructing the left subtree.
6. If the current character at `idx` is '(', move to the next character and call the `str2treeHelper` to construct the right child node. Increment `idx` after constructing the right subtree.
7. Return the newly created TreeNode.

The main function initializes the index variable `idx`, calls the helper function, and returns the root node of the constructed binary tree.

## A solution in C++

```cpp
#include <string>

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

class Solution {
public:
    TreeNode* str2tree(std::string s) {
        int idx = 0;
        return str2treeHelper(s, idx);
    }

    TreeNode* str2treeHelper(const std::string& s, int& idx) {
        if (idx >= s.length()) return NULL;

        int sign = 1;
        if (s[idx] == '-') {
            sign = -1;
            idx++;
        }

        int num = 0;
        while (idx < s.length() && isdigit(s[idx])) {
            num = num * 10 + (s[idx] - '0');
            idx++;
        }

        TreeNode* node = new TreeNode(sign * num);

        if (idx < s.length() && s[idx] == '(') {
            idx++;
            node->left = str2treeHelper(s, idx);
            idx++;
        }
        if (idx < s.length() && s[idx] == '(') {
            idx++;
            node->right = str2treeHelper(s, idx);
            idx++;
        }

        return node;
    }
};
```
The algorithm uses a recursive helper function (`str2treeHelper`) that constructs the binary tree nodes by traversing the input string `s`. The helper function updates the index (`idx`) at each recursive call and creates a TreeNode for each parenthesis pair encountered.

1. If `idx` is greater than or equal to the string length, return `null`.
2. Check the sign of the current number (if a negative sign is found) and update the `sign` and `idx`.
3. Extract the current number and update the `idx`.
4. Create a new TreeNode with the current number's value.
5. If the current character at `idx` is '(', move to the next character and call the `str2treeHelper` to construct the left child node. Increment `idx` after constructing the left subtree.
6. If the current character at `idx` is '(', move to the next character and call the `str2treeHelper` to construct the right child node. Increment `idx` after constructing the right subtree.
7. Return the newly created TreeNode.

The main function initializes the index variable `idx`, calls the helper function, and returns the root node of the constructed binary tree.

## A solution in Python

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

class Solution:
    def str2tree(self, s: str) -> TreeNode:
        def str2tree_helper(idx):
            if idx[0] >= len(s):
                return None

            sign = 1
            if s[idx[0]] == '-':
                sign = -1
                idx[0] += 1

            num = 0
            while idx[0] < len(s) and s[idx[0]].isdigit():
                num = num * 10 + int(s[idx[0]])
                idx[0] += 1

            node = TreeNode(sign * num)

            if idx[0] < len(s) and s[idx[0]] == '(':
                idx[0] += 1
                node.left = str2tree_helper(idx)
                idx[0] += 1
            if idx[0] < len(s) and s[idx[0]] == '(':
                idx[0] += 1
                node.right = str2tree_helper(idx)
                idx[0] += 1

            return node

        idx = [0]
        return str2tree_helper(idx)
```
The algorithm uses a recursive helper function (`str2treeHelper`) that constructs the binary tree nodes by traversing the input string `s`. The helper function updates the index (`idx`) at each recursive call and creates a TreeNode for each parenthesis pair encountered.

1. If `idx` is greater than or equal to the string length, return `null`.
2. Check the sign of the current number (if a negative sign is found) and update the `sign` and `idx`.
3. Extract the current number and update the `idx`.
4. Create a new TreeNode with the current number's value.
5. If the current character at `idx` is '(', move to the next character and call the `str2treeHelper` to construct the left child node. Increment `idx` after constructing the left subtree.
6. If the current character at `idx` is '(', move to the next character and call the `str2treeHelper` to construct the right child node. Increment `idx` after constructing the right subtree.
7. Return the newly created TreeNode.

The main function initializes the index variable `idx`, calls the helper function, and returns the root node of the constructed binary tree.

## A solution in Javascript

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

var str2tree = function(s) {
    const str2treeHelper = (s, idx) => {
        if (idx.value >= s.length) return null;

        let sign = 1;
        if (s[idx.value] === '-') {
            sign = -1;
            idx.value++;
        }

        let num = 0;
        while (idx.value < s.length && !isNaN(parseInt(s[idx.value], 10))) {
            num = num * 10 + parseInt(s[idx.value], 10);
            idx.value++;
        }

        const node = new TreeNode(sign * num);

        if (idx.value < s.length && s[idx.value] === '(') {
            idx.value++;
            node.left = str2treeHelper(s, idx);
            idx.value++;
        }
        if (idx.value < s.length && s[idx.value] === '(') {
            idx.value++;
            node.right = str2treeHelper(s, idx);
            idx.value++;
        }

        return node;
    };

    const idx = {value: 0};
    return str2treeHelper(s, idx);
};
```
The algorithm uses a recursive helper function (`str2treeHelper`) that constructs the binary tree nodes by traversing the input string `s`. The helper function updates the index (`idx`) at each recursive call and creates a TreeNode for each parenthesis pair encountered.

1. If `idx` is greater than or equal to the string length, return `null`.
2. Check the sign of the current number (if a negative sign is found) and update the `sign` and `idx`.
3. Extract the current number and update the `idx`.
4. Create a new TreeNode with the current number's value.
5. If the current character at `idx` is '(', move to the next character and call the `str2treeHelper` to construct the left child node. Increment `idx` after constructing the left subtree.
6. If the current character at `idx` is '(', move to the next character and call the `str2treeHelper` to construct the right child node. Increment `idx` after constructing the right subtree.
7. Return the newly created TreeNode.

The main function initializes the index variable `idx`, calls the helper function, and returns the root node of the constructed binary tree.


# Complex Number Multiplication

- slug: complex-number-multiplication
- difficulty: Medium

A [complex number](https://en.wikipedia.org/wiki/Complex_number) can be represented as a string on the form `"**real**+**imaginary**i "` where:

*   `real` is the real part and is an integer in the range `[-100, 100]`.
*   `imaginary` is the imaginary part and is an integer in the range `[-100, 100]`.
*   `i2 == -1`.

Given two complex numbers `num1` and `num2` as strings, return _a string of the complex number that represents their multiplications_.

**Example 1:**

**Input:** num1 =  "1+1i ", num2 =  "1+1i "
**Output:**  "0+2i "
**Explanation:** (1 + i) \* (1 + i) = 1 + i2 + 2 \* i = 2i, and you need convert it to the form of 0+2i.

**Example 2:**

**Input:** num1 =  "1+-1i ", num2 =  "1+-1i "
**Output:**  "0+-2i "
**Explanation:** (1 - i) \* (1 - i) = 1 + i2 - 2 \* i = -2i, and you need convert it to the form of 0+-2i.

**Constraints:**

*   `num1` and `num2` are valid complex numbers.

## A solution in Java

```java
public String complexNumberMultiply(String num1, String num2) {
    String[] tokens1 = num1.split("\\+|i");
    String[] tokens2 = num2.split("\\+|i");
    int real1 = Integer.parseInt(tokens1[0]);
    int imag1 = Integer.parseInt(tokens1[1]);
    int real2 = Integer.parseInt(tokens2[0]);
    int imag2 = Integer.parseInt(tokens2[1]);

    int real = real1 * real2 - imag1 * imag2;
    int imag = real1 * imag2 + real2 * imag1;

    return real + "+" + imag + "i";
}
```
The algorithm first extracts the real and imaginary parts of the input complex numbers. In C++, sscanf is used to read formatted data from a string. In Java, we use split with a regex that matches both "+" and "i". In Python and JavaScript, we use split and map for the conversions.

Once we have real and imaginary parts of both numbers, we multiply the complex numbers using the formula:
(real1 * real2 - imag1 * imag2) + (real1 * imag2 + real2 * imag1)i

Finally, we convert the result into a string in the required format and return it.

## A solution in C++

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

std::string complexNumberMultiply(std::string num1, std::string num2) {
    int real1, imag1, real2, imag2;
    sscanf(num1.c_str(), "%d+%di", &real1, &imag1);
    sscanf(num2.c_str(), "%d+%di", &real2, &imag2);

    int real = real1 * real2 - imag1 * imag2;
    int imag = real1 * imag2 + real2 * imag1;

    return std::to_string(real) + "+" + std::to_string(imag) + "i";
}
```
The algorithm first extracts the real and imaginary parts of the input complex numbers. In C++, sscanf is used to read formatted data from a string. In Java, we use split with a regex that matches both "+" and "i". In Python and JavaScript, we use split and map for the conversions.

Once we have real and imaginary parts of both numbers, we multiply the complex numbers using the formula:
(real1 * real2 - imag1 * imag2) + (real1 * imag2 + real2 * imag1)i

Finally, we convert the result into a string in the required format and return it.

## A solution in Python

```python
def complexNumberMultiply(num1: str, num2: str) -> str:
    real1, imag1 = map(int, num1[:-1].split('+'))
    real2, imag2 = map(int, num2[:-1].split('+'))

    real = real1 * real2 - imag1 * imag2
    imag = real1 * imag2 + real2 * imag1

    return f"{real}+{imag}i"
```
The algorithm first extracts the real and imaginary parts of the input complex numbers. In C++, sscanf is used to read formatted data from a string. In Java, we use split with a regex that matches both "+" and "i". In Python and JavaScript, we use split and map for the conversions.

Once we have real and imaginary parts of both numbers, we multiply the complex numbers using the formula:
(real1 * real2 - imag1 * imag2) + (real1 * imag2 + real2 * imag1)i

Finally, we convert the result into a string in the required format and return it.

## A solution in Javascript

```javascript
function complexNumberMultiply(num1, num2) {
    const [real1, imag1] = num1.slice(0, -1).split('+').map(Number);
    const [real2, imag2] = num2.slice(0, -1).split('+').map(Number);

    const real = real1 * real2 - imag1 * imag2;
    const imag = real1 * imag2 + real2 * imag1;

    return `${real}+${imag}i`;
}
```
The algorithm first extracts the real and imaginary parts of the input complex numbers. In C++, sscanf is used to read formatted data from a string. In Java, we use split with a regex that matches both "+" and "i". In Python and JavaScript, we use split and map for the conversions.

Once we have real and imaginary parts of both numbers, we multiply the complex numbers using the formula:
(real1 * real2 - imag1 * imag2) + (real1 * imag2 + real2 * imag1)i

Finally, we convert the result into a string in the required format and return it.


# Convert BST to Greater Tree

- slug: convert-bst-to-greater-tree
- difficulty: Medium

Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.

As a reminder, a _binary search tree_ is a tree that satisfies these constraints:

*   The left subtree of a node contains only nodes with keys **less than** the node's key.
*   The right subtree of a node contains only nodes with keys **greater than** the node's key.
*   Both the left and right subtrees must also be binary search trees.

**Example 1:**

**Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\]
**Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\]

**Example 2:**

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

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 104]`.
*   `-104 <= Node.val <= 104`
*   All the values in the tree are **unique**.
*   `root` is guaranteed to be a valid binary search tree.

**Note:** This question is the same as 1038: [https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/](https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/)

## A solution in Java

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

class Solution {
    int sum = 0;

    public TreeNode convertBST(TreeNode root) {
        if (root != null) {
            convertBST(root.right);
            sum += root.val;
            root.val = sum;
            convertBST(root.left);
        }

        return root;
    }
}
```
We traverse the tree in a right-to-left inorder traversal using a recursive algorithm. This traversal ensures we visit the nodes with the greater keys first. During this traversal, we maintain a running sum of the values of the nodes we've visited so far. When we visit a new node, we add the running sum to it and update the running sum with the new node's value. This effectively converts the tree into a Greater Tree, as the nodes' values are replaced with the sum of all the values greater than their initial values. This solution has a time complexity of O(n), where n is the number of nodes in the tree.

## A solution in C++

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

class Solution {
public:
    int sum = 0;

    TreeNode* convertBST(TreeNode* root) {
        if (root) {
            convertBST(root->right);
            sum += root->val;
            root->val = sum;
            convertBST(root->left);
        }

        return root;
    }
};
```
We traverse the tree in a right-to-left inorder traversal using a recursive algorithm. This traversal ensures we visit the nodes with the greater keys first. During this traversal, we maintain a running sum of the values of the nodes we've visited so far. When we visit a new node, we add the running sum to it and update the running sum with the new node's value. This effectively converts the tree into a Greater Tree, as the nodes' values are replaced with the sum of all the values greater than their initial values. This solution has a time complexity of O(n), where n is the number of nodes in the tree.

## A solution in Python

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

class Solution:
    def __init__(self):
        self.sum = 0

    def convertBST(self, root: TreeNode) -> TreeNode:
        if root:
            self.convertBST(root.right)
            self.sum += root.val
            root.val = self.sum
            self.convertBST(root.left)

        return root
```
We traverse the tree in a right-to-left inorder traversal using a recursive algorithm. This traversal ensures we visit the nodes with the greater keys first. During this traversal, we maintain a running sum of the values of the nodes we've visited so far. When we visit a new node, we add the running sum to it and update the running sum with the new node's value. This effectively converts the tree into a Greater Tree, as the nodes' values are replaced with the sum of all the values greater than their initial values. This solution has a time complexity of O(n), where n is the number of nodes in the tree.

## A solution in Javascript

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

class Solution {
    constructor() {
        this.sum = 0;
    }

    convertBST(root) {
        if (root) {
            this.convertBST(root.right);
            this.sum += root.val;
            root.val = this.sum;
            this.convertBST(root.left);
        }

        return root;
    }
}
```
We traverse the tree in a right-to-left inorder traversal using a recursive algorithm. This traversal ensures we visit the nodes with the greater keys first. During this traversal, we maintain a running sum of the values of the nodes we've visited so far. When we visit a new node, we add the running sum to it and update the running sum with the new node's value. This effectively converts the tree into a Greater Tree, as the nodes' values are replaced with the sum of all the values greater than their initial values. This solution has a time complexity of O(n), where n is the number of nodes in the tree.


# Minimum Time Difference

- slug: minimum-time-difference
- difficulty: Medium

Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.

**Example 1:**

**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1

**Example 2:**

**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0

**Constraints:**

*   `2 <= timePoints.length <= 2 * 104`
*   `timePoints[i]` is in the format **"HH:MM "**.

## A solution in Java

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

public int findMinDifference(List<String> timePoints) {
    Collections.sort(timePoints);
    int minDifference = Integer.MAX_VALUE;

    for (int i = 0; i < timePoints.size(); ++i) {
        int curDifference = Math.abs((Integer.parseInt(timePoints.get(i).substring(0, 2)) * 60 + Integer.parseInt(timePoints.get(i).substring(3, 5))) - (Integer.parseInt(timePoints.get((i + 1) % timePoints.size()).substring(0, 2)) * 60 + Integer.parseInt(timePoints.get((i + 1) % timePoints.size()).substring(3, 5))));
        minDifference = Math.min(minDifference, curDifference > 720 ? 1440 - curDifference : curDifference);
    }

    return minDifference;
}
```
1. Sort the given timePoints list.
2. Initialize variable minDifference with the maximum value possible to keep track of the minimum difference.
3. Loop through the timePoints list and for each pair of consecutive times (including the last time and the first time in the list):
    - Calculate the absolute difference between the time in minutes.
    - If the difference is greater than 720 (half of 1440 minutes in a day), take the complementary difference (i.e., 1440 - curDifference).
    - Update the minDifference variable with the minimum of the previous minDifference and the calculated difference.
4. After the loop, the minDifference variable will hold the minimum minutes difference between any two time-points in the list. Return it.

## A solution in C++

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

int findMinDifference(std::vector<std::string>& timePoints) {
    std::sort(timePoints.begin(), timePoints.end());
    int minDifference = INT_MAX;

    for (int i = 0; i < timePoints.size(); ++i) {
        int curDifference = abs((stoi(timePoints[i].substr(0, 2)) * 60 + stoi(timePoints[i].substr(3, 2))) - (stoi(timePoints[(i + 1) % timePoints.size()].substr(0, 2)) * 60 + stoi(timePoints[(i + 1) % timePoints.size()].substr(3, 2))));
        minDifference = std::min(minDifference, curDifference > 720 ? 1440 - curDifference : curDifference);
    }

    return minDifference;
}
```
1. Sort the given timePoints list.
2. Initialize variable minDifference with the maximum value possible to keep track of the minimum difference.
3. Loop through the timePoints list and for each pair of consecutive times (including the last time and the first time in the list):
    - Calculate the absolute difference between the time in minutes.
    - If the difference is greater than 720 (half of 1440 minutes in a day), take the complementary difference (i.e., 1440 - curDifference).
    - Update the minDifference variable with the minimum of the previous minDifference and the calculated difference.
4. After the loop, the minDifference variable will hold the minimum minutes difference between any two time-points in the list. Return it.

## A solution in Python

```python
def findMinDifference(timePoints):
    timePoints.sort()
    min_difference = float('inf')

    for i in range(len(timePoints)):
        h1, m1 = map(int, timePoints[i].split(':'))
        h2, m2 = map(int, timePoints[(i+1)%len(timePoints)].split(':'))
        cur_difference = abs((h1 * 60 + m1) - (h2 * 60 + m2))
        min_difference = min(min_difference, 1440 - cur_difference if cur_difference > 720 else cur_difference)

    return min_difference
```
1. Sort the given timePoints list.
2. Initialize variable minDifference with the maximum value possible to keep track of the minimum difference.
3. Loop through the timePoints list and for each pair of consecutive times (including the last time and the first time in the list):
    - Calculate the absolute difference between the time in minutes.
    - If the difference is greater than 720 (half of 1440 minutes in a day), take the complementary difference (i.e., 1440 - curDifference).
    - Update the minDifference variable with the minimum of the previous minDifference and the calculated difference.
4. After the loop, the minDifference variable will hold the minimum minutes difference between any two time-points in the list. Return it.

## A solution in Javascript

```javascript
function findMinDifference(timePoints) {
    timePoints.sort();
    let minDifference = Infinity;

    for (let i = 0; i < timePoints.length; ++i) {
        const [h1, m1] = timePoints[i].split(':').map(Number);
        const [h2, m2] = timePoints[(i + 1) % timePoints.length].split(':').map(Number);
        const curDifference = Math.abs((h1 * 60 + m1) - (h2 * 60 + m2));
        minDifference = Math.min(minDifference, curDifference > 720 ? 1440 - curDifference : curDifference);
    }

    return minDifference;
}
```
1. Sort the given timePoints list.
2. Initialize variable minDifference with the maximum value possible to keep track of the minimum difference.
3. Loop through the timePoints list and for each pair of consecutive times (including the last time and the first time in the list):
    - Calculate the absolute difference between the time in minutes.
    - If the difference is greater than 720 (half of 1440 minutes in a day), take the complementary difference (i.e., 1440 - curDifference).
    - Update the minDifference variable with the minimum of the previous minDifference and the calculated difference.
4. After the loop, the minDifference variable will hold the minimum minutes difference between any two time-points in the list. Return it.