# Longest Absolute File Path

- slug: longest-absolute-file-path
- difficulty: Medium

Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:

Here, we have `dir` as the only directory in the root. `dir` contains two subdirectories, `subdir1` and `subdir2`. `subdir1` contains a file `file1.ext` and subdirectory `subsubdir1`. `subdir2` contains a subdirectory `subsubdir2`, which contains a file `file2.ext`.

In text form, it looks like this (with ⟶ representing the tab character):

dir
⟶ subdir1
⟶ ⟶ file1.ext
⟶ ⟶ subsubdir1
⟶ subdir2
⟶ ⟶ subsubdir2
⟶ ⟶ ⟶ file2.ext

If we were to write this representation in code, it will look like this: `"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext "`. Note that the `'\n'` and `'\t'` are the new-line and tab characters.

Every file and directory has a unique **absolute path** in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by `'/'s`. Using the above example, the **absolute path** to `file2.ext` is `"dir/subdir2/subsubdir2/file2.ext "`. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form `name.extension`, where `name` and `extension` consist of letters, digits, and/or spaces.

Given a string `input` representing the file system in the explained format, return _the length of the **longest absolute path** to a **file** in the abstracted file system_. If there is no file in the system, return `0`.

**Note** that the testcases are generated such that the file system is valid and no file or directory name has length 0.

**Example 1:**

**Input:** input =  "dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext "
**Output:** 20
**Explanation:** We have only one file, and the absolute path is  "dir/subdir2/file.ext " of length 20.

**Example 2:**

**Input:** input =  "dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext "
**Output:** 32
**Explanation:** We have two files:
 "dir/subdir1/file1.ext " of length 21
 "dir/subdir2/subsubdir2/file2.ext " of length 32.
We return 32 since it is the longest absolute path to a file.

**Example 3:**

**Input:** input =  "a "
**Output:** 0
**Explanation:** We do not have any files, just a single directory named  "a ".

**Constraints:**

*   `1 <= input.length <= 104`
*   `input` may contain lowercase or uppercase English letters, a new line character `'\n'`, a tab character `'\t'`, a dot `'.'`, a space `' '`, and digits.
*   All file and directory names have **positive** length.

## A solution in Java

```java
import java.util.Stack;

public int lengthLongestPath(String input) {
    Stack<Integer> dirLengthStack = new Stack<>();
    String[] lines = input.split("\n");
    int maxFileLength = 0;

    for (String line : lines) {
        int level = line.lastIndexOf('\t') + 1;
        line = line.substring(level);

        while (dirLengthStack.size() > level) {
            dirLengthStack.pop();
        }

        int length = (dirLengthStack.isEmpty()) ? line.length() : dirLengthStack.peek() + line.length() + 1;
        dirLengthStack.push(length);

        if (line.contains(".")) {
            maxFileLength = Math.max(maxFileLength, length);
        }
    }

    return maxFileLength;
}
```
The algorithm maintains a stack named `dir_length_stack` to remember the lengths of the directory paths seen so far.

1. We split the input by new-line `\n` to get the lines.
2. For each line, we calculate its level by counting the number of tab `\t` characters.
3. We discard old levels from the `dir_length_stack` by popping elements until reaching the current level.
4. If `dir_length_stack` is not empty, we calculate the length of the current file/directory by adding the length of the parent directory, and the name of the current file/directory. If `dir_length_stack` is empty, we simply use the length of the current line.
5. We push the length into the `dir_length_stack`.
6. If the line contains a '.' (file), we update the maximum path length.
7. After the iteration, the result stored in `max_file_length` is returned.

## A solution in C++

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

int lengthLongestPath(std::string input) {
    std::istringstream ss(input);
    std::vector<int> dir_length_stack;
    std::string line;
    int max_file_length = 0;

    while (std::getline(ss, line, '\n')) {
        int level = 0;
        while (line.find('\t') != std::string::npos) {
            line.erase(0, 1);
            level++;
        }

        while (dir_length_stack.size() > level)
            dir_length_stack.pop_back();

        int length;
        if (dir_length_stack.empty()) {
            length = line.length();
        } else {
            length = dir_length_stack.back() + line.length() + 1;
        }
        dir_length_stack.push_back(length);

        if (line.find('.') != std::string::npos) {
            max_file_length = std::max(max_file_length, length);
        }
    }

    return max_file_length;
}
```
The algorithm maintains a stack named `dir_length_stack` to remember the lengths of the directory paths seen so far.

1. We split the input by new-line `\n` to get the lines.
2. For each line, we calculate its level by counting the number of tab `\t` characters.
3. We discard old levels from the `dir_length_stack` by popping elements until reaching the current level.
4. If `dir_length_stack` is not empty, we calculate the length of the current file/directory by adding the length of the parent directory, and the name of the current file/directory. If `dir_length_stack` is empty, we simply use the length of the current line.
5. We push the length into the `dir_length_stack`.
6. If the line contains a '.' (file), we update the maximum path length.
7. After the iteration, the result stored in `max_file_length` is returned.

## A solution in Python

```python
def length_longest_path(input: str) -> int:
    dir_length_stack = []
    max_file_length = 0
    lines = input.split('\n')

    for line in lines:
        level = line.count('\t')
        line = line.lstrip('\t')

        while len(dir_length_stack) > level:
            dir_length_stack.pop()

        if dir_length_stack:
            length = dir_length_stack[-1] + len(line) + 1
        else:
            length = len(line)
        dir_length_stack.append(length)

        if '.' in line:
            max_file_length = max(max_file_length, length)

    return max_file_length
```
The algorithm maintains a stack named `dir_length_stack` to remember the lengths of the directory paths seen so far.

1. We split the input by new-line `\n` to get the lines.
2. For each line, we calculate its level by counting the number of tab `\t` characters.
3. We discard old levels from the `dir_length_stack` by popping elements until reaching the current level.
4. If `dir_length_stack` is not empty, we calculate the length of the current file/directory by adding the length of the parent directory, and the name of the current file/directory. If `dir_length_stack` is empty, we simply use the length of the current line.
5. We push the length into the `dir_length_stack`.
6. If the line contains a '.' (file), we update the maximum path length.
7. After the iteration, the result stored in `max_file_length` is returned.

## A solution in Javascript

```javascript
function lengthLongestPath(input) {
    const dirLengthStack = [];
    const lines = input.split('\n');
    let maxFileLength = 0;

    for (const line of lines) {
        const level = (line.match(/\t/g) || []).length;
        const lineText = line.replace(/\t/g, '');

        while (dirLengthStack.length > level)
            dirLengthStack.pop();

        const length = (dirLengthStack.length === 0) ? lineText.length : (dirLengthStack[dirLengthStack.length - 1] + lineText.length + 1);
        dirLengthStack.push(length);

        if (lineText.includes('.')) {
            maxFileLength = Math.max(maxFileLength, length);
        }
    }

    return maxFileLength;
}
```
The algorithm maintains a stack named `dir_length_stack` to remember the lengths of the directory paths seen so far.

1. We split the input by new-line `\n` to get the lines.
2. For each line, we calculate its level by counting the number of tab `\t` characters.
3. We discard old levels from the `dir_length_stack` by popping elements until reaching the current level.
4. If `dir_length_stack` is not empty, we calculate the length of the current file/directory by adding the length of the parent directory, and the name of the current file/directory. If `dir_length_stack` is empty, we simply use the length of the current line.
5. We push the length into the `dir_length_stack`.
6. If the line contains a '.' (file), we update the maximum path length.
7. After the iteration, the result stored in `max_file_length` is returned.


# Find the Difference

- slug: find-the-difference
- difficulty: Easy

You are given two strings `s` and `t`.

String `t` is generated by random shuffling string `s` and then add one more letter at a random position.

Return the letter that was added to `t`.

**Example 1:**

**Input:** s =  "abcd ", t =  "abcde "
**Output:**  "e "
**Explanation:** 'e' is the letter that was added.

**Example 2:**

**Input:** s =  " ", t =  "y "
**Output:**  "y "

**Constraints:**

*   `0 <= s.length <= 1000`
*   `t.length == s.length + 1`
*   `s` and `t` consist of lowercase English letters.

## A solution in Java

```java
public char findTheDifference(String s, String t) {
    int sum_s = 0, sum_t = 0;
    for(char c : s.toCharArray()) sum_s += c;
    for(char c : t.toCharArray()) sum_t += c;
    return (char)(sum_t - sum_s);
}
```
The algorithm calculates the sum of the ASCII values of characters in both strings s and t. Since t is a shuffled version of s plus an extra character, the difference in the sums of ASCII values will give us the ASCII value of the added character. Finally, we return the character corresponding to this ASCII value.

## A solution in C++

```cpp
char findTheDifference(std::string s, std::string t) {
    int sum_s = 0, sum_t = 0;
    for(char c : s) sum_s += c;
    for(char c : t) sum_t += c;
    return sum_t - sum_s;
}
```
The algorithm calculates the sum of the ASCII values of characters in both strings s and t. Since t is a shuffled version of s plus an extra character, the difference in the sums of ASCII values will give us the ASCII value of the added character. Finally, we return the character corresponding to this ASCII value.

## A solution in Python

```python
def findTheDifference(s: str, t: str) -> str:
    return chr(sum(ord(c) for c in t) - sum(ord(c) for c in s))
