# Longest Substring with At Most Two Distinct Characters

- slug: longest-substring-with-at-most-two-distinct-characters
- difficulty: Medium

Given a string `s`, return _the length of the longest_ _substring_ _that contains at most **two distinct characters**_.

**Example 1:**

**Input:** s =  "eceba "
**Output:** 3
**Explanation:** The substring is  "ece " which its length is 3.

**Example 2:**

**Input:** s =  "ccaabbb "
**Output:** 5
**Explanation:** The substring is  "aabbb " which its length is 5.

**Constraints:**

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

## A solution in Java

```java
public int lengthOfLongestSubstringTwoDistinct(String s) {
    int l = 0, r = 0, max_len = 0, cur_len = 0;
    HashMap<Character, Integer> char_count = new HashMap<>();

    while (r < s.length()) {
        char_count.put(s.charAt(r), char_count.getOrDefault(s.charAt(r), 0) + 1);
        if (char_count.size() <= 2) {
            cur_len++;
        } else {
            while (char_count.size() > 2 && l <= r) {
                char_count.put(s.charAt(l), char_count.get(s.charAt(l)) - 1);
                if (char_count.get(s.charAt(l)) == 0) {
                    char_count.remove(s.charAt(l));
                }
                l++;
                cur_len--;
            }
            cur_len++;
        }
        max_len = Math.max(max_len, cur_len);
        r++;
    }
    return max_len;
}
```
The algorithm implements a sliding window approach. We maintain two pointers `l` and `r` representing the left and right ends of the current substring. We also maintain a hash map `char_count` to store the counts of distinct characters in the current substring.

We iterate through the string with pointer `r`. For each character, we increment its count in the hash map. If we have two or fewer distinct characters in the current substring, we update the current length `cur_len`. If we have more than two distinct characters, we move the pointer `l` to the right, decrementing the count of the character at `l` in the hash map, and removing it if its count becomes zero. We update `cur_len` accordingly in the process.

At each step, we update the maximum length `max_len` with the maximum of `max_len` and `cur_len`. We return `max_len` at the end.

## A solution in C++

```cpp
int lengthOfLongestSubstringTwoDistinct(string s) {
    int l = 0, r = 0, max_len = 0, cur_len = 0;
    unordered_map<char, int> char_count;

    while (r < s.length()) {
        char_count[s[r]]++;
        if (char_count.size() <= 2) {
            cur_len++;
        } else {
            while (char_count.size() > 2 && l <= r) {
                char_count[s[l]]--;
                if (char_count[s[l]] == 0) {
                    char_count.erase(s[l]);
                }
                l++;
                cur_len--;
            }
            cur_len++;
        }
        max_len = max(max_len, cur_len);
        r++;
    }
    return max_len;
}
```
The algorithm implements a sliding window approach. We maintain two pointers `l` and `r` representing the left and right ends of the current substring. We also maintain a hash map `char_count` to store the counts of distinct characters in the current substring.

We iterate through the string with pointer `r`. For each character, we increment its count in the hash map. If we have two or fewer distinct characters in the current substring, we update the current length `cur_len`. If we have more than two distinct characters, we move the pointer `l` to the right, decrementing the count of the character at `l` in the hash map, and removing it if its count becomes zero. We update `cur_len` accordingly in the process.

At each step, we update the maximum length `max_len` with the maximum of `max_len` and `cur_len`. We return `max_len` at the end.

## A solution in Python

```python
def lengthOfLongestSubstringTwoDistinct(s: str) -> int:
    l, r, max_len, cur_len = 0, 0, 0, 0
    char_count = {}

    while r < len(s):
        if s[r] in char_count:
            char_count[s[r]] += 1
        else:
            char_count[s[r]] = 1
        if len(char_count) <= 2:
            cur_len += 1
        else:
            while len(char_count) > 2 and l <= r:
                char_count[s[l]] -= 1
                if char_count[s[l]] == 0:
                    del char_count[s[l]]
                l += 1
                cur_len -= 1
            cur_len += 1
        max_len = max(max_len, cur_len)
        r += 1
    return max_len
```
The algorithm implements a sliding window approach. We maintain two pointers `l` and `r` representing the left and right ends of the current substring. We also maintain a hash map `char_count` to store the counts of distinct characters in the current substring.

We iterate through the string with pointer `r`. For each character, we increment its count in the hash map. If we have two or fewer distinct characters in the current substring, we update the current length `cur_len`. If we have more than two distinct characters, we move the pointer `l` to the right, decrementing the count of the character at `l` in the hash map, and removing it if its count becomes zero. We update `cur_len` accordingly in the process.

At each step, we update the maximum length `max_len` with the maximum of `max_len` and `cur_len`. We return `max_len` at the end.

## A solution in Javascript

```javascript
function lengthOfLongestSubstringTwoDistinct(s) {
    let l = 0, r = 0, max_len = 0, cur_len = 0;
    const char_count = new Map();

    while (r < s.length) {
        char_count.set(s[r], (char_count.get(s[r]) || 0) + 1);
        if (char_count.size <= 2) {
            cur_len++;
        } else {
            while (char_count.size > 2 && l <= r) {
                char_count.set(s[l], char_count.get(s[l]) - 1);
                if (char_count.get(s[l]) === 0) {
                    char_count.delete(s[l]);
                }
                l++;
                cur_len--;
            }
            cur_len++;
        }
        max_len = Math.max(max_len, cur_len);
        r++;
    }
    return max_len;
}
```
The algorithm implements a sliding window approach. We maintain two pointers `l` and `r` representing the left and right ends of the current substring. We also maintain a hash map `char_count` to store the counts of distinct characters in the current substring.

We iterate through the string with pointer `r`. For each character, we increment its count in the hash map. If we have two or fewer distinct characters in the current substring, we update the current length `cur_len`. If we have more than two distinct characters, we move the pointer `l` to the right, decrementing the count of the character at `l` in the hash map, and removing it if its count becomes zero. We update `cur_len` accordingly in the process.

At each step, we update the maximum length `max_len` with the maximum of `max_len` and `cur_len`. We return `max_len` at the end.


# Intersection of Two Linked Lists

- slug: intersection-of-two-linked-lists
- difficulty: Easy

Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`.

For example, the following two linked lists begin to intersect at node `c1`:

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

**Note** that the linked lists must **retain their original structure** after the function returns.

**Custom Judge:**

The inputs to the **judge** are given as follows (your program is **not** given these inputs):

*   `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node.
*   `listA` - The first linked list.
*   `listB` - The second linked list.
*   `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node.
*   `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node.

The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**.

**Example 1:**

**Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3
**Output:** Intersected at '8'
**Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.

**Example 2:**

**Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1
**Output:** Intersected at '2'
**Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.

**Example 3:**

**Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2
**Output:** No intersection
**Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.

**Constraints:**

*   The number of nodes of `listA` is in the `m`.
*   The number of nodes of `listB` is in the `n`.
*   `1 <= m, n <= 3 * 104`
*   `1 <= Node.val <= 105`
*   `0 <= skipA < m`
*   `0 <= skipB < n`
*   `intersectVal` is `0` if `listA` and `listB` do not intersect.
*   `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect.

**Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?

## A solution in Java

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

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    ListNode pA = headA, pB = headB;
    while (pA != pB) {
        pA = pA != null ? pA.next : headB;
        pB = pB != null ? pB.next : headA;
    }
    return pA;
}
```
The algorithm uses two pointers, one for each linked list head (headA and headB). The pointers traverse through the lists such that they traverse the sum of the node count of both lists. If the lists intersect at a node, the pointers will eventually meet at this intersection node because they will have traversed the same number of total nodes. If the lists do not intersect, the pointers will meet at the end of the lists, resulting in both pointers being null, and the function will return null.

## A solution in C++

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

ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    ListNode *pA = headA, *pB = headB;
    while (pA != pB) {
        pA = pA ? pA->next : headB;
        pB = pB ? pB->next : headA;
    }
    return pA;
}
```
The algorithm uses two pointers, one for each linked list head (headA and headB). The pointers traverse through the lists such that they traverse the sum of the node count of both lists. If the lists intersect at a node, the pointers will eventually meet at this intersection node because they will have traversed the same number of total nodes. If the lists do not intersect, the pointers will meet at the end of the lists, resulting in both pointers being null, and the function will return null.

## A solution in Python

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

def getIntersectionNode(headA, headB):
    pA, pB = headA, headB
    while pA is not pB:
        pA = pA.next if pA else headB
        pB = pB.next if pB else headA
    return pA
```
The algorithm uses two pointers, one for each linked list head (headA and headB). The pointers traverse through the lists such that they traverse the sum of the node count of both lists. If the lists intersect at a node, the pointers will eventually meet at this intersection node because they will have traversed the same number of total nodes. If the lists do not intersect, the pointers will meet at the end of the lists, resulting in both pointers being null, and the function will return null.

## A solution in Javascript

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