```
The algorithm calculates the sum of the ASCII values of characters in both strings s and t. Since t is a shuffled version of s plus an extra character, the difference in the sums of ASCII values will give us the ASCII value of the added character. Finally, we return the character corresponding to this ASCII value.

## A solution in Javascript

```javascript
function findTheDifference(s, t) {
    let sum_s = 0, sum_t = 0;
    for(let c of s) sum_s += c.charCodeAt(0);
    for(let c of t) sum_t += c.charCodeAt(0);
    return String.fromCharCode(sum_t - sum_s);
}
```
The algorithm calculates the sum of the ASCII values of characters in both strings s and t. Since t is a shuffled version of s plus an extra character, the difference in the sums of ASCII values will give us the ASCII value of the added character. Finally, we return the character corresponding to this ASCII value.


# Elimination Game

- slug: elimination-game
- difficulty: Medium

You have a list `arr` of all integers in the range `[1, n]` sorted in a strictly increasing order. Apply the following algorithm on `arr`:

*   Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
*   Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.
*   Keep repeating the steps again, alternating left to right and right to left, until a single number remains.

Given the integer `n`, return _the last number that remains in_ `arr`.

**Example 1:**

**Input:** n = 9
**Output:** 6
**Explanation:**
arr = \[1, 2, 3, 4, 5, 6, 7, 8, 9\]
arr = \[2, 4, 6, 8\]
arr = \[2, 6\]
arr = \[6\]

**Example 2:**

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

**Constraints:**

*   `1 <= n <= 109`

## A solution in Java

```java
public int lastRemaining(int n) {
    boolean direction = true;
    int head = 1, remaining = n, step = 1;

    while (remaining > 1) {
        if (direction || remaining % 2 == 1) {
            head += step;
        }
        remaining /= 2;
        step *= 2;
        direction = !direction;
    }

    return head;
}
```
The algorithm starts with `head` pointing to the first element, and it will move `head` according to the direction flag and the current value of `remaining`. The `direction` flag alternates between `true` and `false` in each iteration, indicating whether we need to move forwards or backwards. The `remaining` variable represents the number of elements left in the list.

In each iteration, if the direction is forward (`true`) or the remaining elements are odd, we will increment `head` by the current `step`. Then, we update the remaining elements by dividing it by 2, as half elements are removed in each iteration, and the `step` doubles as the number of removed elements in the next round will also double. Finally, we toggle the `direction` flag, which means reversing the direction in which we move `head`.

At the end of the algorithm, when there is only one element remaining, the position of `head` will be the number that remains.

## A solution in C++

```cpp
int lastRemaining(int n) {
    bool direction = true;
    int head = 1, remaining = n, step = 1;

    while (remaining > 1) {
        if (direction || remaining % 2 == 1) {
            head += step;
        }
        remaining /= 2;
        step *= 2;
        direction = !direction;
    }

    return head;
}
```
The algorithm starts with `head` pointing to the first element, and it will move `head` according to the direction flag and the current value of `remaining`. The `direction` flag alternates between `true` and `false` in each iteration, indicating whether we need to move forwards or backwards. The `remaining` variable represents the number of elements left in the list.

In each iteration, if the direction is forward (`true`) or the remaining elements are odd, we will increment `head` by the current `step`. Then, we update the remaining elements by dividing it by 2, as half elements are removed in each iteration, and the `step` doubles as the number of removed elements in the next round will also double. Finally, we toggle the `direction` flag, which means reversing the direction in which we move `head`.

At the end of the algorithm, when there is only one element remaining, the position of `head` will be the number that remains.

## A solution in Python

```python
def last_remaining(n: int) -> int:
    direction = True
    head = 1
    remaining = n
    step = 1

    while remaining > 1:
        if direction or remaining % 2 == 1:
            head += step
        remaining //= 2
        step *= 2
        direction = not direction

    return head
```
The algorithm starts with `head` pointing to the first element, and it will move `head` according to the direction flag and the current value of `remaining`. The `direction` flag alternates between `true` and `false` in each iteration, indicating whether we need to move forwards or backwards. The `remaining` variable represents the number of elements left in the list.

In each iteration, if the direction is forward (`true`) or the remaining elements are odd, we will increment `head` by the current `step`. Then, we update the remaining elements by dividing it by 2, as half elements are removed in each iteration, and the `step` doubles as the number of removed elements in the next round will also double. Finally, we toggle the `direction` flag, which means reversing the direction in which we move `head`.

At the end of the algorithm, when there is only one element remaining, the position of `head` will be the number that remains.

## A solution in Javascript

```javascript
function lastRemaining(n) {
    let direction = true;
    let head = 1, remaining = n, step = 1;

    while (remaining > 1) {
        if (direction || remaining % 2 === 1) {
            head += step;
        }
        remaining = Math.floor(remaining / 2);
        step *= 2;
        direction = !direction;
    }

    return head;
}
```
The algorithm starts with `head` pointing to the first element, and it will move `head` according to the direction flag and the current value of `remaining`. The `direction` flag alternates between `true` and `false` in each iteration, indicating whether we need to move forwards or backwards. The `remaining` variable represents the number of elements left in the list.

In each iteration, if the direction is forward (`true`) or the remaining elements are odd, we will increment `head` by the current `step`. Then, we update the remaining elements by dividing it by 2, as half elements are removed in each iteration, and the `step` doubles as the number of removed elements in the next round will also double. Finally, we toggle the `direction` flag, which means reversing the direction in which we move `head`.

At the end of the algorithm, when there is only one element remaining, the position of `head` will be the number that remains.


# Perfect Rectangle

- slug: perfect-rectangle
- difficulty: Hard

Given an array `rectangles` where `rectangles[i] = [xi, yi, ai, bi]` represents an axis-aligned rectangle. The bottom-left point of the rectangle is `(xi, yi)` and the top-right point of it is `(ai, bi)`.

Return `true` _if all the rectangles together form an exact cover of a rectangular region_.

**Example 1:**

**Input:** rectangles = \[\[1,1,3,3\],\[3,1,4,2\],\[3,2,4,4\],\[1,3,2,4\],\[2,3,3,4\]\]
**Output:** true
**Explanation:** All 5 rectangles together form an exact cover of a rectangular region.

**Example 2:**

**Input:** rectangles = \[\[1,1,2,3\],\[1,3,2,4\],\[3,1,4,2\],\[3,2,4,4\]\]
**Output:** false
**Explanation:** Because there is a gap between the two rectangular regions.

**Example 3:**

**Input:** rectangles = \[\[1,1,3,3\],\[3,1,4,2\],\[1,3,2,4\],\[2,2,4,4\]\]
**Output:** false
**Explanation:** Because two of the rectangles overlap with each other.

**Constraints:**

*   `1 <= rectangles.length <= 2 * 104`
*   `rectangles[i].length == 4`
*   `-105 <= xi, yi, ai, bi <= 105`

## A solution in Java

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

public class RectCover {
    public boolean isRectangleCover(int[][] rectangles) {
        int area = 0;
        Set<Point> points = new HashSet<>();
        int lx = Integer.MAX_VALUE, ly = Integer.MAX_VALUE, rx = Integer.MIN_VALUE, ry = Integer.MIN_VALUE;

        for (int[] rect : rectangles) {
            lx = Math.min(lx, rect[0]);
            ly = Math.min(ly, rect[1]);
            rx = Math.max(rx, rect[2]);
            ry = Math.max(ry, rect[3]);

            area += (rect[2] - rect[0]) * (rect[3] - rect[1]);

            Point p1 = new Point(rect[0], rect[1]);
            Point p2 = new Point(rect[0], rect[3]);
            Point p3 = new Point(rect[2], rect[1]);
            Point p4 = new Point(rect[2], rect[3]);

            if (!points.remove(p1)) points.add(p1);
            if (!points.remove(p2)) points.add(p2);
            if (!points.remove(p3)) points.add(p3);
            if (!points.remove(p4)) points.add(p4);
        }

        if (points.contains(new Point(lx, ly)) && points.contains(new Point(lx, ry)) &&
            points.contains(new Point(rx, ly)) && points.contains(new Point(rx, ry)) &&
            points.size() == 4)
            return area == (rx - lx) * (ry - ly);

        return false;
    }
}
```
1. Initialize the area to 0 and create a set to store the points.
2. Initialize lx, ly, rx, and ry to min and max values.
3. Iterate through the input rectangles.
4. Update lx, ly, rx, and ry with the min and the max values found in the rectangles.
5. Calculate the area of the current rectangle and add it to the total area.
6. Compute 4 points for each rectangle and store them in the set using the following conditions:
   - If a point exists in the set, remove it.
   - If a point doesn't exist in the set, add it.
7. Check if the set contains the four corner points of the large rectangle (lx, ly), (lx, ry), (rx, ly), (rx, ry) and if the size of the set is 4.
8. Return true if the area of the large rectangle equals the total area calculated in step 5, and the conditions in step 7 are met; otherwise, return false.

## A solution in C++

```cpp
#include <vector>
#include <set>

bool isRectangleCover(std::vector<std::vector<int>>& rectangles) {
    int area = 0;
    std::set<std::pair<int, int>> points;
    int lx = INT_MAX, ly = INT_MAX, rx = INT_MIN, ry = INT_MIN;

    for (auto& rect : rectangles) {
        lx = std::min(lx, rect[0]);
        ly = std::min(ly, rect[1]);
        rx = std::max(rx, rect[2]);
        ry = std::max(ry, rect[3]);

        area += (rect[2] - rect[0]) * (rect[3] - rect[1]);

        std::pair<int, int> p1(rect[0], rect[1]);
        std::pair<int, int> p2(rect[0], rect[3]);
        std::pair<int, int> p3(rect[2], rect[1]);
        std::pair<int, int> p4(rect[2], rect[3]);

        if (!points.erase(p1)) points.insert(p1);
        if (!points.erase(p2)) points.insert(p2);
        if (!points.erase(p3)) points.insert(p3);
        if (!points.erase(p4)) points.insert(p4);
    }

    if (points.count({lx, ly}) && points.count({lx, ry}) &&
        points.count({rx, ly}) && points.count({rx, ry}) &&
        points.size() == 4)
        return area == (rx - lx) * (ry - ly);

    return false;
}
```
1. Initialize the area to 0 and create a set to store the points.
2. Initialize lx, ly, rx, and ry to min and max values.
3. Iterate through the input rectangles.
4. Update lx, ly, rx, and ry with the min and the max values found in the rectangles.
5. Calculate the area of the current rectangle and add it to the total area.
6. Compute 4 points for each rectangle and store them in the set using the following conditions:
   - If a point exists in the set, remove it.
   - If a point doesn't exist in the set, add it.
7. Check if the set contains the four corner points of the large rectangle (lx, ly), (lx, ry), (rx, ly), (rx, ry) and if the size of the set is 4.
8. Return true if the area of the large rectangle equals the total area calculated in step 5, and the conditions in step 7 are met; otherwise, return false.

## A solution in Python