function getIntersectionNode(headA, headB) {
    let pA = headA, pB = headB;
    while (pA !== pB) {
        pA = pA !== null ? pA.next : headB;
        pB = pB !== null ? pB.next : headA;
    }
    return pA;
}
```
The algorithm uses two pointers, one for each linked list head (headA and headB). The pointers traverse through the lists such that they traverse the sum of the node count of both lists. If the lists intersect at a node, the pointers will eventually meet at this intersection node because they will have traversed the same number of total nodes. If the lists do not intersect, the pointers will meet at the end of the lists, resulting in both pointers being null, and the function will return null.


# One Edit Distance

- slug: one-edit-distance
- difficulty: Medium

Given two strings `s` and `t`, return `true` if they are both one edit distance apart, otherwise return `false`.

A string `s` is said to be one distance apart from a string `t` if you can:

*   Insert **exactly one** character into `s` to get `t`.
*   Delete **exactly one** character from `s` to get `t`.
*   Replace **exactly one** character of `s` with **a different character** to get `t`.

**Example 1:**

**Input:** s =  "ab ", t =  "acb "
**Output:** true
**Explanation:** We can insert 'c' into s to get t.

**Example 2:**

**Input:** s =  " ", t =  " "
**Output:** false
**Explanation:** We cannot get t from s by only one step.

**Constraints:**

*   `0 <= s.length, t.length <= 104`
*   `s` and `t` consist of lowercase letters, uppercase letters, and digits.

## A solution in Java

```java
public boolean isOneEditDistance(String s, String t) {
    int m = s.length();
    int n = t.length();
    if (m > n) {
        return isOneEditDistance(t, s);
    }
    if (n - m > 1) {
        return false;
    }
    for (int i = 0; i < m; ++i) {
        if (s.charAt(i) != t.charAt(i)) {
            if (m < n) {
                return s.substring(i).equals(t.substring(i + 1));
            } else {
                return s.substring(i + 1).equals(t.substring(i + 1));
            }
        }
    }
    return m + 1 == n;
}
```
The algorithm first checks if the length of string `s` is greater than the length of string `t`. If true, it swaps the two strings and continues the checks. Next, the algorithm checks if the length difference between the strings is greater than 1, returning `false` if so since it's not possible to meet the one edit distance criteria in that case.

The algorithm iterates through the characters of the two strings. If it encounters a mismatched character it checks if the insertion or deletion of a character can yield the other string, and if not, it checks if the replacement of the mismatched character in string `s` can yield string `t`. If it iterates through both strings without finding a mismatch, it returns `true` if the length difference of the strings is 1 to ensure only one character has been inserted. Otherwise, it returns `false`.

## A solution in C++

```cpp
bool isOneEditDistance(string s, string t) {
    int m = s.length(), n = t.length();
    if (m > n) {
        return isOneEditDistance(t, s);
    }
    if (n - m > 1) {
        return false;
    }
    bool flag = false;
    for (int i = 0; i < m; ++i) {
      if (s[i] != t[i]) {
          if (m < n) {
              return s.substr(i) == t.substr(i + 1);
          } else {
              return s.substr(i + 1) == t.substr(i + 1);
          }
      }
    }
    return m + 1 == n;
}
```
The algorithm first checks if the length of string `s` is greater than the length of string `t`. If true, it swaps the two strings and continues the checks. Next, the algorithm checks if the length difference between the strings is greater than 1, returning `false` if so since it's not possible to meet the one edit distance criteria in that case.

The algorithm iterates through the characters of the two strings. If it encounters a mismatched character it checks if the insertion or deletion of a character can yield the other string, and if not, it checks if the replacement of the mismatched character in string `s` can yield string `t`. If it iterates through both strings without finding a mismatch, it returns `true` if the length difference of the strings is 1 to ensure only one character has been inserted. Otherwise, it returns `false`.

## A solution in Python

```python
def isOneEditDistance(s: str, t: str) -> bool:
    m, n = len(s), len(t)
    if m > n:
        return isOneEditDistance(t, s)
    if n - m > 1:
        return False
    for i in range(m):
        if s[i] != t[i]:
            return s[i + (m < n):] == t[i + 1:]
    return m + 1 == n
```
The algorithm first checks if the length of string `s` is greater than the length of string `t`. If true, it swaps the two strings and continues the checks. Next, the algorithm checks if the length difference between the strings is greater than 1, returning `false` if so since it's not possible to meet the one edit distance criteria in that case.

The algorithm iterates through the characters of the two strings. If it encounters a mismatched character it checks if the insertion or deletion of a character can yield the other string, and if not, it checks if the replacement of the mismatched character in string `s` can yield string `t`. If it iterates through both strings without finding a mismatch, it returns `true` if the length difference of the strings is 1 to ensure only one character has been inserted. Otherwise, it returns `false`.

## A solution in Javascript

```javascript
function isOneEditDistance(s, t) {
    let m = s.length, n = t.length;
    if (m > n) {
        return isOneEditDistance(t, s);
    }
    if (n - m > 1) {
        return false;
    }
    for (let i = 0; i < m; ++i) {
        if (s[i] !== t[i]) {
            if (m < n) {
                return s.slice(i) === t.slice(i + 1);
            } else {
                return s.slice(i + 1) === t.slice(i + 1);
            }
        }
    }
    return m + 1 === n;
}
```
The algorithm first checks if the length of string `s` is greater than the length of string `t`. If true, it swaps the two strings and continues the checks. Next, the algorithm checks if the length difference between the strings is greater than 1, returning `false` if so since it's not possible to meet the one edit distance criteria in that case.

The algorithm iterates through the characters of the two strings. If it encounters a mismatched character it checks if the insertion or deletion of a character can yield the other string, and if not, it checks if the replacement of the mismatched character in string `s` can yield string `t`. If it iterates through both strings without finding a mismatch, it returns `true` if the length difference of the strings is 1 to ensure only one character has been inserted. Otherwise, it returns `false`.


# Find Peak Element

- slug: find-peak-element
- difficulty: Medium

A peak element is an element that is strictly greater than its neighbors.

Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**.

You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.

You must write an algorithm that runs in `O(log n)` time.

**Example 1:**

**Input:** nums = \[1,2,3,1\]
**Output:** 2
**Explanation:** 3 is a peak element and your function should return the index number 2.

**Example 2:**

**Input:** nums = \[1,2,1,3,5,6,4\]
**Output:** 5
**Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `-231 <= nums[i] <= 231 - 1`
*   `nums[i] != nums[i + 1]` for all valid `i`.

## A solution in Java

```java
public int findPeakElement(int[] nums) {
    int left = 0, right = nums.length - 1;
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] < nums[mid + 1]) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}
```
For this problem, we can use the binary search. Instead of comparing the mid-element to the target value, we compare it with its neighbors. Based on the comparison, we adjust the left and right pointers accordingly:

1. Initialize left and right pointer, `left = 0` and `right = nums.length - 1`.
2. While `left < right`, do the following:
   a. Calculate the mid index, `mid = left + (right - left) // 2`.
   b. If `nums[mid] < nums[mid + 1]`, move the left pointer to `mid + 1`.
   c. Else, move the right pointer to the `mid`.
3. When `left >= right`, the peak index is found, so return `left`.

Since we use a binary search, the algorithm runs in O(log n) time.

## A solution in C++

```cpp
int findPeakElement(vector<int>& nums) {
    int left = 0, right = nums.size() - 1;
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] < nums[mid + 1]) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}
```
For this problem, we can use the binary search. Instead of comparing the mid-element to the target value, we compare it with its neighbors. Based on the comparison, we adjust the left and right pointers accordingly:

1. Initialize left and right pointer, `left = 0` and `right = nums.length - 1`.
2. While `left < right`, do the following:
   a. Calculate the mid index, `mid = left + (right - left) // 2`.
   b. If `nums[mid] < nums[mid + 1]`, move the left pointer to `mid + 1`.
   c. Else, move the right pointer to the `mid`.
3. When `left >= right`, the peak index is found, so return `left`.

Since we use a binary search, the algorithm runs in O(log n) time.

## A solution in Python

```python
def findPeakElement(nums):
    left, right = 0, len(nums) - 1
    while left < right:
        mid = left + (right - left) // 2
        if nums[mid] < nums[mid + 1]:
            left = mid + 1
        else:
            right = mid
    return left
```
For this problem, we can use the binary search. Instead of comparing the mid-element to the target value, we compare it with its neighbors. Based on the comparison, we adjust the left and right pointers accordingly:

1. Initialize left and right pointer, `left = 0` and `right = nums.length - 1`.
2. While `left < right`, do the following:
   a. Calculate the mid index, `mid = left + (right - left) // 2`.
   b. If `nums[mid] < nums[mid + 1]`, move the left pointer to `mid + 1`.
   c. Else, move the right pointer to the `mid`.
3. When `left >= right`, the peak index is found, so return `left`.

Since we use a binary search, the algorithm runs in O(log n) time.

## A solution in Javascript

```javascript
function findPeakElement(nums) {
    let left = 0, right = nums.length - 1;
    while (left < right) {
        let mid = left + Math.floor((right - left) / 2);
        if (nums[mid] < nums[mid + 1]) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}
```
For this problem, we can use the binary search. Instead of comparing the mid-element to the target value, we compare it with its neighbors. Based on the comparison, we adjust the left and right pointers accordingly:

1. Initialize left and right pointer, `left = 0` and `right = nums.length - 1`.
2. While `left < right`, do the following:
   a. Calculate the mid index, `mid = left + (right - left) // 2`.
   b. If `nums[mid] < nums[mid + 1]`, move the left pointer to `mid + 1`.
   c. Else, move the right pointer to the `mid`.
3. When `left >= right`, the peak index is found, so return `left`.

Since we use a binary search, the algorithm runs in O(log n) time.


# Missing Ranges

- slug: missing-ranges
- difficulty: Easy

You are given an inclusive range `[lower, upper]` and a **sorted unique** integer array `nums`, where all elements are in the inclusive range.

A number `x` is considered **missing** if `x` is in the range `[lower, upper]` and `x` is not in `nums`.

Return _the **smallest sorted** list of ranges that **cover every missing number exactly**_. That is, no element of `nums` is in any of the ranges, and each missing number is in one of the ranges.

Each range `[a,b]` in the list should be output as:

*   `"a->b "` if `a != b`
*   `"a "` if `a == b`

**Example 1:**

**Input:** nums = \[0,1,3,50,75\], lower = 0, upper = 99
**Output:** \[ "2 ", "4->49 ", "51->74 ", "76->99 "\]
**Explanation:** The ranges are:
\[2,2\] -->  "2 "
\[4,49\] -->  "4->49 "
\[51,74\] -->  "51->74 "
\[76,99\] -->  "76->99 "

**Example 2:**

**Input:** nums = \[-1\], lower = -1, upper = -1
**Output:** \[\]
**Explanation:** There are no missing ranges since there are no missing numbers.

**Constraints:**

*   `-109 <= lower <= upper <= 109`
*   `0 <= nums.length <= 100`
*   `lower <= nums[i] <= upper`
*   All the values of `nums` are **unique**.

## A solution in Java

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