```python
def isRectangleCover(rectangles):
    area = 0
    points = set()
    lx, ly, rx, ry = float('inf'), float('inf'), float('-inf'), float('-inf')

    for rect in rectangles:
        lx, ly = min(lx, rect[0]), min(ly, rect[1])
        rx, ry = max(rx, rect[2]), max(ry, rect[3])

        area += (rect[2] - rect[0]) * (rect[3] - rect[1])

        p1, p2, p3, p4 = (rect[0], rect[1]), (rect[0], rect[3]), (rect[2], rect[1]), (rect[2], rect[3])

        points ^= {p1, p2, p3, p4}

    return len(points) == 4 and area == (rx - lx) * (ry - ly) and (lx, ly) in points and \
           (lx, ry) in points and (rx, ly) in points and (rx, ry) in points
```
1. Initialize the area to 0 and create a set to store the points.
2. Initialize lx, ly, rx, and ry to min and max values.
3. Iterate through the input rectangles.
4. Update lx, ly, rx, and ry with the min and the max values found in the rectangles.
5. Calculate the area of the current rectangle and add it to the total area.
6. Compute 4 points for each rectangle and store them in the set using the following conditions:
   - If a point exists in the set, remove it.
   - If a point doesn't exist in the set, add it.
7. Check if the set contains the four corner points of the large rectangle (lx, ly), (lx, ry), (rx, ly), (rx, ry) and if the size of the set is 4.
8. Return true if the area of the large rectangle equals the total area calculated in step 5, and the conditions in step 7 are met; otherwise, return false.

## A solution in Javascript

```javascript
function isRectangleCover(rectangles) {
    let area = 0;
    let points = new Set();
    let lx = Infinity, ly = Infinity, rx = -Infinity, ry = -Infinity;

    for (let rect of rectangles) {
        lx = Math.min(lx, rect[0]);
        ly = Math.min(ly, rect[1]);
        rx = Math.max(rx, rect[2]);
        ry = Math.max(ry, rect[3]);

        area += (rect[2] - rect[0]) * (rect[3] - rect[1]);

        let p1 = rect[0] + "," + rect[1];
        let p2 = rect[0] + "," + rect[3];
        let p3 = rect[2] + "," + rect[1];
        let p4 = rect[2] + "," + rect[3];

        if (points.has(p1)) points.delete(p1);
        else points.add(p1);
        if (points.has(p2)) points.delete(p2);
        else points.add(p2);
        if (points.has(p3)) points.delete(p3);
        else points.add(p3);
        if (points.has(p4)) points.delete(p4);
        else points.add(p4);
    }

    return points.size === 4 &&
           points.has(lx + "," + ly) && points.has(lx + "," + ry) &&
           points.has(rx + "," + ly) && points.has(rx + "," + ry) &&
           area === (rx - lx) * (ry - ly);
}
```
1. Initialize the area to 0 and create a set to store the points.
2. Initialize lx, ly, rx, and ry to min and max values.
3. Iterate through the input rectangles.
4. Update lx, ly, rx, and ry with the min and the max values found in the rectangles.
5. Calculate the area of the current rectangle and add it to the total area.
6. Compute 4 points for each rectangle and store them in the set using the following conditions:
   - If a point exists in the set, remove it.
   - If a point doesn't exist in the set, add it.
7. Check if the set contains the four corner points of the large rectangle (lx, ly), (lx, ry), (rx, ly), (rx, ry) and if the size of the set is 4.
8. Return true if the area of the large rectangle equals the total area calculated in step 5, and the conditions in step 7 are met; otherwise, return false.


# Is Subsequence

- slug: is-subsequence
- difficulty: Easy

Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.

A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).

**Example 1:**

**Input:** s = "abc", t = "ahbgdc"
**Output:** true

**Example 2:**

**Input:** s = "axc", t = "ahbgdc"
**Output:** false

**Constraints:**

*   `0 <= s.length <= 100`
*   `0 <= t.length <= 104`
*   `s` and `t` consist only of lowercase English letters.

**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?

## A solution in Java

```java
boolean isSubsequence(String s, String t) {
    int si = 0, ti = 0;

    while (si < s.length() && ti < t.length()) {
        if (s.charAt(si) == t.charAt(ti))
            si++;
        ti++;
    }

    return si == s.length();
}
```
We use two pointers to iterate through the strings `s` and `t`. The `si` pointer will be used to iterate through the string `s` and the `ti` pointer will be used for `t`.

At each iteration of the loop, if the character at the current position of both strings is the same, we increment the `si` pointer. We will always increment the `ti` pointer.

The loop will continue until we have checked all the characters in the `s` string or until we have checked all the characters in the `t` string. If the `si` pointer is equal to the length of the `s` string, it means we've found all the characters in the `t` string and the function returns true. Otherwise, it returns false.

This algorithm runs with a time complexity of O(max(n, m)) where n and m are the lengths of the strings s and t, respectively.

## A solution in C++

```cpp
bool isSubsequence(std::string s, std::string t) {
    int si = 0, ti = 0;

    while (si < s.size() && ti < t.size()) {
        if (s[si] == t[ti])
            si++;
        ti++;
    }

    return si == s.size();
}
```
We use two pointers to iterate through the strings `s` and `t`. The `si` pointer will be used to iterate through the string `s` and the `ti` pointer will be used for `t`.

At each iteration of the loop, if the character at the current position of both strings is the same, we increment the `si` pointer. We will always increment the `ti` pointer.

The loop will continue until we have checked all the characters in the `s` string or until we have checked all the characters in the `t` string. If the `si` pointer is equal to the length of the `s` string, it means we've found all the characters in the `t` string and the function returns true. Otherwise, it returns false.

This algorithm runs with a time complexity of O(max(n, m)) where n and m are the lengths of the strings s and t, respectively.

## A solution in Python

```python
def is_subsequence(s, t):
    si, ti = 0, 0

    while si < len(s) and ti < len(t):
        if s[si] == t[ti]:
            si += 1
        ti += 1

    return si == len(s)
```
We use two pointers to iterate through the strings `s` and `t`. The `si` pointer will be used to iterate through the string `s` and the `ti` pointer will be used for `t`.

At each iteration of the loop, if the character at the current position of both strings is the same, we increment the `si` pointer. We will always increment the `ti` pointer.

The loop will continue until we have checked all the characters in the `s` string or until we have checked all the characters in the `t` string. If the `si` pointer is equal to the length of the `s` string, it means we've found all the characters in the `t` string and the function returns true. Otherwise, it returns false.

This algorithm runs with a time complexity of O(max(n, m)) where n and m are the lengths of the strings s and t, respectively.

## A solution in Javascript

```javascript
function isSubsequence(s, t) {
    let si = 0, ti = 0;

    while (si < s.length && ti < t.length) {
        if (s[si] === t[ti])
            si++;
        ti++;
    }

    return si === s.length;
}
```
We use two pointers to iterate through the strings `s` and `t`. The `si` pointer will be used to iterate through the string `s` and the `ti` pointer will be used for `t`.

At each iteration of the loop, if the character at the current position of both strings is the same, we increment the `si` pointer. We will always increment the `ti` pointer.

The loop will continue until we have checked all the characters in the `s` string or until we have checked all the characters in the `t` string. If the `si` pointer is equal to the length of the `s` string, it means we've found all the characters in the `t` string and the function returns true. Otherwise, it returns false.

This algorithm runs with a time complexity of O(max(n, m)) where n and m are the lengths of the strings s and t, respectively.


# UTF-8 Validation

- slug: utf-8-validation
- difficulty: Medium

Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).

A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules:

1.  For a **1-byte** character, the first bit is a `0`, followed by its Unicode code.
2.  For an **n-bytes** character, the first `n` bits are all one's, the `n + 1` bit is `0`, followed by `n - 1` bytes with the most significant `2` bits being `10`.

This is how the UTF-8 encoding would work:

     Number of Bytes   |        UTF-8 Octet Sequence
                       |              (binary)
   --------------------+-----------------------------------------
            1          |   0xxxxxxx
            2          |   110xxxxx 10xxxxxx
            3          |   1110xxxx 10xxxxxx 10xxxxxx
            4          |   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

`x` denotes a bit in the binary form of a byte that may be either `0` or `1`.

**Note:** The input is an array of integers. Only the **least significant 8 bits** of each integer is used to store the data. This means each integer represents only 1 byte of data.

**Example 1:**

**Input:** data = \[197,130,1\]
**Output:** true
**Explanation:** data represents the octet sequence: 11000101 10000010 00000001.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.

**Example 2:**

**Input:** data = \[235,140,4\]
**Output:** false
**Explanation:** data represented the octet sequence: 11101011 10001100 00000100.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.

**Constraints:**

*   `1 <= data.length <= 2 * 104`
*   `0 <= data[i] <= 255`

## A solution in Java

```java
public boolean validUtf8(int[] data) {
    int count = 0;
    for (int byteValue : data) {
        if (count == 0) {
            if ((byteValue >> 5) == 0b110) count = 1;
            else if ((byteValue >> 4) == 0b1110) count = 2;
            else if ((byteValue >> 3) == 0b11110) count = 3;
            else if ((byteValue >> 7) == 1) return false;
        } else {
            if ((byteValue >> 6) != 0b10) return false;
            count--;
        }
    }
    return count == 0;
}
```
We iterate through each byte in the given data array. If we are not currently processing a multi-byte character (count = 0), we check if it's a 1-byte, 2-byte, 3-byte, or 4-byte character encodings, and update the `count` accordingly. For 1-byte characters, we just check if the first bit is 0.

In case the current byte is a part of multi-byte character (count > 0), we check whether it is a valid continuation byte by checking if its two most significant bits are `10`. If it's not a valid continuation byte, return `false`.

Finally, return `true` if the `count` is 0 at the end of the iteration, i.e., there are no unfinished multi-byte sequences.

## A solution in C++

```cpp
bool validUtf8(vector<int>& data) {
    int count = 0;
    for (int byte : data) {
        if (count == 0) {
            if ((byte >> 5) == 0b110) count = 1;
            else if ((byte >> 4) == 0b1110) count = 2;
            else if ((byte >> 3) == 0b11110) count = 3;
            else if ((byte >> 7)) return false;
        } else {
            if ((byte >> 6) != 0b10) return false;
            count--;
        }
    }
    return count == 0;
}
```
We iterate through each byte in the given data array. If we are not currently processing a multi-byte character (count = 0), we check if it's a 1-byte, 2-byte, 3-byte, or 4-byte character encodings, and update the `count` accordingly. For 1-byte characters, we just check if the first bit is 0.

In case the current byte is a part of multi-byte character (count > 0), we check whether it is a valid continuation byte by checking if its two most significant bits are `10`. If it's not a valid continuation byte, return `false`.

Finally, return `true` if the `count` is 0 at the end of the iteration, i.e., there are no unfinished multi-byte sequences.

## A solution in Python

```python
def validUtf8(data):
    count = 0
    for byte in data:
        if count == 0:
            if byte >> 5 == 0b110:
                count = 1
            elif byte >> 4 == 0b1110:
                count = 2
            elif byte >> 3 == 0b11110:
                count = 3
            elif byte >> 7:
                return False
        else:
            if byte >> 6 != 0b10:
                return False
            count -= 1
    return count == 0
```
We iterate through each byte in the given data array. If we are not currently processing a multi-byte character (count = 0), we check if it's a 1-byte, 2-byte, 3-byte, or 4-byte character encodings, and update the `count` accordingly. For 1-byte characters, we just check if the first bit is 0.

In case the current byte is a part of multi-byte character (count > 0), we check whether it is a valid continuation byte by checking if its two most significant bits are `10`. If it's not a valid continuation byte, return `false`.

Finally, return `true` if the `count` is 0 at the end of the iteration, i.e., there are no unfinished multi-byte sequences.

## A solution in Javascript

```javascript
function validUtf8(data) {
    let count = 0;
    for (let byte of data) {
        if (count === 0) {
            if (byte >> 5 === 0b110) count = 1;
            else if (byte >> 4 === 0b1110) count = 2;
            else if (byte >> 3 === 0b11110) count = 3;
            else if (byte >> 7) return false;
        } else {
            if (byte >> 6 !== 0b10) return false;
            count--;
        }
    }
    return count === 0;
}
```
We iterate through each byte in the given data array. If we are not currently processing a multi-byte character (count = 0), we check if it's a 1-byte, 2-byte, 3-byte, or 4-byte character encodings, and update the `count` accordingly. For 1-byte characters, we just check if the first bit is 0.

In case the current byte is a part of multi-byte character (count > 0), we check whether it is a valid continuation byte by checking if its two most significant bits are `10`. If it's not a valid continuation byte, return `false`.

Finally, return `true` if the `count` is 0 at the end of the iteration, i.e., there are no unfinished multi-byte sequences.


# Decode String

- slug: decode-string
- difficulty: Medium

Given an encoded string, return its decoded string.

The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.

You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`.

The test cases are generated so that the length of the output will never exceed `105`.

**Example 1:**

**Input:** s =  "3\[a\]2\[bc\] "
**Output:**  "aaabcbc "

**Example 2:**

**Input:** s =  "3\[a2\[c\]\] "
**Output:**  "accaccacc "

**Example 3:**

**Input:** s =  "2\[abc\]3\[cd\]ef "
**Output:**  "abcabccdcdcdef "

**Constraints:**

*   `1 <= s.length <= 30`
*   `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
*   `s` is guaranteed to be **a valid** input.
*   All the integers in `s` are in the range `[1, 300]`.

## A solution in Java

```java
import java.util.*;

class Solution {
    public String decodeString(String s) {
        Stack<Integer> counts = new Stack<>();
        Stack<String> results = new Stack<>();
        String current = "";
        int ptr = 0;

        while (ptr < s.length()) {
            if (Character.isDigit(s.charAt(ptr))) {
                int count = 0;
                while (Character.isDigit(s.charAt(ptr))) {
                    count = count * 10 + (s.charAt(ptr) - '0');
                    ptr++;
                }
                counts.push(count);
            } else if (s.charAt(ptr) == '[') {
                results.push(current);
                current = "";
                ptr++;
            } else if (s.charAt(ptr) == ']') {
                String prev = results.pop();
                int count = counts.pop();
                for (int i = 0; i < count; i++) {
                    prev += current;
                }
                current = prev;
                ptr++;
            } else {
                current += s.charAt(ptr);
                ptr++;
            }
        }

        return current;
    }
}
```
1. Initialize two stacks `counts` and `results`, a pointer `ptr`, and a `current` string.
2. Loop through the input string `s`.
3. If the current character is a digit, calculate the number and push it onto the `counts` stack.
4. If the current character is an opening bracket `[`, push the `current` string into the `results` stack and reset the `current` string.
5. If the current character is a closing bracket `]`, pop the top strings from the `results` stack and multiply the `current` string with the top count from the `counts` stack. Update the `current` string.
6. If the current character is a letter, add it to the `current` string.
7. After looping through `s`, return the `current` string, which is now the decoded version of the input string.

## A solution in C++

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

std::string decodeString(const std::string &s) {
    std::stack<int> counts;
    std::stack<std::string> results;
    std::string current;
    int ptr = 0;

    while (ptr < s.size()) {
        if (isdigit(s[ptr])) {
            int count = 0;
            while (isdigit(s[ptr])) {
                count = count * 10 + (s[ptr] - '0');
                ptr++;
            }
            counts.push(count);
        } else if (s[ptr] == '[') {
            results.push(current);
            current = "";
            ptr++;
        } else if (s[ptr] == ']') {
            std::string prev = results.top();
            results.pop();
            int count = counts.top();
            counts.pop();
            for (int i = 0; i < count; i++) {
                prev += current;
            }
            current = prev;
            ptr++;
        } else {
            current += s[ptr];
            ptr++;
        }
    }

    return current;
}
```
1. Initialize two stacks `counts` and `results`, a pointer `ptr`, and a `current` string.
2. Loop through the input string `s`.
3. If the current character is a digit, calculate the number and push it onto the `counts` stack.
4. If the current character is an opening bracket `[`, push the `current` string into the `results` stack and reset the `current` string.
5. If the current character is a closing bracket `]`, pop the top strings from the `results` stack and multiply the `current` string with the top count from the `counts` stack. Update the `current` string.
6. If the current character is a letter, add it to the `current` string.
7. After looping through `s`, return the `current` string, which is now the decoded version of the input string.

## A solution in Python

```python
def decodeString(s):
    counts = []
    results = []
    current = ""
    ptr = 0

    while ptr < len(s):
        if s[ptr].isdigit():
            count = 0
            while s[ptr].isdigit():
                count = count * 10 + int(s[ptr])
                ptr += 1
            counts.append(count)
        elif s[ptr] == '[':
            results.append(current)
            current = ""
            ptr += 1
        elif s[ptr] == ']':
            prev = results.pop()
            count = counts.pop()
            current = prev + current * count
            ptr += 1
        else:
            current += s[ptr]
            ptr += 1

    return current
```
1. Initialize two stacks `counts` and `results`, a pointer `ptr`, and a `current` string.
2. Loop through the input string `s`.
3. If the current character is a digit, calculate the number and push it onto the `counts` stack.
4. If the current character is an opening bracket `[`, push the `current` string into the `results` stack and reset the `current` string.
5. If the current character is a closing bracket `]`, pop the top strings from the `results` stack and multiply the `current` string with the top count from the `counts` stack. Update the `current` string.
6. If the current character is a letter, add it to the `current` string.
7. After looping through `s`, return the `current` string, which is now the decoded version of the input string.

## A solution in Javascript

```javascript
function decodeString(s) {
    const counts = [];
    const results = [];
    let current = "";
    let ptr = 0;

    while (ptr < s.length) {
        if (s[ptr].match(/\d/)) {
            let count = 0;
            while (s[ptr].match(/\d/)) {
                count = count * 10 + parseInt(s[ptr]);
                ptr++;
            }
            counts.push(count);
        } else if (s[ptr] === '[') {
            results.push(current);
            current = "";
            ptr++;
        } else if (s[ptr] === ']') {
            const prev = results.pop();
            const count = counts.pop();
            for (let i = 0; i < count; i++) {
                prev += current;
            }
            current = prev;
            ptr++;
        } else {
            current += s[ptr];
            ptr++;
        }
    }

    return current;
}
```
1. Initialize two stacks `counts` and `results`, a pointer `ptr`, and a `current` string.
2. Loop through the input string `s`.
3. If the current character is a digit, calculate the number and push it onto the `counts` stack.
4. If the current character is an opening bracket `[`, push the `current` string into the `results` stack and reset the `current` string.
5. If the current character is a closing bracket `]`, pop the top strings from the `results` stack and multiply the `current` string with the top count from the `counts` stack. Update the `current` string.
6. If the current character is a letter, add it to the `current` string.
7. After looping through `s`, return the `current` string, which is now the decoded version of the input string.


# Longest Substring with At Least K Repeating Characters

- slug: longest-substring-with-at-least-k-repeating-characters
- difficulty: Medium

Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`.

**Example 1:**

**Input:** s =  "aaabb ", k = 3
**Output:** 3
**Explanation:** The longest substring is  "aaa ", as 'a' is repeated 3 times.

**Example 2:**

**Input:** s =  "ababbc ", k = 2
**Output:** 5
**Explanation:** The longest substring is  "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times.

**Constraints:**

*   `1 <= s.length <= 104`
*   `s` consists of only lowercase English letters.
*   `1 <= k <= 105`

## A solution in Java

```java
import java.util.*;

public int longestSubstring(String s, int k) {
    if (s == null || s.length() == 0 || k <= 0) return 0;

    Map<Character, Integer> charCount = new HashMap<>();
    for (char ch : s.toCharArray())
        charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);

    for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
        if (entry.getValue() < k) {
            int res = 0;
            for (String str : s.split(Character.toString(entry.getKey())))
                res = Math.max(res, longestSubstring(str, k));
            return res;
        }
    }
    return s.length();
}
```
The algorithm starts by counting the frequency of each character in the input string `s`. If the count of any character is less than `k`, then that character cannot be part of any substring with characters having a frequency greater than or equal to `k`. Therefore, we split the input string around such characters and recursively apply the same logic on each substring. The longest substring's length across different recursive calls is returned.