public List<String> findMissingRanges(int[] nums, int lower, int upper) {
    List<String> result = new ArrayList<>();
    long prev = (long) lower - 1;

    for (int i = 0; i <= nums.length; ++i) {
        long cur = (i == nums.length) ? (long) upper + 1 : nums[i];
        if (cur - prev >= 2) {
            result.add(Long.toString(prev + 1) + (cur - prev == 2 ? "" : "->") + Long.toString(cur - 1));
        }
        prev = cur;
    }

    return result;
}
```
The algorithm iterates over the nums array and keeps track of the previous number (initialized to lower - 1) keeping in mind that nums is a sorted unique array of elements in the range [lower, upper]. For each number, it checks the difference between the current number and the previous number. If the difference is greater or equal to 2, it adds a range to the result vector. Also, it checks whether the range length is equal to 2, in which case it will only print the starting value of the range, without the "->". At the end of the loop, it returns the list of ranges covering the missing numbers in the input range.

## A solution in C++

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

std::vector<std::string> findMissingRanges(std::vector<int>& nums, int lower, int upper) {
    std::vector<std::string> result;
    long prev = (long)lower - 1;

    for (int i = 0; i <= nums.size(); ++i) {
        long cur = (i == nums.size()) ? (long)upper + 1 : nums[i];
        if (cur - prev >= 2) {
            result.push_back(std::to_string(prev + 1) + (cur - prev == 2 ? "" : "->") + std::to_string(cur - 1));
        }
        prev = cur;
    }

    return result;
}
```
The algorithm iterates over the nums array and keeps track of the previous number (initialized to lower - 1) keeping in mind that nums is a sorted unique array of elements in the range [lower, upper]. For each number, it checks the difference between the current number and the previous number. If the difference is greater or equal to 2, it adds a range to the result vector. Also, it checks whether the range length is equal to 2, in which case it will only print the starting value of the range, without the "->". At the end of the loop, it returns the list of ranges covering the missing numbers in the input range.

## A solution in Python

```python
from typing import List

def find_missing_ranges(nums: List[int], lower: int, upper: int) -> List[str]:
    result = []
    prev = lower - 1

    for i, num in enumerate(nums + [upper + 1]):
        if num - prev >= 2:
            result.append(f"{prev + 1}" + ("" if num - prev == 2 else "->") + f"{num - 1}")
        prev = num

    return result
```
The algorithm iterates over the nums array and keeps track of the previous number (initialized to lower - 1) keeping in mind that nums is a sorted unique array of elements in the range [lower, upper]. For each number, it checks the difference between the current number and the previous number. If the difference is greater or equal to 2, it adds a range to the result vector. Also, it checks whether the range length is equal to 2, in which case it will only print the starting value of the range, without the "->". At the end of the loop, it returns the list of ranges covering the missing numbers in the input range.

## A solution in Javascript

```javascript
function findMissingRanges(nums, lower, upper) {
    let result = [];
    let prev = lower - 1;

    for (let i = 0; i <= nums.length; ++i) {
        let cur = (i === nums.length) ? upper + 1 : nums[i];
        if (cur - prev >= 2) {
            result.push((prev + 1) + (cur - prev === 2 ? "" : "->") + (cur - 1));
        }
        prev = cur;
    }

    return result;
}
```
The algorithm iterates over the nums array and keeps track of the previous number (initialized to lower - 1) keeping in mind that nums is a sorted unique array of elements in the range [lower, upper]. For each number, it checks the difference between the current number and the previous number. If the difference is greater or equal to 2, it adds a range to the result vector. Also, it checks whether the range length is equal to 2, in which case it will only print the starting value of the range, without the "->". At the end of the loop, it returns the list of ranges covering the missing numbers in the input range.


# Maximum Gap

- slug: maximum-gap
- difficulty: Hard

Given an integer array `nums`, return _the maximum difference between two successive elements in its sorted form_. If the array contains less than two elements, return `0`.

You must write an algorithm that runs in linear time and uses linear extra space.

**Example 1:**

**Input:** nums = \[3,6,9,1\]
**Output:** 3
**Explanation:** The sorted form of the array is \[1,3,6,9\], either (3,6) or (6,9) has the maximum difference 3.

**Example 2:**

**Input:** nums = \[10\]
**Output:** 0
**Explanation:** The array contains less than 2 elements, therefore return 0.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `0 <= nums[i] <= 109`

## A solution in Java

```java
public int maximumGap(int[] nums) {
    if (nums.length < 2) return 0;

    int min_val = Arrays.stream(nums).min().getAsInt();
    int max_val = Arrays.stream(nums).max().getAsInt();
    int len = nums.length;
    int bucket_size = Math.max(1, (max_val - min_val) / (len - 1));
    int bucket_num = (max_val - min_val) / bucket_size + 1;
    int[][] buckets = new int[bucket_num][2];
    for (int i = 0; i < bucket_num; i++) {
        buckets[i] = new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE};
    }

    for (int num : nums) {
        int idx = (num - min_val) / bucket_size;
        buckets[idx][0] = Math.min(buckets[idx][0], num);
        buckets[idx][1] = Math.max(buckets[idx][1], num);
    }

    int max_gap = 0, prev_max = min_val;
    for (int[] bucket : buckets) {
        if (bucket[0] == Integer.MAX_VALUE) continue;
        max_gap = Math.max(max_gap, bucket[0] - prev_max);
        prev_max = bucket[1];
    }
    return max_gap;
}
```
The algorithm first finds the minimum and maximum values of the input array `nums`. Then it calculates the ideal bucket size by dividing the difference between the maximum and minimum values by the length of the array minus one. The algorithm then initializes an array of buckets, where each bucket contains the minimum and maximum values of its elements.

Next, the algorithm updates the minimum and maximum values for each bucket appropriately by iterating through the input array. Finally, the algorithm calculates the maximum gap by finding the difference between the minimum value of the current bucket and the maximum value of the previous non-empty bucket, and updating the maximum gap value accordingly.

This algorithm runs in linear time, because it iterates through the input array once to fill the buckets, and then it iterates through the buckets once to compute the maximum gap. It also uses linear extra space, as the number of buckets is proportional to the length of the input array.

## A solution in C++

```cpp
int maximumGap(vector<int>& nums) {
    if (nums.size() < 2) return 0;

    int min_val = *min_element(nums.begin(), nums.end());
    int max_val = *max_element(nums.begin(), nums.end());
    int len = nums.size();
    int bucket_size = max(1, (max_val - min_val) / (len - 1));
    int bucket_num = (max_val - min_val) / bucket_size + 1;
    vector<pair<int, int>> buckets(bucket_num, {INT_MAX, INT_MIN});

    for (int num : nums) {
        int idx = (num - min_val) / bucket_size;
        buckets[idx].first = min(buckets[idx].first, num);
        buckets[idx].second = max(buckets[idx].second, num);
    }

    int max_gap = 0, prev_max = min_val;
    for (auto& bucket : buckets) {
        if (bucket.first == INT_MAX) continue;
        max_gap = max(max_gap, bucket.first - prev_max);
        prev_max = bucket.second;
    }
    return max_gap;
}
```
The algorithm first finds the minimum and maximum values of the input array `nums`. Then it calculates the ideal bucket size by dividing the difference between the maximum and minimum values by the length of the array minus one. The algorithm then initializes an array of buckets, where each bucket contains the minimum and maximum values of its elements.

Next, the algorithm updates the minimum and maximum values for each bucket appropriately by iterating through the input array. Finally, the algorithm calculates the maximum gap by finding the difference between the minimum value of the current bucket and the maximum value of the previous non-empty bucket, and updating the maximum gap value accordingly.

This algorithm runs in linear time, because it iterates through the input array once to fill the buckets, and then it iterates through the buckets once to compute the maximum gap. It also uses linear extra space, as the number of buckets is proportional to the length of the input array.

## A solution in Python

```python
def maximumGap(nums):
    if len(nums) < 2:
        return 0

    min_val = min(nums)
    max_val = max(nums)
    length = len(nums)
    bucket_size = max(1, (max_val - min_val) // (length - 1))
    bucket_num = (max_val - min_val) // bucket_size + 1
    buckets = [[float("inf"), float("-inf")] for _ in range(bucket_num)]

    for num in nums:
        idx = (num - min_val) // bucket_size
        buckets[idx][0] = min(buckets[idx][0], num)
        buckets[idx][1] = max(buckets[idx][1], num)

    max_gap = 0
    prev_max = min_val
    for bucket in buckets:
        if bucket[0] == float("inf"):
            continue
        max_gap = max(max_gap, bucket[0] - prev_max)
        prev_max = bucket[1]
    return max_gap
```
The algorithm first finds the minimum and maximum values of the input array `nums`. Then it calculates the ideal bucket size by dividing the difference between the maximum and minimum values by the length of the array minus one. The algorithm then initializes an array of buckets, where each bucket contains the minimum and maximum values of its elements.

Next, the algorithm updates the minimum and maximum values for each bucket appropriately by iterating through the input array. Finally, the algorithm calculates the maximum gap by finding the difference between the minimum value of the current bucket and the maximum value of the previous non-empty bucket, and updating the maximum gap value accordingly.

This algorithm runs in linear time, because it iterates through the input array once to fill the buckets, and then it iterates through the buckets once to compute the maximum gap. It also uses linear extra space, as the number of buckets is proportional to the length of the input array.

## A solution in Javascript

```javascript
function maximumGap(nums) {
    if (nums.length < 2) return 0;

    let min_val = Math.min(...nums);
    let max_val = Math.max(...nums);
    let len = nums.length;
    let bucket_size = Math.max(1, Math.floor((max_val - min_val) / (len - 1)));
    let bucket_num = Math.floor((max_val - min_val) / bucket_size) + 1;
    let buckets = Array.from({ length: bucket_num }, () => [Infinity, -Infinity]);

    for (let num of nums) {
        let idx = Math.floor((num - min_val) / bucket_size);
        buckets[idx][0] = Math.min(buckets[idx][0], num);
        buckets[idx][1] = Math.max(buckets[idx][1], num);
    }

    let max_gap = 0, prev_max = min_val;
    for (let bucket of buckets) {
        if (bucket[0] === Infinity) continue;
        max_gap = Math.max(max_gap, bucket[0] - prev_max);
        prev_max = bucket[1];
    }
    return max_gap;
}
```
The algorithm first finds the minimum and maximum values of the input array `nums`. Then it calculates the ideal bucket size by dividing the difference between the maximum and minimum values by the length of the array minus one. The algorithm then initializes an array of buckets, where each bucket contains the minimum and maximum values of its elements.