## A solution in C++

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

int longestSubstring(const std::string& s, int k) {
    if (s.empty() || k <= 0) return 0;

    std::unordered_map<char, int> char_count;
    for (char ch : s)
        char_count[ch]++;

    for (const auto& item : char_count) {
        if (item.second < k) {
            int res = 0;
            for (const std::string& str : split(s, item.first))
                res = std::max(res, longestSubstring(str, k));
            return res;
        }
    }
    return s.length();
}

std::vector<std::string> split(const std::string& s, char delimiter) {
    std::vector<std::string> subs;
    size_t start = 0;
    size_t end = s.find(delimiter);
    while (end != std::string::npos) {
        subs.push_back(s.substr(start, end - start));
        start = end + 1;
        end = s.find(delimiter, start);
    }
    subs.push_back(s.substr(start));
    return subs;
}
```
The algorithm starts by counting the frequency of each character in the input string `s`. If the count of any character is less than `k`, then that character cannot be part of any substring with characters having a frequency greater than or equal to `k`. Therefore, we split the input string around such characters and recursively apply the same logic on each substring. The longest substring's length across different recursive calls is returned.

## A solution in Python

```python
def longestSubstring(s: str, k: int) -> int:
    if not s or k <= 0:
        return 0

    char_count = {}
    for ch in s:
        char_count[ch] = char_count.get(ch, 0) + 1

    for char, count in char_count.items():
        if count < k:
            return max(longestSubstring(sub_s, k) for sub_s in s.split(char))
    return len(s)
```
The algorithm starts by counting the frequency of each character in the input string `s`. If the count of any character is less than `k`, then that character cannot be part of any substring with characters having a frequency greater than or equal to `k`. Therefore, we split the input string around such characters and recursively apply the same logic on each substring. The longest substring's length across different recursive calls is returned.

## A solution in Javascript

```javascript
function longestSubstring(s, k) {
    if (!s || k <= 0) return 0;

    const charCount = {};
    for (const ch of s)
        charCount[ch] = (charCount[ch] || 0) + 1;

    for (const key in charCount) {
        if (charCount[key] < k) {
            let res = 0;
            for (const subStr of s.split(key))
                res = Math.max(res, longestSubstring(subStr, k));
            return res;
        }
    }
    return s.length;
}
```
The algorithm starts by counting the frequency of each character in the input string `s`. If the count of any character is less than `k`, then that character cannot be part of any substring with characters having a frequency greater than or equal to `k`. Therefore, we split the input string around such characters and recursively apply the same logic on each substring. The longest substring's length across different recursive calls is returned.


# Rotate Function

- slug: rotate-function
- difficulty: Medium

You are given an integer array `nums` of length `n`.

Assume `arrk` to be an array obtained by rotating `nums` by `k` positions clock-wise. We define the **rotation function** `F` on `nums` as follow:

*   `F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].`

Return _the maximum value of_ `F(0), F(1), ..., F(n-1)`.

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

**Example 1:**

**Input:** nums = \[4,3,2,6\]
**Output:** 26
**Explanation:**
F(0) = (0 \* 4) + (1 \* 3) + (2 \* 2) + (3 \* 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 \* 6) + (1 \* 4) + (2 \* 3) + (3 \* 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 \* 2) + (1 \* 6) + (2 \* 4) + (3 \* 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 \* 3) + (1 \* 2) + (2 \* 6) + (3 \* 4) = 0 + 2 + 12 + 12 = 26
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

**Example 2:**

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

**Constraints:**

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

## A solution in Java

```java
public int maxRotateFunction(int[] nums) {
    int n = nums.length;
    int total_sum = 0;
    int f = 0;

    for (int i = 0; i < n; i++) {
        total_sum += nums[i];
        f += i * nums[i];
    }

    int max_f = f;
    for (int i = 1; i < n; i++) {
        f += total_sum - (n * nums[n - i]);
        max_f = Math.max(max_f, f);
    }

    return max_f;
}
```
1. Calculate the total_sum of elements in the given array.
2. Calculate the initial value of the rotation function F(0) and assign it to f.
3. Initialize max_f with the value of f.
4. Iterate through the array with index i from 1 to n-1.
5. For each iteration, calculate the value of the rotation function F(i) by adding total_sum to the previous value of the rotation function and subtracting the product of n and nums[n - i]. Update f with the new value.
6. Compare the new value of f with max_f and update max_f with the maximum value.
7. Return max_f after finishing the loop.

## A solution in C++

```cpp
int maxRotateFunction(vector<int>& nums) {
    int n = nums.size();
    int total_sum = 0;
    int f = 0;

    for (int i = 0; i < n; i++) {
        total_sum += nums[i];
        f += i * nums[i];
    }

    int max_f = f;
    for (int i = 1; i < n; i++) {
        f += total_sum - n * nums[n - i];
        max_f = max(max_f, f);
    }

    return max_f;
}
```
1. Calculate the total_sum of elements in the given array.
2. Calculate the initial value of the rotation function F(0) and assign it to f.
3. Initialize max_f with the value of f.
4. Iterate through the array with index i from 1 to n-1.
5. For each iteration, calculate the value of the rotation function F(i) by adding total_sum to the previous value of the rotation function and subtracting the product of n and nums[n - i]. Update f with the new value.
6. Compare the new value of f with max_f and update max_f with the maximum value.
7. Return max_f after finishing the loop.

## A solution in Python

```python
def maxRotateFunction(nums):
    n = len(nums)
    total_sum = sum(nums)
    f = sum(i * num for i, num in enumerate(nums))

    max_f = f
    for i in range(1, n):
        f += total_sum - n * nums[-i]
        max_f = max(max_f, f)

    return max_f
```
1. Calculate the total_sum of elements in the given array.
2. Calculate the initial value of the rotation function F(0) and assign it to f.
3. Initialize max_f with the value of f.
4. Iterate through the array with index i from 1 to n-1.
5. For each iteration, calculate the value of the rotation function F(i) by adding total_sum to the previous value of the rotation function and subtracting the product of n and nums[n - i]. Update f with the new value.
6. Compare the new value of f with max_f and update max_f with the maximum value.
7. Return max_f after finishing the loop.

## A solution in Javascript

```javascript
function maxRotateFunction(nums) {
    let n = nums.length;
    let total_sum = nums.reduce((a, b) => a + b, 0);
    let f = nums.reduce((acc, val, i) => acc + i * val, 0);

    let max_f = f;
    for (let i = 1; i < n; i++) {
        f += total_sum - n * nums[n - i];
        max_f = Math.max(max_f, f);
    }

    return max_f;
}
```
1. Calculate the total_sum of elements in the given array.
2. Calculate the initial value of the rotation function F(0) and assign it to f.
3. Initialize max_f with the value of f.
4. Iterate through the array with index i from 1 to n-1.
5. For each iteration, calculate the value of the rotation function F(i) by adding total_sum to the previous value of the rotation function and subtracting the product of n and nums[n - i]. Update f with the new value.
6. Compare the new value of f with max_f and update max_f with the maximum value.
7. Return max_f after finishing the loop.


# Integer Replacement

- slug: integer-replacement
- difficulty: Medium

Given a positive integer `n`, you can apply one of the following operations:

1.  If `n` is even, replace `n` with `n / 2`.
2.  If `n` is odd, replace `n` with either `n + 1` or `n - 1`.

Return _the minimum number of operations needed for_ `n` _to become_ `1`.

**Example 1:**

**Input:** n = 8
**Output:** 3
**Explanation:** 8 -> 4 -> 2 -> 1

**Example 2:**

**Input:** n = 7
**Output:** 4
**Explanation:** 7 -> 8 -> 4 -> 2 -> 1
or 7 -> 6 -> 3 -> 2 -> 1

**Example 3:**

**Input:** n = 4
**Output:** 2

**Constraints:**

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

## A solution in Java

```java
int minOperations(int n) {
    int steps = 0;
    while(n > 1) {
        n = (n % 2 == 0) ? n / 2 : n - 1;
        steps++;
    }
    return steps;
}
```
The algorithm to calculate the minimum number of operations needed for n to become 1 is straightforward. We initialize a variable `steps` to 0 to keep track of the number of operations performed. In a loop, we iterate until n becomes 1.

In each iteration of the loop, we check if n is an even number (n % 2 == 0). If it is, we divide n by 2; otherwise, we subtract 1 from n. We increase the count of `steps` by 1 in each iteration.

Finally, we return the total number of `steps` when the loop terminates (when n becomes 1).

## A solution in C++

```cpp
int minOperations(int n) {
    int steps = 0;
    while(n > 1) {
        n = (n % 2 == 0) ? n / 2 : n - 1;
        steps++;
    }
    return steps;
}
```
The algorithm to calculate the minimum number of operations needed for n to become 1 is straightforward. We initialize a variable `steps` to 0 to keep track of the number of operations performed. In a loop, we iterate until n becomes 1.

In each iteration of the loop, we check if n is an even number (n % 2 == 0). If it is, we divide n by 2; otherwise, we subtract 1 from n. We increase the count of `steps` by 1 in each iteration.

Finally, we return the total number of `steps` when the loop terminates (when n becomes 1).

## A solution in Python

```python
def min_operations(n):
    steps = 0
    while n > 1:
        n = n // 2 if n % 2 == 0 else n - 1
        steps += 1
    return steps
```
The algorithm to calculate the minimum number of operations needed for n to become 1 is straightforward. We initialize a variable `steps` to 0 to keep track of the number of operations performed. In a loop, we iterate until n becomes 1.

In each iteration of the loop, we check if n is an even number (n % 2 == 0). If it is, we divide n by 2; otherwise, we subtract 1 from n. We increase the count of `steps` by 1 in each iteration.

Finally, we return the total number of `steps` when the loop terminates (when n becomes 1).

## A solution in Javascript

```javascript
function minOperations(n) {
    let steps = 0;
    while(n > 1) {
        n = (n % 2 === 0) ? n / 2 : n - 1;
        steps++;
    }
    return steps;
}
```
The algorithm to calculate the minimum number of operations needed for n to become 1 is straightforward. We initialize a variable `steps` to 0 to keep track of the number of operations performed. In a loop, we iterate until n becomes 1.

In each iteration of the loop, we check if n is an even number (n % 2 == 0). If it is, we divide n by 2; otherwise, we subtract 1 from n. We increase the count of `steps` by 1 in each iteration.

Finally, we return the total number of `steps` when the loop terminates (when n becomes 1).


# Random Pick Index

- slug: random-pick-index
- difficulty: Medium

Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array.

Implement the `Solution` class:

*   `Solution(int[] nums)` Initializes the object with the array `nums`.
*   `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid i's, then each index should have an equal probability of returning.