Next, the algorithm updates the minimum and maximum values for each bucket appropriately by iterating through the input array. Finally, the algorithm calculates the maximum gap by finding the difference between the minimum value of the current bucket and the maximum value of the previous non-empty bucket, and updating the maximum gap value accordingly.

This algorithm runs in linear time, because it iterates through the input array once to fill the buckets, and then it iterates through the buckets once to compute the maximum gap. It also uses linear extra space, as the number of buckets is proportional to the length of the input array.


# Compare Version Numbers

- slug: compare-version-numbers
- difficulty: Medium

Given two version numbers, `version1` and `version2`, compare them.

Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers.

To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`.

_Return the following:_

*   If `version1 < version2`, return `-1`.
*   If `version1 > version2`, return `1`.
*   Otherwise, return `0`.

**Example 1:**

**Input:** version1 =  "1.01 ", version2 =  "1.001 "
**Output:** 0
**Explanation:** Ignoring leading zeroes, both  "01 " and  "001 " represent the same integer  "1 ".

**Example 2:**

**Input:** version1 =  "1.0 ", version2 =  "1.0.0 "
**Output:** 0
**Explanation:** version1 does not specify revision 2, which means it is treated as  "0 ".

**Example 3:**

**Input:** version1 =  "0.1 ", version2 =  "1.1 "
**Output:** -1
**Explanation:** version1's revision 0 is  "0 ", while version2's revision 0 is  "1 ". 0 < 1, so version1 < version2.

**Constraints:**

*   `1 <= version1.length, version2.length <= 500`
*   `version1` and `version2` only contain digits and `'.'`.
*   `version1` and `version2` **are valid version numbers**.
*   All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.

## A solution in Java

```java
public int compareVersion(String version1, String version2) {
    int i = 0, j = 0;
    while (i < version1.length() || j < version2.length()) {
        int num1 = 0, num2 = 0;
        while (i < version1.length() && version1.charAt(i) != '.') {
            num1 = num1 * 10 + (version1.charAt(i++) - '0');
        }
        while (j < version2.length() && version2.charAt(j) != '.') {
            num2 = num2 * 10 + (version2.charAt(j++) - '0');
        }
        if (num1 < num2) return -1;
        if (num1 > num2) return 1;
        i++; j++;
    }
    return 0;
}
```
1. Set two pointers `i` and `j` at the beginning of each version string.
2. Start a while loop that runs while either pointer has not reached the end of its version string.
3. Initialize two integer variables `num1` and `num2`.
4. Inside the while loop, extract the integer revision values by scanning the digits at the current pointer locations and incrementing the pointers while skipping dot separators.
5. Compare the extracted revisions. If `num1` is smaller, return -1. If `num2` is smaller, return 1.
6. After comparing revisions or if both pointers reach the end of their version strings, increment the pointers.
7. If the while loop finishes without finding a difference in the revisions, the version numbers are equal, so return 0.

## A solution in C++

```cpp
int compareVersion(string version1, string version2) {
    int i = 0, j = 0;
    while (i < version1.size() || j < version2.size()) {
        int num1 = 0, num2 = 0;
        while (i < version1.size() && version1[i] != '.') {
            num1 = num1 * 10 + (version1[i++] - '0');
        }
        while (j < version2.size() && version2[j] != '.') {
            num2 = num2 * 10 + (version2[j++] - '0');
        }
        if (num1 < num2) return -1;
        if (num1 > num2) return 1;
        i++; j++;
    }
    return 0;
}
```
1. Set two pointers `i` and `j` at the beginning of each version string.
2. Start a while loop that runs while either pointer has not reached the end of its version string.
3. Initialize two integer variables `num1` and `num2`.
4. Inside the while loop, extract the integer revision values by scanning the digits at the current pointer locations and incrementing the pointers while skipping dot separators.
5. Compare the extracted revisions. If `num1` is smaller, return -1. If `num2` is smaller, return 1.
6. After comparing revisions or if both pointers reach the end of their version strings, increment the pointers.
7. If the while loop finishes without finding a difference in the revisions, the version numbers are equal, so return 0.

## A solution in Python

```python
def compare_version(version1, version2):
    v1 = version1.split('.')
    v2 = version2.split('.')

    while v1 or v2:
        num1 = int(v1.pop(0)) if v1 else 0
        num2 = int(v2.pop(0)) if v2 else 0

        if num1 < num2:
            return -1
        if num1 > num2:
            return 1
    return 0
```
1. Set two pointers `i` and `j` at the beginning of each version string.
2. Start a while loop that runs while either pointer has not reached the end of its version string.
3. Initialize two integer variables `num1` and `num2`.
4. Inside the while loop, extract the integer revision values by scanning the digits at the current pointer locations and incrementing the pointers while skipping dot separators.
5. Compare the extracted revisions. If `num1` is smaller, return -1. If `num2` is smaller, return 1.
6. After comparing revisions or if both pointers reach the end of their version strings, increment the pointers.
7. If the while loop finishes without finding a difference in the revisions, the version numbers are equal, so return 0.

## A solution in Javascript

```javascript
function compareVersion(version1, version2) {
    const v1 = version1.split('.');
    const v2 = version2.split('.');

    while (v1.length > 0 || v2.length > 0) {
        const num1 = v1.length > 0 ? parseInt(v1.shift()) : 0;
        const num2 = v2.length > 0 ? parseInt(v2.shift()) : 0;

        if (num1 < num2) return -1;
        if (num1 > num2) return 1;
    }
    return 0;
}
```
1. Set two pointers `i` and `j` at the beginning of each version string.
2. Start a while loop that runs while either pointer has not reached the end of its version string.
3. Initialize two integer variables `num1` and `num2`.
4. Inside the while loop, extract the integer revision values by scanning the digits at the current pointer locations and incrementing the pointers while skipping dot separators.
5. Compare the extracted revisions. If `num1` is smaller, return -1. If `num2` is smaller, return 1.
6. After comparing revisions or if both pointers reach the end of their version strings, increment the pointers.
7. If the while loop finishes without finding a difference in the revisions, the version numbers are equal, so return 0.


# Fraction to Recurring Decimal

- slug: fraction-to-recurring-decimal
- difficulty: Medium

Given two integers representing the `numerator` and `denominator` of a fraction, return _the fraction in string format_.

If the fractional part is repeating, enclose the repeating part in parentheses.

If multiple answers are possible, return **any of them**.

It is **guaranteed** that the length of the answer string is less than `104` for all the given inputs.

**Example 1:**

**Input:** numerator = 1, denominator = 2
**Output:**  "0.5 "

**Example 2:**

**Input:** numerator = 2, denominator = 1
**Output:**  "2 "

**Example 3:**

**Input:** numerator = 4, denominator = 333
**Output:**  "0.(012) "

**Constraints:**

*   `-231 <= numerator, denominator <= 231 - 1`
*   `denominator != 0`

## A solution in Java

```java
import java.util.HashMap;

public String fractionToDecimal(int numerator, int denominator) {
    if (numerator == 0) return "0";
    StringBuilder res = new StringBuilder();
    if ((numerator > 0) ^ (denominator > 0)) res.append('-');
    long num = Math.abs((long)numerator), den = Math.abs((long)denominator);
    res.append(num / den);
    num %= den;
    if (num == 0) return res.toString();
    res.append('.');
    HashMap<Long, Integer> map = new HashMap<>();
    while (num != 0) {
        if (map.containsKey(num)) {
            res.insert(map.get(num), "(");
            res.append(")");
            break;
        }
        map.put(num, res.length());
        num *= 10;
        res.append(num / den);
        num %= den;
    }
    return res.toString();
}
```
The algorithm follows the steps:
1. If numerator is 0, the result is 0.
2. Add the sign to the result string if necessary, and make both numerator and denominator positive.
3. Calculate integer part using integer division and add it to the result string.
4. Calculate the remainder of the division.
5. If the remainder is 0, return the result. Otherwise, add a dot to the result string.
6. Use a hash map to store remainder positions. Iterate while the remainder is not 0.
   - If the remainder is in the map, add parentheses around the repeating part and break the loop.
   - Update the hash map with the current remainder and its position in the result string.
   - Multiply the remainder by 10, add the new integer part to the result string, and update the remainder.
7. Return the result string.

## A solution in C++

```cpp
#include <unordered_map>
std::string fractionToDecimal(int numerator, int denominator) {
    if (numerator == 0) return "0";
    std::string res;
    if ((numerator > 0) ^ (denominator > 0)) res += '-';
    long num = std::abs((long)numerator), den = std::abs((long)denominator);
    res += std::to_string(num / den);
    num %= den;
    if (num == 0) return res;
    res += '.';
    std::unordered_map<int, int> map;
    while (num) {
        if (map.find(num) != map.end()) {
            res.insert(map[num], "(");
            res += ")";
            break;
        }
        map[num] = res.size();
        num *= 10;
        res += std::to_string(num / den);
        num %= den;
    }
    return res;
}
```
The algorithm follows the steps:
1. If numerator is 0, the result is 0.
2. Add the sign to the result string if necessary, and make both numerator and denominator positive.
3. Calculate integer part using integer division and add it to the result string.
4. Calculate the remainder of the division.
5. If the remainder is 0, return the result. Otherwise, add a dot to the result string.
6. Use a hash map to store remainder positions. Iterate while the remainder is not 0.
   - If the remainder is in the map, add parentheses around the repeating part and break the loop.
   - Update the hash map with the current remainder and its position in the result string.
   - Multiply the remainder by 10, add the new integer part to the result string, and update the remainder.
7. Return the result string.

## A solution in Python

```python
def fraction_to_decimal(numerator, denominator):
    if numerator == 0:
        return "0"
    res = []
    if (numerator > 0) ^ (denominator > 0):
        res.append("-")
    num = abs(numerator)
    den = abs(denominator)
    res.append(str(num // den))
    num %= den
    if num == 0:
        return "".join(res)
    res.append(".")
    map = {}
    while num:
        if num in map:
            res.insert(map[num], "(")
            res.append(")")
            break
        map[num] = len(res)
        num *= 10
        res.append(str(num // den))
        num %= den
    return "".join(res)
```
The algorithm follows the steps:
1. If numerator is 0, the result is 0.
2. Add the sign to the result string if necessary, and make both numerator and denominator positive.
3. Calculate integer part using integer division and add it to the result string.
4. Calculate the remainder of the division.
5. If the remainder is 0, return the result. Otherwise, add a dot to the result string.
6. Use a hash map to store remainder positions. Iterate while the remainder is not 0.
   - If the remainder is in the map, add parentheses around the repeating part and break the loop.
   - Update the hash map with the current remainder and its position in the result string.
   - Multiply the remainder by 10, add the new integer part to the result string, and update the remainder.
7. Return the result string.

## A solution in Javascript

```javascript
function fractionToDecimal(numerator, denominator) {
    if (numerator === 0) return "0";
    let res = "";
    if ((numerator > 0) ^ (denominator > 0)) res += '-';
    let num = Math.abs(numerator), den = Math.abs(denominator);
    res += Math.floor(num / den);
    num %= den;
    if (num === 0) return res;
    res += '.';
    let map = new Map();
    while (num) {
        if (map.has(num)) {
            res = res.slice(0, map.get(num)) + "(" + res.slice(map.get(num)) + ")";
            break;
        }
        map.set(num, res.length);
        num *= 10;
        res += Math.floor(num / den);
        num %= den;
    }
    return res;
}
```
The algorithm follows the steps:
1. If numerator is 0, the result is 0.
2. Add the sign to the result string if necessary, and make both numerator and denominator positive.
3. Calculate integer part using integer division and add it to the result string.
4. Calculate the remainder of the division.
5. If the remainder is 0, return the result. Otherwise, add a dot to the result string.
6. Use a hash map to store remainder positions. Iterate while the remainder is not 0.
   - If the remainder is in the map, add parentheses around the repeating part and break the loop.
   - Update the hash map with the current remainder and its position in the result string.
   - Multiply the remainder by 10, add the new integer part to the result string, and update the remainder.
7. Return the result string.


# Two Sum II - Input Array Is Sorted

- slug: two-sum-ii-input-array-is-sorted
- difficulty: Medium

Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`.

Return _the indices of the two numbers,_ `index1` _and_ `index2`_, **added by one** as an integer array_ `[index1, index2]` _of length 2._

The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice.

Your solution must use only constant extra space.

**Example 1:**

**Input:** numbers = \[2,7,11,15\], target = 9
**Output:** \[1,2\]
**Explanation:** The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return \[1, 2\].

**Example 2:**

**Input:** numbers = \[2,3,4\], target = 6
**Output:** \[1,3\]
**Explanation:** The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return \[1, 3\].

**Example 3:**

**Input:** numbers = \[\-1,0\], target = -1
**Output:** \[1,2\]
**Explanation:** The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return \[1, 2\].

**Constraints:**

*   `2 <= numbers.length <= 3 * 104`
*   `-1000 <= numbers[i] <= 1000`
*   `numbers` is sorted in **non-decreasing order**.
*   `-1000 <= target <= 1000`
*   The tests are generated such that there is **exactly one solution**.

## A solution in Java

```java
public int[] twoSum(int[] numbers, int target) {
    int left = 0, right = numbers.length - 1;
    while (left < right) {
        int current_sum = numbers[left] + numbers[right];
        if (current_sum == target) {
            return new int[]{left + 1, right + 1};
        } else if (current_sum < target) {
            left++;
        } else {
            right--;
        }
    }
    return new int[]{};
}
```
The algorithm uses a two-pointer approach. Initialize two pointers, `left` and `right`, to the first and last elements of the sorted array. Then, iterate until `left < right`. In each iteration, calculate the sum of the elements pointed to by `left` and `right`. If the sum equals the target, return the indices of the two numbers (1-indexed). If the sum is less than the target, increment `left` to consider a larger number. If the sum is greater than the target, decrement `right` to consider a smaller number. Since the input is guaranteed to have a solution, the loop will always return a valid result. This algorithm has a constant space complexity as it does not use any additional data structures.

## A solution in C++

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

vector<int> twoSum(vector<int>& numbers, int target) {
    int left = 0, right = numbers.size() - 1;
    while (left < right) {
        int current_sum = numbers[left] + numbers[right];
        if (current_sum == target) {
            return {left + 1, right + 1};
        } else if (current_sum < target) {
            left++;
        } else {
            right--;
        }
    }
    return {};
}
```
The algorithm uses a two-pointer approach. Initialize two pointers, `left` and `right`, to the first and last elements of the sorted array. Then, iterate until `left < right`. In each iteration, calculate the sum of the elements pointed to by `left` and `right`. If the sum equals the target, return the indices of the two numbers (1-indexed). If the sum is less than the target, increment `left` to consider a larger number. If the sum is greater than the target, decrement `right` to consider a smaller number. Since the input is guaranteed to have a solution, the loop will always return a valid result. This algorithm has a constant space complexity as it does not use any additional data structures.

## A solution in Python

```python
def twoSum(numbers, target):
    left, right = 0, len(numbers) - 1
    while left < right:
        current_sum = numbers[left] + numbers[right]
        if current_sum == target:
            return [left + 1, right + 1]
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    return []
```
The algorithm uses a two-pointer approach. Initialize two pointers, `left` and `right`, to the first and last elements of the sorted array. Then, iterate until `left < right`. In each iteration, calculate the sum of the elements pointed to by `left` and `right`. If the sum equals the target, return the indices of the two numbers (1-indexed). If the sum is less than the target, increment `left` to consider a larger number. If the sum is greater than the target, decrement `right` to consider a smaller number. Since the input is guaranteed to have a solution, the loop will always return a valid result. This algorithm has a constant space complexity as it does not use any additional data structures.

## A solution in Javascript

```javascript
function twoSum(numbers, target) {
    let left = 0, right = numbers.length - 1;
    while (left < right) {
        let current_sum = numbers[left] + numbers[right];
        if (current_sum === target) {
            return [left + 1, right + 1];
        } else if (current_sum < target) {
            left++;
        } else {
            right--;
        }
    }
    return [];
}
```
The algorithm uses a two-pointer approach. Initialize two pointers, `left` and `right`, to the first and last elements of the sorted array. Then, iterate until `left < right`. In each iteration, calculate the sum of the elements pointed to by `left` and `right`. If the sum equals the target, return the indices of the two numbers (1-indexed). If the sum is less than the target, increment `left` to consider a larger number. If the sum is greater than the target, decrement `right` to consider a smaller number. Since the input is guaranteed to have a solution, the loop will always return a valid result. This algorithm has a constant space complexity as it does not use any additional data structures.


# Excel Sheet Column Title

- slug: excel-sheet-column-title
- difficulty: Easy

Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...

**Example 1:**

**Input:** columnNumber = 1
**Output:**  "A "

**Example 2:**

**Input:** columnNumber = 28
**Output:**  "AB "

**Example 3:**

**Input:** columnNumber = 701
**Output:**  "ZY "

**Constraints:**

*   `1 <= columnNumber <= 231 - 1`

## A solution in Java

```java
public String convertToTitle(int columnNumber) {
    StringBuilder result = new StringBuilder();
    while (columnNumber > 0) {
        columnNumber--;
        result.insert(0, (char) ('A' + columnNumber % 26));
        columnNumber /= 26;
    }
    return result.toString();
}
```
The algorithm converts an integer `columnNumber` to its corresponding column title as it appears in an Excel sheet. It does so by treating the Excel sheet column headers as a Base-26 number system where the numbers are represented by the characters from A-Z.

1. We start by initializing an empty string called `result` that will store the final column title.
2. In a while loop, we continue until the `columnNumber` is greater than 0.
3. We subtract 1 from `columnNumber`, as the base representation starts from A (1).
4. The remainder of `columnNumber` divided by 26 is the index of the character in the A-Z range, which is added to the `result` string.
5. `columnNumber` is then divided by 26 and the loop continues until `columnNumber` is 0.
6. Once the loop is finished, the `result` string is returned as the corresponding column title.

## A solution in C++

```cpp
#include <string>

std::string convertToTitle(int columnNumber) {
    std::string result = "";
    while (columnNumber) {
        columnNumber--;
        result = (char)(columnNumber % 26 + 'A') + result;
        columnNumber /= 26;
    }
    return result;
}
```
The algorithm converts an integer `columnNumber` to its corresponding column title as it appears in an Excel sheet. It does so by treating the Excel sheet column headers as a Base-26 number system where the numbers are represented by the characters from A-Z.

1. We start by initializing an empty string called `result` that will store the final column title.
2. In a while loop, we continue until the `columnNumber` is greater than 0.
3. We subtract 1 from `columnNumber`, as the base representation starts from A (1).
4. The remainder of `columnNumber` divided by 26 is the index of the character in the A-Z range, which is added to the `result` string.
5. `columnNumber` is then divided by 26 and the loop continues until `columnNumber` is 0.
6. Once the loop is finished, the `result` string is returned as the corresponding column title.

## A solution in Python

```python
def convert_to_title(columnNumber: int) -> str:
    result = ""
    while columnNumber:
        columnNumber -= 1
        result = chr(columnNumber % 26 + ord('A')) + result
        columnNumber //= 26
    return result
```
The algorithm converts an integer `columnNumber` to its corresponding column title as it appears in an Excel sheet. It does so by treating the Excel sheet column headers as a Base-26 number system where the numbers are represented by the characters from A-Z.

1. We start by initializing an empty string called `result` that will store the final column title.
2. In a while loop, we continue until the `columnNumber` is greater than 0.
3. We subtract 1 from `columnNumber`, as the base representation starts from A (1).
4. The remainder of `columnNumber` divided by 26 is the index of the character in the A-Z range, which is added to the `result` string.
5. `columnNumber` is then divided by 26 and the loop continues until `columnNumber` is 0.
6. Once the loop is finished, the `result` string is returned as the corresponding column title.

## A solution in Javascript

```javascript
function convertToTitle(columnNumber) {
    let result = "";
    while (columnNumber) {
        columnNumber--;
        result = String.fromCharCode(columnNumber % 26 + 'A'.charCodeAt(0)) + result;
        columnNumber = Math.floor(columnNumber / 26);
    }
    return result;
}
```
The algorithm converts an integer `columnNumber` to its corresponding column title as it appears in an Excel sheet. It does so by treating the Excel sheet column headers as a Base-26 number system where the numbers are represented by the characters from A-Z.

1. We start by initializing an empty string called `result` that will store the final column title.
2. In a while loop, we continue until the `columnNumber` is greater than 0.
3. We subtract 1 from `columnNumber`, as the base representation starts from A (1).
4. The remainder of `columnNumber` divided by 26 is the index of the character in the A-Z range, which is added to the `result` string.
5. `columnNumber` is then divided by 26 and the loop continues until `columnNumber` is 0.
6. Once the loop is finished, the `result` string is returned as the corresponding column title.


# Majority Element

- slug: majority-element
- difficulty: Easy

Given an array `nums` of size `n`, return _the majority element_.

The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array.

**Example 1:**

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

**Example 2:**

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

**Constraints:**

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

**Follow-up:** Could you solve the problem in linear time and in `O(1)` space?

## A solution in Java

```java
public int majorityElement(int[] nums) {
    int count = 0;
    Integer candidate = null;

    for (int num : nums) {
        if (count == 0) {
            candidate = num;
        }
        count += (num == candidate) ? 1 : -1;
    }

    return candidate;
}
```
The algorithm used here is called the Boyer-Moore Majority Vote algorithm. It works by initializing a candidate element and a count. Then, we iterate through the given array. If the count is 0, we set the candidate to the current element in the array. Then we update the count by adding 1 if the current element is equal to the candidate, or subtracting 1 otherwise. At the end of the iteration, the candidate will have the majority element.

The algorithm works because if there is a majority element, it will always appear more than the sum of all other elements, so the count will not be 0 at the end.

## A solution in C++

```cpp
int majorityElement(vector<int>& nums) {
    int count = 0;
    int candidate;

    for (int num : nums) {
        if (count == 0) {
            candidate = num;
        }
        count += (num == candidate) ? 1 : -1;
    }

    return candidate;
}
```
The algorithm used here is called the Boyer-Moore Majority Vote algorithm. It works by initializing a candidate element and a count. Then, we iterate through the given array. If the count is 0, we set the candidate to the current element in the array. Then we update the count by adding 1 if the current element is equal to the candidate, or subtracting 1 otherwise. At the end of the iteration, the candidate will have the majority element.

The algorithm works because if there is a majority element, it will always appear more than the sum of all other elements, so the count will not be 0 at the end.

## A solution in Python

```python
def majority_element(nums):
    count = 0
    candidate = None

    for num in nums:
        if count == 0:
            candidate = num
        count += (num == candidate) - (num != candidate)

    return candidate
```
The algorithm used here is called the Boyer-Moore Majority Vote algorithm. It works by initializing a candidate element and a count. Then, we iterate through the given array. If the count is 0, we set the candidate to the current element in the array. Then we update the count by adding 1 if the current element is equal to the candidate, or subtracting 1 otherwise. At the end of the iteration, the candidate will have the majority element.

The algorithm works because if there is a majority element, it will always appear more than the sum of all other elements, so the count will not be 0 at the end.

## A solution in Javascript

```javascript
function majorityElement(nums) {
    let count = 0;
    let candidate = null;

    for (const num of nums) {
        if (count === 0) {
            candidate = num;
        }
        count += (num === candidate) ? 1 : -1;
    }

    return candidate;
}
```
The algorithm used here is called the Boyer-Moore Majority Vote algorithm. It works by initializing a candidate element and a count. Then, we iterate through the given array. If the count is 0, we set the candidate to the current element in the array. Then we update the count by adding 1 if the current element is equal to the candidate, or subtracting 1 otherwise. At the end of the iteration, the candidate will have the majority element.

The algorithm works because if there is a majority element, it will always appear more than the sum of all other elements, so the count will not be 0 at the end.


# Two Sum III - Data structure design

- slug: two-sum-iii-data-structure-design
- difficulty: Easy

Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.

Implement the `TwoSum` class:

*   `TwoSum()` Initializes the `TwoSum` object, with an empty array initially.
*   `void add(int number)` Adds `number` to the data structure.
*   `boolean find(int value)` Returns `true` if there exists any pair of numbers whose sum is equal to `value`, otherwise, it returns `false`.

**Example 1:**

**Input**
\[ "TwoSum ",  "add ",  "add ",  "add ",  "find ",  "find "\]
\[\[\], \[1\], \[3\], \[5\], \[4\], \[7\]\]
**Output**
\[null, null, null, null, true, false\]

**Explanation**
TwoSum twoSum = new TwoSum();
twoSum.add(1);   // \[\] --> \[1\]
twoSum.add(3);   // \[1\] --> \[1,3\]
twoSum.add(5);   // \[1,3\] --> \[1,3,5\]
twoSum.find(4);  // 1 + 3 = 4, return true
twoSum.find(7);  // No two integers sum up to 7, return false

**Constraints:**

*   `-105 <= number <= 105`
*   `-231 <= value <= 231 - 1`
*   At most `104` calls will be made to `add` and `find`.

## A solution in Java

```java
import java.util.HashMap;

class TwoSum {
    private HashMap<Integer, Integer> nums;

    public TwoSum() {
        nums = new HashMap<>();
    }

    public void add(int number) {
        nums.put(number, nums.getOrDefault(number, 0) + 1);
    }

    public boolean find(int value) {
        for (Integer i : nums.keySet()) {
            int complement = value - i;
            if (nums.containsKey(complement)) {
                if (i != complement || nums.get(i) > 1) {
                    return true;
                }
            }
        }
        return false;
    }
}
```
We create a class `TwoSum` to represent the data structure. We use a hashmap (`unordered_map` in C++, `HashMap` in Java, dictionary in Python, and object in JavaScript) to store the numbers as keys and their counts as values.

In the `add` method, we simply increment the count of the number in the hashmap.

In the `find` method, we iterate through the keys of the hashmap. For each number, we calculate its complement (`value - number`). If the complement is present in the hashmap, we check two cases:
1. If `number` and `complement` are the same, we need at least two occurrences of the number in the hashmap to form a pair.
2. If `number` and `complement` are different, we have our required pair and return `true`.

If we go through the entire hashmap and don't find any pair that satisfies one of the above conditions, we return `false`.

## A solution in C++

```cpp
class TwoSum {
public:
    unordered_map<int, int> m;

    TwoSum() {

    }

    void add(int number) {
        m[number]++;
    }

    bool find(int value) {
        for (auto &pair : m) {
            int num1 = pair.first;
            int num2 = value - num1;
            if (num1 == num2 && pair.second > 1 || num1 != num2 && m.count(num2)) {
                return true;
            }
        }
        return false;
    }
};
```
We create a class `TwoSum` to represent the data structure. We use a hashmap (`unordered_map` in C++, `HashMap` in Java, dictionary in Python, and object in JavaScript) to store the numbers as keys and their counts as values.

In the `add` method, we simply increment the count of the number in the hashmap.

In the `find` method, we iterate through the keys of the hashmap. For each number, we calculate its complement (`value - number`). If the complement is present in the hashmap, we check two cases:
1. If `number` and `complement` are the same, we need at least two occurrences of the number in the hashmap to form a pair.
2. If `number` and `complement` are different, we have our required pair and return `true`.

If we go through the entire hashmap and don't find any pair that satisfies one of the above conditions, we return `false`.

## A solution in Python

```python
class TwoSum:

    def __init__(self):
        self.nums = {}

    def add(self, number: int) -> None:
        if number in self.nums:
            self.nums[number] += 1
        else:
            self.nums[number] = 1

    def find(self, value: int) -> bool:
        for num in self.nums:
            target = value - num
            if target in self.nums:
                if target != num or self.nums[num] > 1:
                    return True
        return False
```
We create a class `TwoSum` to represent the data structure. We use a hashmap (`unordered_map` in C++, `HashMap` in Java, dictionary in Python, and object in JavaScript) to store the numbers as keys and their counts as values.

In the `add` method, we simply increment the count of the number in the hashmap.

In the `find` method, we iterate through the keys of the hashmap. For each number, we calculate its complement (`value - number`). If the complement is present in the hashmap, we check two cases:
1. If `number` and `complement` are the same, we need at least two occurrences of the number in the hashmap to form a pair.
2. If `number` and `complement` are different, we have our required pair and return `true`.

If we go through the entire hashmap and don't find any pair that satisfies one of the above conditions, we return `false`.

## A solution in Javascript

```javascript
class TwoSum {
    constructor() {
        this.nums = {};
    }

    add(number) {
        if (this.nums.hasOwnProperty(number)) {
            this.nums[number]++;
        } else {
            this.nums[number] = 1;
        }
    }

    find(value) {
        for (let num in this.nums) {
            let target = value - num;
            if (this.nums.hasOwnProperty(target)) {
                if (target !== num || this.nums[num] > 1) {
                    return true;
                }
            }
        }
        return false;
    }
}
```
We create a class `TwoSum` to represent the data structure. We use a hashmap (`unordered_map` in C++, `HashMap` in Java, dictionary in Python, and object in JavaScript) to store the numbers as keys and their counts as values.

In the `add` method, we simply increment the count of the number in the hashmap.

In the `find` method, we iterate through the keys of the hashmap. For each number, we calculate its complement (`value - number`). If the complement is present in the hashmap, we check two cases:
1. If `number` and `complement` are the same, we need at least two occurrences of the number in the hashmap to form a pair.
2. If `number` and `complement` are different, we have our required pair and return `true`.

If we go through the entire hashmap and don't find any pair that satisfies one of the above conditions, we return `false`.


# Excel Sheet Column Number

- slug: excel-sheet-column-number
- difficulty: Easy

Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...

**Example 1:**

**Input:** columnTitle =  "A "
**Output:** 1

**Example 2:**

**Input:** columnTitle =  "AB "
**Output:** 28

**Example 3:**

**Input:** columnTitle =  "ZY "
**Output:** 701

**Constraints:**

*   `1 <= columnTitle.length <= 7`
*   `columnTitle` consists only of uppercase English letters.
*   `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.

## A solution in Java

```java
public int titleToNumber(String columnTitle) {
    int result = 0;
    for (char c : columnTitle.toCharArray()) {
        result = result * 26 + (c - 'A' + 1);
    }
    return result;
}
```
The algorithm iterates through the given `columnTitle` string and computes the corresponding column number by treating the string like a base-26 number representation, where 'A' represents the digit 1 and 'Z' represents the digit 26. To convert each character to its corresponding numeric value, we subtract the ASCII value of 'A' and add 1. In each iteration, the current result is multiplied by 26 and the numeric value of the current character is added to the result. Finally, the accumulated result is returned as the column number.

## A solution in C++

```cpp
int titleToNumber(string columnTitle) {
    int result = 0;
    for (char c : columnTitle) {
        result = result * 26 + (c - 'A' + 1);
    }
    return result;
}
```
The algorithm iterates through the given `columnTitle` string and computes the corresponding column number by treating the string like a base-26 number representation, where 'A' represents the digit 1 and 'Z' represents the digit 26. To convert each character to its corresponding numeric value, we subtract the ASCII value of 'A' and add 1. In each iteration, the current result is multiplied by 26 and the numeric value of the current character is added to the result. Finally, the accumulated result is returned as the column number.

## A solution in Python

```python
def title_to_number(column_title: str) -> int:
    result = 0
    for c in column_title:
        result = result * 26 + (ord(c) - ord('A') + 1)
    return result
```
The algorithm iterates through the given `columnTitle` string and computes the corresponding column number by treating the string like a base-26 number representation, where 'A' represents the digit 1 and 'Z' represents the digit 26. To convert each character to its corresponding numeric value, we subtract the ASCII value of 'A' and add 1. In each iteration, the current result is multiplied by 26 and the numeric value of the current character is added to the result. Finally, the accumulated result is returned as the column number.

## A solution in Javascript

```javascript
function titleToNumber(columnTitle) {
    let result = 0;
    for (let c of columnTitle) {
        result = result * 26 + (c.charCodeAt(0) - 'A'.charCodeAt(0) + 1);
    }
    return result;
}
```
The algorithm iterates through the given `columnTitle` string and computes the corresponding column number by treating the string like a base-26 number representation, where 'A' represents the digit 1 and 'Z' represents the digit 26. To convert each character to its corresponding numeric value, we subtract the ASCII value of 'A' and add 1. In each iteration, the current result is multiplied by 26 and the numeric value of the current character is added to the result. Finally, the accumulated result is returned as the column number.


# Factorial Trailing Zeroes

- slug: factorial-trailing-zeroes
- difficulty: Medium

Given an integer `n`, return _the number of trailing zeroes in_ `n!`.

Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`.

**Example 1:**

**Input:** n = 3
**Output:** 0
**Explanation:** 3! = 6, no trailing zero.

**Example 2:**

**Input:** n = 5
**Output:** 1
**Explanation:** 5! = 120, one trailing zero.

**Example 3:**

**Input:** n = 0
**Output:** 0

**Constraints:**

*   `0 <= n <= 104`

**Follow up:** Could you write a solution that works in logarithmic time complexity?

## A solution in Java

```java
public int trailingZeroes(int n) {
    int count = 0;
    while (n > 0) {
        n = n / 5;
        count += n;
    }
    return count;
}
```
The given problem requires us to calculate the number of trailing zeroes in n! (factorial of n). Trailing zeroes are formed by the product of 2 and 5. For example, 20! has 4 trailing zeroes as there are 4 instances of 2 * 5 (10, 20, 30, and 50). We know there are plenty of even factors in a factorial, so we just need to count how many times the factor 5 appears.

The algorithm we use here is dividing n by 5 iteratively until n becomes 0. In each step, we divide n by 5 and add the quotient to the count. Finally, we return the count as the result.

## A solution in C++

```cpp
int trailingZeroes(int n) {
    int count = 0;
    while (n > 0) {
        n /= 5;
        count += n;
    }
    return count;
}
```
The given problem requires us to calculate the number of trailing zeroes in n! (factorial of n). Trailing zeroes are formed by the product of 2 and 5. For example, 20! has 4 trailing zeroes as there are 4 instances of 2 * 5 (10, 20, 30, and 50). We know there are plenty of even factors in a factorial, so we just need to count how many times the factor 5 appears.

The algorithm we use here is dividing n by 5 iteratively until n becomes 0. In each step, we divide n by 5 and add the quotient to the count. Finally, we return the count as the result.

## A solution in Python

```python
def trailing_zeroes(n: int) -> int:
    count = 0
    while n > 0:
        n //= 5
        count += n
    return count
```
The given problem requires us to calculate the number of trailing zeroes in n! (factorial of n). Trailing zeroes are formed by the product of 2 and 5. For example, 20! has 4 trailing zeroes as there are 4 instances of 2 * 5 (10, 20, 30, and 50). We know there are plenty of even factors in a factorial, so we just need to count how many times the factor 5 appears.

The algorithm we use here is dividing n by 5 iteratively until n becomes 0. In each step, we divide n by 5 and add the quotient to the count. Finally, we return the count as the result.

## A solution in Javascript

```javascript
function trailingZeroes(n) {
    let count = 0;
    while (n > 0) {
        n = Math.floor(n / 5);
        count += n;
    }
    return count;
}
```
The given problem requires us to calculate the number of trailing zeroes in n! (factorial of n). Trailing zeroes are formed by the product of 2 and 5. For example, 20! has 4 trailing zeroes as there are 4 instances of 2 * 5 (10, 20, 30, and 50). We know there are plenty of even factors in a factorial, so we just need to count how many times the factor 5 appears.

The algorithm we use here is dividing n by 5 iteratively until n becomes 0. In each step, we divide n by 5 and add the quotient to the count. Finally, we return the count as the result.


# Binary Search Tree Iterator

- slug: binary-search-tree-iterator
- difficulty: Medium

Implement the `BSTIterator` class that represents an iterator over the **[in-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))** of a binary search tree (BST):

*   `BSTIterator(TreeNode root)` Initializes an object of the `BSTIterator` class. The `root` of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
*   `boolean hasNext()` Returns `true` if there exists a number in the traversal to the right of the pointer, otherwise returns `false`.
*   `int next()` Moves the pointer to the right, then returns the number at the pointer.

Notice that by initializing the pointer to a non-existent smallest number, the first call to `next()` will return the smallest element in the BST.

You may assume that `next()` calls will always be valid. That is, there will be at least a next number in the in-order traversal when `next()` is called.

**Example 1:**

**Input**
\[ "BSTIterator ",  "next ",  "next ",  "hasNext ",  "next ",  "hasNext ",  "next ",  "hasNext ",  "next ",  "hasNext "\]
\[\[\[7, 3, 15, null, null, 9, 20\]\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 3, 7, true, 9, true, 15, true, 20, false\]

**Explanation**
BSTIterator bSTIterator = new BSTIterator(\[7, 3, 15, null, null, 9, 20\]);
bSTIterator.next();    // return 3
bSTIterator.next();    // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 20
bSTIterator.hasNext(); // return False

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 105]`.
*   `0 <= Node.val <= 106`
*   At most `105` calls will be made to `hasNext`, and `next`.

**Follow up:**

*   Could you implement `next()` and `hasNext()` to run in average `O(1)` time and use `O(h)` memory, where `h` is the height of the tree?

## A solution in Java

```java
import java.util.Stack;

public class BSTIterator {
    private final Stack<TreeNode> stack;

    public BSTIterator(TreeNode root) {
        stack = new Stack<>();
        pushLeft(root);
    }

    public int next() {
        TreeNode top = stack.pop();
        pushLeft(top.right);
        return top.val;
    }

    public boolean hasNext() {
        return !stack.isEmpty();
    }

    private void pushLeft(TreeNode node) {
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
    }
}
```
The algorithm initializes an empty stack and pushes all the left nodes from the root to the lowest node in the tree. For each next() call, the algorithm pops the top node in the stack, which is the next smallest element, and adds the left subtree of the popped element to the stack if the popped node has a right child. The hasNext() method checks if there are any nodes left in the stack. This way, the iterator always has the next smallest element at the top of the stack.

## A solution in C++

```cpp
class BSTIterator {
public:
    stack<TreeNode*> stk;

    BSTIterator(TreeNode* root) {
        pushLeft(root);
    }

    int next() {
        TreeNode* top = stk.top();
        stk.pop();
        pushLeft(top->right);
        return top->val;
    }

    bool hasNext() {
        return !stk.empty();
    }

private:
    void pushLeft(TreeNode* node) {
        while (node) {
            stk.push(node);
            node = node->left;
        }
    }
};
```
The algorithm initializes an empty stack and pushes all the left nodes from the root to the lowest node in the tree. For each next() call, the algorithm pops the top node in the stack, which is the next smallest element, and adds the left subtree of the popped element to the stack if the popped node has a right child. The hasNext() method checks if there are any nodes left in the stack. This way, the iterator always has the next smallest element at the top of the stack.

## A solution in Python

```python
class BSTIterator:

    def __init__(self, root):
        self.stack = []
        self.push_left(root)

    def next(self):
        top = self.stack.pop()
        self.push_left(top.right)
        return top.val

    def hasNext(self):
        return len(self.stack) > 0

    def push_left(self, node):
        while node:
            self.stack.append(node)
            node = node.left
```
The algorithm initializes an empty stack and pushes all the left nodes from the root to the lowest node in the tree. For each next() call, the algorithm pops the top node in the stack, which is the next smallest element, and adds the left subtree of the popped element to the stack if the popped node has a right child. The hasNext() method checks if there are any nodes left in the stack. This way, the iterator always has the next smallest element at the top of the stack.

## A solution in Javascript

```javascript
class BSTIterator {
    constructor(root) {
        this.stack = [];
        this.pushLeft(root);
    }

    next() {
        let top = this.stack.pop();
        this.pushLeft(top.right);
        return top.val;
    }

    hasNext() {
        return this.stack.length > 0;
    }

    pushLeft(node) {
        while (node) {
            this.stack.push(node);
            node = node.left;
        }
    }
}
```
The algorithm initializes an empty stack and pushes all the left nodes from the root to the lowest node in the tree. For each next() call, the algorithm pops the top node in the stack, which is the next smallest element, and adds the left subtree of the popped element to the stack if the popped node has a right child. The hasNext() method checks if there are any nodes left in the stack. This way, the iterator always has the next smallest element at the top of the stack.


# Dungeon Game

- slug: dungeon-game
- difficulty: Hard

The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately.

Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).

To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step.

Return _the knight's minimum initial health so that he can rescue the princess_.

**Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.

**Example 1:**

**Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\]
**Output:** 7
**Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.

**Example 2:**

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

**Constraints:**

*   `m == dungeon.length`
*   `n == dungeon[i].length`
*   `1 <= m, n <= 200`
*   `-1000 <= dungeon[i][j] <= 1000`

## A solution in Java

```java
public int calculateMinimumHP(int[][] dungeon) {
    int m = dungeon.length, n = dungeon[0].length;
    int[][] dp = new int[m][n];

    for (int i = m - 1; i >= 0; i--) {
        for (int j = n - 1; j >= 0; j--) {
            if(i == m-1 && j == n-1)
                dp[i][j] = Math.min(0, dungeon[i][j]);
            else if (i == m - 1)
                dp[i][j] = Math.min(0, dp[i][j + 1] + dungeon[i][j]);
            else if (j == n - 1)
                dp[i][j] = Math.min(0, dp[i + 1][j] + dungeon[i][j]);
            else
                dp[i][j] = Math.min(0, Math.max(dp[i + 1][j], dp[i][j + 1]) + dungeon[i][j]);
        }
    }

    return Math.abs(dp[0][0]) + 1;
}
```
The algorithm uses dynamic programming to find the minimum health needed in a bottom-up manner by starting from the bottom-right corner of the dungeon to the top-left corner. We create a "dp" table with the same size as the dungeon and fill it initially with zeros. Then we iterate over each cell in the dungeon from the bottom-right to the top-left. For each cell, we consider the right and down adjacent cells (if they exist) and calculate the minimum health required to move forward. We update the "dp" table with these values. The minimum of the health required to move right or down, plus the current cell dungeon value, is then stored in the current cell in the "dp" table. Finally, we return the absolute value of the top-left cell of "dp" table plus one (for the initial health point). This gives us the minimum initial health needed to get to the princess.

## A solution in C++

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

int calculateMinimumHP(vector<vector<int>>& dungeon) {
    int m = dungeon.size(), n = dungeon[0].size();
    vector<vector<int>> dp(m, vector<int>(n));

    for (int i = m - 1; i >= 0; i--) {
        for (int j = n - 1; j >= 0; j--) {
            if(i == m-1 && j == n-1){
                dp[i][j] = min(0, dungeon[i][j]);
            }
            else if (i == m - 1) {
                dp[i][j] = min(0, dp[i][j + 1] + dungeon[i][j]);
            }
            else if (j == n - 1) {
                dp[i][j] = min(0, dp[i + 1][j] + dungeon[i][j]);
            }
            else {
                dp[i][j] = min(0, max(dp[i + 1][j], dp[i][j + 1]) + dungeon[i][j]);
            }
        }
    }

    return abs(dp[0][0]) + 1;
}
```
The algorithm uses dynamic programming to find the minimum health needed in a bottom-up manner by starting from the bottom-right corner of the dungeon to the top-left corner. We create a "dp" table with the same size as the dungeon and fill it initially with zeros. Then we iterate over each cell in the dungeon from the bottom-right to the top-left. For each cell, we consider the right and down adjacent cells (if they exist) and calculate the minimum health required to move forward. We update the "dp" table with these values. The minimum of the health required to move right or down, plus the current cell dungeon value, is then stored in the current cell in the "dp" table. Finally, we return the absolute value of the top-left cell of "dp" table plus one (for the initial health point). This gives us the minimum initial health needed to get to the princess.

## A solution in Python

```python
def calculateMinimumHP(dungeon):
    m, n = len(dungeon), len(dungeon[0])
    dp = [[0] * n for _ in range(m)]

    for i in range(m - 1, -1, -1):
        for j in range(n - 1, -1, -1):
            if i == m - 1 and j == n - 1:
                dp[i][j] = min(0, dungeon[i][j])
            elif i == m - 1:
                dp[i][j] = min(0, dp[i][j + 1] + dungeon[i][j])
            elif j == n - 1:
                dp[i][j] = min(0, dp[i + 1][j] + dungeon[i][j])
            else:
                dp[i][j] = min(0, max(dp[i + 1][j], dp[i][j + 1]) + dungeon[i][j])

    return abs(dp[0][0]) + 1
```
The algorithm uses dynamic programming to find the minimum health needed in a bottom-up manner by starting from the bottom-right corner of the dungeon to the top-left corner. We create a "dp" table with the same size as the dungeon and fill it initially with zeros. Then we iterate over each cell in the dungeon from the bottom-right to the top-left. For each cell, we consider the right and down adjacent cells (if they exist) and calculate the minimum health required to move forward. We update the "dp" table with these values. The minimum of the health required to move right or down, plus the current cell dungeon value, is then stored in the current cell in the "dp" table. Finally, we return the absolute value of the top-left cell of "dp" table plus one (for the initial health point). This gives us the minimum initial health needed to get to the princess.

## A solution in Javascript

```javascript
function calculateMinimumHP(dungeon) {
    const m = dungeon.length, n = dungeon[0].length;
    const dp = new Array(m).fill(0).map(() => new Array(n).fill(0));

    for (let i = m - 1; i >= 0; i--) {
        for (let j = n - 1; j >= 0; j--) {
            if (i === m - 1 && j === n - 1)
                dp[i][j] = Math.min(0, dungeon[i][j]);
            else if (i === m - 1)
                dp[i][j] = Math.min(0, dp[i][j + 1] + dungeon[i][j]);
            else if (j === n - 1)
                dp[i][j] = Math.min(0, dp[i + 1][j] + dungeon[i][j]);
            else
                dp[i][j] = Math.min(0, Math.max(dp[i + 1][j], dp[i][j + 1]) + dungeon[i][j]);
        }
    }

    return Math.abs(dp[0][0]) + 1;
}
```
The algorithm uses dynamic programming to find the minimum health needed in a bottom-up manner by starting from the bottom-right corner of the dungeon to the top-left corner. We create a "dp" table with the same size as the dungeon and fill it initially with zeros. Then we iterate over each cell in the dungeon from the bottom-right to the top-left. For each cell, we consider the right and down adjacent cells (if they exist) and calculate the minimum health required to move forward. We update the "dp" table with these values. The minimum of the health required to move right or down, plus the current cell dungeon value, is then stored in the current cell in the "dp" table. Finally, we return the absolute value of the top-left cell of "dp" table plus one (for the initial health point). This gives us the minimum initial health needed to get to the princess.


# Largest Number

- slug: largest-number
- difficulty: Medium

Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it.

Since the result may be very large, so you need to return a string instead of an integer.

**Example 1:**

**Input:** nums = \[10,2\]
**Output:**  "210 "

**Example 2:**

**Input:** nums = \[3,30,34,5,9\]
**Output:**  "9534330 "

**Constraints:**

*   `1 <= nums.length <= 100`
*   `0 <= nums[i] <= 109`

## A solution in Java

```java
import java.util.Arrays;
import java.util.Comparator;

public class Solution {
    public String largestNumber(int[] nums) {
        String[] strNums = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            strNums[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(strNums, (a, b) -> (b + a).compareTo(a + b));
        if (strNums[0].equals("0")) {
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        for (String str : strNums) sb.append(str);
        return sb.toString();
    }
}
```
1. Convert all integers to strings.
2. Sort the strings using a custom comparator. The comparator shall compare concatenation of two strings in reverse order, i.e., a+b and b+a. Compare a+b and b+a, if a+b is larger, it means a should be before b, else b should before a.
3. Join sorted strings to form the answer. If the first string is '0', return '0' as that means all elements are '0' (as strings are sorted).

## A solution in C++

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

bool compare(std::string a, std::string b) {
    return a+b > b+a;
}

std::string largestNumber(std::vector<int>& nums) {
    std::vector<std::string> asStrs;
    for (int num : nums) asStrs.push_back(std::to_string(num));
    std::sort(asStrs.begin(), asStrs.end(), compare);
    std::string res;
    for (std::string s: asStrs) res += s;
    return res[0] == '0' ? "0" : res;
}
```
1. Convert all integers to strings.
2. Sort the strings using a custom comparator. The comparator shall compare concatenation of two strings in reverse order, i.e., a+b and b+a. Compare a+b and b+a, if a+b is larger, it means a should be before b, else b should before a.
3. Join sorted strings to form the answer. If the first string is '0', return '0' as that means all elements are '0' (as strings are sorted).

## A solution in Python

```python
from functools import cmp_to_key

def largestNumber(nums):
    def comparator(a, b):
        return -1 if a + b > b + a else int(a + b < b + a)

    nums_as_str = list(map(str, nums))
    nums_as_str.sort(key=cmp_to_key(comparator))
    return '0' if nums_as_str[0] == "0" else "".join(nums_as_str)
```
1. Convert all integers to strings.
2. Sort the strings using a custom comparator. The comparator shall compare concatenation of two strings in reverse order, i.e., a+b and b+a. Compare a+b and b+a, if a+b is larger, it means a should be before b, else b should before a.
3. Join sorted strings to form the answer. If the first string is '0', return '0' as that means all elements are '0' (as strings are sorted).

## A solution in Javascript

```javascript
function largestNumber(nums) {
    const numsAsStrings = nums.map(String);
    numsAsStrings.sort((a, b) => (b + a).localeCompare(a + b));
    return numsAsStrings[0] === '0' ? '0' : numsAsStrings.join('');
}
```
1. Convert all integers to strings.
2. Sort the strings using a custom comparator. The comparator shall compare concatenation of two strings in reverse order, i.e., a+b and b+a. Compare a+b and b+a, if a+b is larger, it means a should be before b, else b should before a.
3. Join sorted strings to form the answer. If the first string is '0', return '0' as that means all elements are '0' (as strings are sorted).