**Example 1:**

**Input**
\[ "Solution ",  "pick ",  "pick ",  "pick "\]
\[\[\[1, 2, 3, 3, 3\]\], \[3\], \[1\], \[3\]\]
**Output**
\[null, 4, 0, 2\]

**Explanation**
Solution solution = new Solution(\[1, 2, 3, 3, 3\]);
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(1); // It should return 0. Since in the array only nums\[0\] is equal to 1.
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.

**Constraints:**

*   `1 <= nums.length <= 2 * 104`
*   `-231 <= nums[i] <= 231 - 1`
*   `target` is an integer from `nums`.
*   At most `104` calls will be made to `pick`.

## A solution in Java

```java
import java.util.Random;

class Solution {
    int[] nums;
    Random rand;

    public Solution(int[] nums) {
        this.nums = nums;
        this.rand = new Random();
    }

    public int pick(int target) {
        int count = 0, res = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                count++;
                if (rand.nextInt(count) == 0) {
                    res = i;
                }
            }
        }
        return res;
    }
}
```
The algorithm iterates through the input array and whenever it finds the target element, it increments the count variable. It then generates a random number in the range `[0, count - 1]`. If the random number is 0, set the result to the current index. Since the random generator function may generate 0 multiple times during the iteration, this makes sure that the final result is randomly picked among all occurrences of the target.

At the end of the loop, the variable `res` contains the randomly picked index of the target value. The time complexity of this algorithm is O(n) and space complexity is O(1).

## A solution in C++

```cpp
#include <vector>
#include <cstdlib>

class Solution {
public:
    std::vector<int> nums;

    Solution(std::vector<int>& nums) {
        this->nums = nums;
    }

    int pick(int target) {
        int count = 0, res = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == target) {
                count++;
                if (std::rand() % count == 0) {
                    res = i;
                }
            }
        }
        return res;
    }
};
```
The algorithm iterates through the input array and whenever it finds the target element, it increments the count variable. It then generates a random number in the range `[0, count - 1]`. If the random number is 0, set the result to the current index. Since the random generator function may generate 0 multiple times during the iteration, this makes sure that the final result is randomly picked among all occurrences of the target.

At the end of the loop, the variable `res` contains the randomly picked index of the target value. The time complexity of this algorithm is O(n) and space complexity is O(1).

## A solution in Python

```python
import random

class Solution:

    def __init__(self, nums):
        self.nums = nums

    def pick(self, target):
        count, res = 0, 0
        for i, num in enumerate(self.nums):
            if num == target:
                count += 1
                if random.randint(0, count - 1) == 0:
                    res = i
        return res
```
The algorithm iterates through the input array and whenever it finds the target element, it increments the count variable. It then generates a random number in the range `[0, count - 1]`. If the random number is 0, set the result to the current index. Since the random generator function may generate 0 multiple times during the iteration, this makes sure that the final result is randomly picked among all occurrences of the target.

At the end of the loop, the variable `res` contains the randomly picked index of the target value. The time complexity of this algorithm is O(n) and space complexity is O(1).

## A solution in Javascript

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

    pick(target) {
        let count = 0, res = 0;
        for (let i = 0; i < this.nums.length; i++) {
            if (this.nums[i] === target) {
                count++;
                if (Math.floor(Math.random() * count) === 0) {
                    res = i;
                }
            }
        }
        return res;
    }
}
```
The algorithm iterates through the input array and whenever it finds the target element, it increments the count variable. It then generates a random number in the range `[0, count - 1]`. If the random number is 0, set the result to the current index. Since the random generator function may generate 0 multiple times during the iteration, this makes sure that the final result is randomly picked among all occurrences of the target.

At the end of the loop, the variable `res` contains the randomly picked index of the target value. The time complexity of this algorithm is O(n) and space complexity is O(1).


# Evaluate Division

- slug: evaluate-division
- difficulty: Medium

You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.

You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.

Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.

**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.

**Example 1:**

**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]

**Example 2:**

**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]

**Example 3:**

**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]

**Constraints:**

*   `1 <= equations.length <= 20`
*   `equations[i].length == 2`
*   `1 <= Ai.length, Bi.length <= 5`
*   `values.length == equations.length`
*   `0.0 < values[i] <= 20.0`
*   `1 <= queries.length <= 20`
*   `queries[i].length == 2`
*   `1 <= Cj.length, Dj.length <= 5`
*   `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.

## A solution in Java

```java
import java.util.*;

public class Solution {
    public double dfs(String s1, String s2, Map<String, List<Pair<String, Double>>> graph) {
        if (!graph.containsKey(s1) || !graph.containsKey(s2)) return -1.0;
        if (s1.equals(s2)) return 1.0;

        for (Pair<String, Double> p : graph.get(s1)) {
            double temp = dfs(p.getKey(), s2, graph);
            if (temp > 0) return p.getValue() * temp;
        }
        return -1.0;
    }

    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        Map<String, List<Pair<String, Double>>> graph = new HashMap<>();
        for (int i = 0; i < equations.size(); i++) {
            String s1 = equations.get(i).get(0);
            String s2 = equations.get(i).get(1);

            if (!graph.containsKey(s1)) graph.put(s1, new ArrayList<>());
            if (!graph.containsKey(s2)) graph.put(s2, new ArrayList<>());

            graph.get(s1).add(new Pair<>(s2, values[i]));
            graph.get(s2).add(new Pair<>(s1, 1 / values[i]));
        }

        double[] ans = new double[queries.size()];
        for (int i = 0; i < queries.size(); i++) {
            ans[i] = dfs(queries.get(i).get(0), queries.get(i).get(1), graph);
        }
        return ans;
    }
}
```
First, we create an adjacency list `graph` to represent the relationship between variables where `graph[A].push({B, k})` for equation `A / B = k`. In each query, we try to find the path from `Cj` to `Dj` using a Depth-First Search (DFS) algorithm. In case the path exists, we return the value of `Cj / Dj`. If there is no path, return -1.0.

1. Create an empty graph (implemented as a hashmap) to store the variable pairs and values.
2. Iterate through the equations and values arrays, adding an edge between each Ai and Bi with its corresponding value to the graph.
3. Define a helper function (DFS) for traversing the graph and calculating the answer for a given query.
4. Iterate through the queries and apply the DFS function to find the answers. Save the results in an array and return it.

The time complexity of this algorithm is O(N * P) where N is the number of equations and P is the number of queries. This is because for each query, we may need to visit all the nodes in our graph. The space complexity is O(N) which also corresponds to the size of the graph.

## A solution in C++

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

using namespace std;

double dfs(const string& s1, const string& s2, unordered_map<string, vector<pair<string, double>>>& graph) {
    if (!graph.count(s1) || !graph.count(s2)) return -1.0;
    if (s1 == s2) return 1.0;

    for (auto& p : graph[s1]) {
        double temp = dfs(p.first, s2, graph);
        if (temp > 0) return p.second * temp;
    }
    return -1.0;
}

vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
    unordered_map<string, vector<pair<string, double>>> graph;
    for (int i = 0; i < equations.size(); i++) {
        graph[equations[i][0]].push_back({equations[i][1], values[i]});
        graph[equations[i][1]].push_back({equations[i][0], 1 / values[i]});
    }

    vector<double> ans;
    for (const auto& q : queries) {
        ans.push_back(dfs(q[0], q[1], graph));
    }
    return ans;
}
```
First, we create an adjacency list `graph` to represent the relationship between variables where `graph[A].push({B, k})` for equation `A / B = k`. In each query, we try to find the path from `Cj` to `Dj` using a Depth-First Search (DFS) algorithm. In case the path exists, we return the value of `Cj / Dj`. If there is no path, return -1.0.

1. Create an empty graph (implemented as a hashmap) to store the variable pairs and values.
2. Iterate through the equations and values arrays, adding an edge between each Ai and Bi with its corresponding value to the graph.
3. Define a helper function (DFS) for traversing the graph and calculating the answer for a given query.
4. Iterate through the queries and apply the DFS function to find the answers. Save the results in an array and return it.

The time complexity of this algorithm is O(N * P) where N is the number of equations and P is the number of queries. This is because for each query, we may need to visit all the nodes in our graph. The space complexity is O(N) which also corresponds to the size of the graph.

## A solution in Python

```python
from collections import defaultdict

def dfs(s1, s2, graph):
    if s1 not in graph or s2 not in graph:
        return -1.0
    if s1 == s2:
        return 1.0

    for neighbor, weight in graph[s1]:
        if neighbor not in visited:
            visited.add(neighbor)
            temp = dfs(neighbor, s2, graph)
            if temp > 0:
                return weight * temp
    return -1.0

def calcEquation(equations, values, queries):
    graph = defaultdict(list)
    for (s1, s2), value in zip(equations, values):
        graph[s1].append((s2, value))
        graph[s2].append((s1, 1 / value))

    ans = []
    for s1, s2 in queries:
        visited = set()
        ans.append(dfs(s1, s2, graph))
    return ans
```
First, we create an adjacency list `graph` to represent the relationship between variables where `graph[A].push({B, k})` for equation `A / B = k`. In each query, we try to find the path from `Cj` to `Dj` using a Depth-First Search (DFS) algorithm. In case the path exists, we return the value of `Cj / Dj`. If there is no path, return -1.0.

1. Create an empty graph (implemented as a hashmap) to store the variable pairs and values.
2. Iterate through the equations and values arrays, adding an edge between each Ai and Bi with its corresponding value to the graph.
3. Define a helper function (DFS) for traversing the graph and calculating the answer for a given query.
4. Iterate through the queries and apply the DFS function to find the answers. Save the results in an array and return it.

The time complexity of this algorithm is O(N * P) where N is the number of equations and P is the number of queries. This is because for each query, we may need to visit all the nodes in our graph. The space complexity is O(N) which also corresponds to the size of the graph.

## A solution in Javascript

```javascript
function dfs(s1, s2, graph) {
  if (!graph[s1] || !graph[s2]) return -1.0;
  if (s1 === s2) return 1.0;

  for (const [neighbor, weight] of graph[s1]) {
    if (!visited.has(neighbor)) {
      visited.add(neighbor);
      const temp = dfs(neighbor, s2, graph);
      if (temp > 0) return weight * temp;
    }
  }
  return -1.0;
}

function calcEquation(equations, values, queries) {
  const graph = {};
  for (let i = 0; i < equations.length; i++) {
    const [s1, s2] = equations[i];
    const value = values[i];

    if (!graph[s1]) graph[s1] = [];
    if (!graph[s2]) graph[s2] = [];
    graph[s1].push([s2, value]);
    graph[s2].push([s1, 1 / value]);
  }

  const ans = [];
  for (const [s1, s2] of queries) {
    const visited = new Set();
    ans.push(dfs(s1, s2, graph));
  }
  return ans;
}
```
First, we create an adjacency list `graph` to represent the relationship between variables where `graph[A].push({B, k})` for equation `A / B = k`. In each query, we try to find the path from `Cj` to `Dj` using a Depth-First Search (DFS) algorithm. In case the path exists, we return the value of `Cj / Dj`. If there is no path, return -1.0.

1. Create an empty graph (implemented as a hashmap) to store the variable pairs and values.
2. Iterate through the equations and values arrays, adding an edge between each Ai and Bi with its corresponding value to the graph.
3. Define a helper function (DFS) for traversing the graph and calculating the answer for a given query.
4. Iterate through the queries and apply the DFS function to find the answers. Save the results in an array and return it.

The time complexity of this algorithm is O(N * P) where N is the number of equations and P is the number of queries. This is because for each query, we may need to visit all the nodes in our graph. The space complexity is O(N) which also corresponds to the size of the graph.


# Nth Digit

- slug: nth-digit
- difficulty: Medium

Given an integer `n`, return the `nth` digit of the infinite integer sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]`.

**Example 1:**

**Input:** n = 3
**Output:** 3

**Example 2:**

**Input:** n = 11
**Output:** 0
**Explanation:** The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.

**Constraints:**

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

## A solution in Java

```java
public int findNthDigit(int n) {
    int size = 1;
    long length = 9;
    int start = 1;

    while (n > length * size) {
        n -= length * size;
        size++;
        length *= 10;
        start *= 10;
    }

    start += (n - 1) / size;
    String s = Integer.toString(start);
    return Character.getNumericValue(s.charAt((n - 1) % size));
}
```
The solution works as follows:
1. Initialize the `size` of each number at `1` (single-digit numbers), the `length` of numbers of that size at 9 (there are 9 single-digit numbers), and the `start` number of size `1` as `1`.
2. Keep subtracting the total length of numbers of the current size from `n` as long as `n` is greater than the total length of numbers of that size.
3. Increment `size` and multiply `length` and `start` by `10` when moving to the next size.
4. Add `(n - 1) / size` to `start` (adjusted for index 0) to find the number in the sequence that contains the nth digit.
5. Convert the found number to a string, and return the digit at position `(n - 1) % size`. In C++ and JavaScript, subtract '0' or use `parseInt` to convert the character back to an integer.

## A solution in C++

```cpp
int findNthDigit(int n) {
    int size = 1;
    long length = 9;
    int start = 1;

    while (n > length * size) {
        n -= length * size;
        size++;
        length *= 10;
        start *= 10;
    }

    start += (n - 1) / size;
    string s = to_string(start);
    return s[(n - 1) % size] - '0';
}
```
The solution works as follows:
1. Initialize the `size` of each number at `1` (single-digit numbers), the `length` of numbers of that size at 9 (there are 9 single-digit numbers), and the `start` number of size `1` as `1`.
2. Keep subtracting the total length of numbers of the current size from `n` as long as `n` is greater than the total length of numbers of that size.
3. Increment `size` and multiply `length` and `start` by `10` when moving to the next size.
4. Add `(n - 1) / size` to `start` (adjusted for index 0) to find the number in the sequence that contains the nth digit.
5. Convert the found number to a string, and return the digit at position `(n - 1) % size`. In C++ and JavaScript, subtract '0' or use `parseInt` to convert the character back to an integer.

## A solution in Python

```python
def findNthDigit(n):
    size = 1
    length = 9
    start = 1

    while n > length * size:
        n -= length * size
        size += 1
        length *= 10
        start *= 10

    start += (n - 1) // size
    s = str(start)
    return int(s[(n - 1) % size])
```
The solution works as follows:
1. Initialize the `size` of each number at `1` (single-digit numbers), the `length` of numbers of that size at 9 (there are 9 single-digit numbers), and the `start` number of size `1` as `1`.
2. Keep subtracting the total length of numbers of the current size from `n` as long as `n` is greater than the total length of numbers of that size.
3. Increment `size` and multiply `length` and `start` by `10` when moving to the next size.
4. Add `(n - 1) / size` to `start` (adjusted for index 0) to find the number in the sequence that contains the nth digit.
5. Convert the found number to a string, and return the digit at position `(n - 1) % size`. In C++ and JavaScript, subtract '0' or use `parseInt` to convert the character back to an integer.

## A solution in Javascript

```javascript
function findNthDigit(n) {
    let size = 1;
    let length = 9;
    let start = 1;

    while (n > length * size) {
        n -= length * size;
        size++;
        length *= 10;
        start *= 10;
    }

    start += Math.floor((n - 1) / size);
    const s = start.toString();
    return parseInt(s.charAt((n - 1) % size));
}
```
The solution works as follows:
1. Initialize the `size` of each number at `1` (single-digit numbers), the `length` of numbers of that size at 9 (there are 9 single-digit numbers), and the `start` number of size `1` as `1`.
2. Keep subtracting the total length of numbers of the current size from `n` as long as `n` is greater than the total length of numbers of that size.
3. Increment `size` and multiply `length` and `start` by `10` when moving to the next size.
4. Add `(n - 1) / size` to `start` (adjusted for index 0) to find the number in the sequence that contains the nth digit.
5. Convert the found number to a string, and return the digit at position `(n - 1) % size`. In C++ and JavaScript, subtract '0' or use `parseInt` to convert the character back to an integer.


# Binary Watch

- slug: binary-watch
- difficulty: Easy

A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

*   For example, the below binary watch reads `"4:51 "`.

Given an integer `turnedOn` which represents the number of LEDs that are currently on (ignoring the PM), return _all possible times the watch could represent_. You may return the answer in **any order**.

The hour must not contain a leading zero.

*   For example, `"01:00 "` is not valid. It should be `"1:00 "`.

The minute must be consist of two digits and may contain a leading zero.

*   For example, `"10:2 "` is not valid. It should be `"10:02 "`.

**Example 1:**

**Input:** turnedOn = 1
**Output:** \["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"\]

**Example 2:**

**Input:** turnedOn = 9
**Output:** \[\]

**Constraints:**

*   `0 <= turnedOn <= 10`

## A solution in Java

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

public List<String> readBinaryWatch(int turnedOn) {
    List<String> times = new ArrayList<>();
    for (int h = 0; h < 12; h++) {
        for (int m = 0; m < 60; m++) {
            if (Integer.bitCount(h) + Integer.bitCount(m) == turnedOn) {
                times.add(String.format("%d:%02d", h, m));
            }
        }
    }
    return times;
}
```
The algorithm consists of enumerating all possible hour values (0-11) and minute values (0-59), and checking the number of bits set in both. We have a helper function `count_bits` (or named similarly) in each language to count the number of bits set in the binary representation of a given value. The function either uses the built-in bit counting function (__builtin_popcount in C++, Integer.bitCount in Java), or in Python and JavaScript, we convert the numbers to binary strings and count the number of '1's.

For each pair (h, m), if the total number of turned-on LEDs is equal to the given integer `turnedOn`, we add the corresponding formatted string to the result list. In the end, we return the list of all possible times.

## A solution in C++

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

vector<string> readBinaryWatch(int turnedOn) {
    vector<string> times;
    for (int h = 0; h < 12; h++) {
        for (int m = 0; m < 60; m++) {
            if (__builtin_popcount(h) + __builtin_popcount(m) == turnedOn) {
                times.push_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m));
            }
        }
    }
    return times;
}
```
The algorithm consists of enumerating all possible hour values (0-11) and minute values (0-59), and checking the number of bits set in both. We have a helper function `count_bits` (or named similarly) in each language to count the number of bits set in the binary representation of a given value. The function either uses the built-in bit counting function (__builtin_popcount in C++, Integer.bitCount in Java), or in Python and JavaScript, we convert the numbers to binary strings and count the number of '1's.

For each pair (h, m), if the total number of turned-on LEDs is equal to the given integer `turnedOn`, we add the corresponding formatted string to the result list. In the end, we return the list of all possible times.

## A solution in Python

```python
def readBinaryWatch(turnedOn: int):
    def count_bits(n):
        return bin(n).count('1')

    times = []
    for h in range(12):
        for m in range(60):
            if count_bits(h) + count_bits(m) == turnedOn:
                times.append(f"{h}:{m:02d}")
    return times
```
The algorithm consists of enumerating all possible hour values (0-11) and minute values (0-59), and checking the number of bits set in both. We have a helper function `count_bits` (or named similarly) in each language to count the number of bits set in the binary representation of a given value. The function either uses the built-in bit counting function (__builtin_popcount in C++, Integer.bitCount in Java), or in Python and JavaScript, we convert the numbers to binary strings and count the number of '1's.

For each pair (h, m), if the total number of turned-on LEDs is equal to the given integer `turnedOn`, we add the corresponding formatted string to the result list. In the end, we return the list of all possible times.

## A solution in Javascript

```javascript
function readBinaryWatch(turnedOn) {
    function countBits(n) {
        return n.toString(2).split('1').length - 1;
    }

    const times = [];
    for (let h = 0; h < 12; h++) {
        for (let m = 0; m < 60; m++) {
            if (countBits(h) + countBits(m) === turnedOn) {
                times.push(`${h}:${m.toString().padStart(2, '0')}`);
            }
        }
    }
    return times;
}
```
The algorithm consists of enumerating all possible hour values (0-11) and minute values (0-59), and checking the number of bits set in both. We have a helper function `count_bits` (or named similarly) in each language to count the number of bits set in the binary representation of a given value. The function either uses the built-in bit counting function (__builtin_popcount in C++, Integer.bitCount in Java), or in Python and JavaScript, we convert the numbers to binary strings and count the number of '1's.

For each pair (h, m), if the total number of turned-on LEDs is equal to the given integer `turnedOn`, we add the corresponding formatted string to the result list. In the end, we return the list of all possible times.


# Remove K Digits

- slug: remove-k-digits
- difficulty: Medium

Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`.

**Example 1:**

**Input:** num =  "1432219 ", k = 3
**Output:**  "1219 "
**Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

**Example 2:**

**Input:** num =  "10200 ", k = 1
**Output:**  "200 "
**Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

**Example 3:**

**Input:** num =  "10 ", k = 2
**Output:**  "0 "
**Explanation:** Remove all the digits from the number and it is left with nothing which is 0.

**Constraints:**

*   `1 <= k <= num.length <= 105`
*   `num` consists of only digits.
*   `num` does not have any leading zeros except for the zero itself.

## A solution in Java

```java
public String removeKDigits(String num, int k) {
    StringBuilder result = new StringBuilder();
    for (char c : num.toCharArray()) {
        while (k > 0 && result.length() > 0 && result.charAt(result.length() - 1) > c) {
            result.setLength(result.length() - 1);
            k--;
        }
        result.append(c);
    }
    result.setLength(result.length() - k);
    while (result.length() > 0 && result.charAt(0) == '0') {
        result.deleteCharAt(0);
    }
    return result.length() == 0 ? "0" : result.toString();
}
```
The algorithm maintains a stack, initially empty. It iterates through the input string char by char, and for each char, it tries to remove the largest possible digit from the stack, as long as k is greater than 0. If the stack is empty or its topmost element is smaller than the current char, the current char is pushed into the stack.

After the iteration, if k is still greater than 0, then we remove the remaining top k elements from the stack. Finally, the resultant smallest integer is formed from the stack, removing any leading zeros if present, and returned as a string.

The time complexity of this algorithm is O(n), where n is the length of the input string, as it iterates through the input string once and processes each character.

## A solution in C++

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

string removeKDigits(string num, int k) {
    string result = "";
    for (char c : num) {
        while (k > 0 && !result.empty() && result.back() > c) {
            result.pop_back();
            k--;
        }
        result.push_back(c);
    }
    result.resize(result.length() - k);
    while (!result.empty() && result[0] == '0') {
        result.erase(result.begin());
    }
    return result.empty() ? "0" : result;
}
```
The algorithm maintains a stack, initially empty. It iterates through the input string char by char, and for each char, it tries to remove the largest possible digit from the stack, as long as k is greater than 0. If the stack is empty or its topmost element is smaller than the current char, the current char is pushed into the stack.

After the iteration, if k is still greater than 0, then we remove the remaining top k elements from the stack. Finally, the resultant smallest integer is formed from the stack, removing any leading zeros if present, and returned as a string.

The time complexity of this algorithm is O(n), where n is the length of the input string, as it iterates through the input string once and processes each character.

## A solution in Python

```python
def remove_k_digits(num, k):
    stack = []
    for c in num:
        while k > 0 and stack and stack[-1] > c:
            stack.pop()
            k -= 1
        stack.append(c)
    while k > 0:
        stack.pop()
        k -= 1
    return ''.join(stack).lstrip('0') or '0'
```
The algorithm maintains a stack, initially empty. It iterates through the input string char by char, and for each char, it tries to remove the largest possible digit from the stack, as long as k is greater than 0. If the stack is empty or its topmost element is smaller than the current char, the current char is pushed into the stack.

After the iteration, if k is still greater than 0, then we remove the remaining top k elements from the stack. Finally, the resultant smallest integer is formed from the stack, removing any leading zeros if present, and returned as a string.

The time complexity of this algorithm is O(n), where n is the length of the input string, as it iterates through the input string once and processes each character.

## A solution in Javascript

```javascript
function removeKDigits(num, k) {
    let stack = [];
    for (let i = 0; i < num.length; i++) {
        let c = num[i];
        while (k > 0 && stack.length > 0 && stack[stack.length - 1] > c) {
            stack.pop();
            k--;
        }
        stack.push(c);
    }
    while (k > 0) {
        stack.pop();
        k--;
    }
    let result = stack.join('').replace(/^0+/, '');
    return result || '0';
}
```
The algorithm maintains a stack, initially empty. It iterates through the input string char by char, and for each char, it tries to remove the largest possible digit from the stack, as long as k is greater than 0. If the stack is empty or its topmost element is smaller than the current char, the current char is pushed into the stack.

After the iteration, if k is still greater than 0, then we remove the remaining top k elements from the stack. Finally, the resultant smallest integer is formed from the stack, removing any leading zeros if present, and returned as a string.

The time complexity of this algorithm is O(n), where n is the length of the input string, as it iterates through the input string once and processes each character.


# Frog Jump

- slug: frog-jump
- difficulty: Hard

A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit.

If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction.

**Example 1:**

**Input:** stones = \[0,1,3,5,6,8,12,17\]
**Output:** true
**Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.

**Example 2:**

**Input:** stones = \[0,1,2,3,4,8,9,11\]
**Output:** false
**Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.

**Constraints:**

*   `2 <= stones.length <= 2000`
*   `0 <= stones[i] <= 231 - 1`
*   `stones[0] == 0`
*   `stones` is sorted in a strictly increasing order.

## A solution in Java

```java
import java.util.*;

public boolean canCross(int[] stones) {
    Map<Integer, Set<Integer>> dp = new HashMap<>();
    for (int stone : stones)
        dp.put(stone, new HashSet<>());
    dp.get(0).add(0);

    for (int stone : stones) {
        for (int k : dp.get(stone)) {
            for (int jump : new int[]{k - 1, k, k + 1}) {
                if (jump > 0 && dp.containsKey(stone + jump))
                    dp.get(stone + jump).add(jump);
            }
        }
    }
    return !dp.get(stones[stones.length - 1]).isEmpty();
}
```
The algorithm initializes an empty hash map `dp` with a key for each stone position and the values set to be an empty set. We then add the initial jump (0) to the first stone in the `dp` hash map. The algorithm proceeds iteratively for each of the stones. For each stone, the algorithm checks all possible jump lengths (`k`) in the `dp` hash map for the stone. The next possible jumps are then calculated (k - 1, k, and k + 1) and added to their respective stone positions in the `dp` map. This process continues until all stones are traversed. At the end, if the last stone in `dp` map contains any elements, it means the frog can reach the last stone, and the function returns True/True or False. Otherwise, the function returns False/false.

## A solution in C++

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

bool canCross(vector<int>& stones) {
    unordered_map<int, unordered_set<int>> dp;
    int n = stones.size();
    for (int stone : stones)
        dp[stone] = unordered_set<int>();
    dp[0].insert(0);

    for (int stone : stones) {
        for (int k : dp[stone]) {
            for (int jump : {k - 1, k, k + 1}) {
                if (jump > 0 && dp.count(stone + jump))
                    dp[stone + jump].insert(jump);
            }
        }
    }
    return !dp[stones.back()].empty();
}
```
The algorithm initializes an empty hash map `dp` with a key for each stone position and the values set to be an empty set. We then add the initial jump (0) to the first stone in the `dp` hash map. The algorithm proceeds iteratively for each of the stones. For each stone, the algorithm checks all possible jump lengths (`k`) in the `dp` hash map for the stone. The next possible jumps are then calculated (k - 1, k, and k + 1) and added to their respective stone positions in the `dp` map. This process continues until all stones are traversed. At the end, if the last stone in `dp` map contains any elements, it means the frog can reach the last stone, and the function returns True/True or False. Otherwise, the function returns False/false.

## A solution in Python

```python
def can_cross(stones):
    dp = {stone: set() for stone in stones}
    dp[0].add(0)

    for stone in stones:
        for k in dp[stone]:
            for jump in (k - 1, k, k + 1):
                if jump > 0 and stone + jump in dp:
                    dp[stone + jump].add(jump)

    return bool(dp[stones[-1]])
```
The algorithm initializes an empty hash map `dp` with a key for each stone position and the values set to be an empty set. We then add the initial jump (0) to the first stone in the `dp` hash map. The algorithm proceeds iteratively for each of the stones. For each stone, the algorithm checks all possible jump lengths (`k`) in the `dp` hash map for the stone. The next possible jumps are then calculated (k - 1, k, and k + 1) and added to their respective stone positions in the `dp` map. This process continues until all stones are traversed. At the end, if the last stone in `dp` map contains any elements, it means the frog can reach the last stone, and the function returns True/True or False. Otherwise, the function returns False/false.

## A solution in Javascript

```javascript
function canCross(stones) {
    const dp = new Map();
    stones.forEach(stone => dp.set(stone, new Set()));
    dp.get(0).add(0);

    for (const stone of stones) {
        for (const k of dp.get(stone)) {
            for (const jump of [k - 1, k, k + 1]) {
                if (jump > 0 && dp.has(stone + jump))
                    dp.get(stone + jump).add(jump);
            }
        }
    }
    return dp.get(stones[stones.length - 1]).size > 0;
}
```
The algorithm initializes an empty hash map `dp` with a key for each stone position and the values set to be an empty set. We then add the initial jump (0) to the first stone in the `dp` hash map. The algorithm proceeds iteratively for each of the stones. For each stone, the algorithm checks all possible jump lengths (`k`) in the `dp` hash map for the stone. The next possible jumps are then calculated (k - 1, k, and k + 1) and added to their respective stone positions in the `dp` map. This process continues until all stones are traversed. At the end, if the last stone in `dp` map contains any elements, it means the frog can reach the last stone, and the function returns True/True or False. Otherwise, the function returns False/false.