# Logger Rate Limiter

- slug: logger-rate-limiter
- difficulty: Easy

Design a logger system that receives a stream of messages along with their timestamps. Each **unique** message should only be printed **at most every 10 seconds** (i.e. a message printed at timestamp `t` will prevent other identical messages from being printed until timestamp `t + 10`).

All messages will come in chronological order. Several messages may arrive at the same timestamp.

Implement the `Logger` class:

*   `Logger()` Initializes the `logger` object.
*   `bool shouldPrintMessage(int timestamp, string message)` Returns `true` if the `message` should be printed in the given `timestamp`, otherwise returns `false`.

**Example 1:**

**Input**
\[ "Logger ",  "shouldPrintMessage ",  "shouldPrintMessage ",  "shouldPrintMessage ",  "shouldPrintMessage ",  "shouldPrintMessage ",  "shouldPrintMessage "\]
\[\[\], \[1,  "foo "\], \[2,  "bar "\], \[3,  "foo "\], \[8,  "bar "\], \[10,  "foo "\], \[11,  "foo "\]\]
**Output**
\[null, true, true, false, false, false, true\]

**Explanation**
Logger logger = new Logger();
logger.shouldPrintMessage(1,  "foo ");  // return true, next allowed timestamp for  "foo " is 1 + 10 = 11
logger.shouldPrintMessage(2,  "bar ");  // return true, next allowed timestamp for  "bar " is 2 + 10 = 12
logger.shouldPrintMessage(3,  "foo ");  // 3 < 11, return false
logger.shouldPrintMessage(8,  "bar ");  // 8 < 12, return false
logger.shouldPrintMessage(10,  "foo "); // 10 < 11, return false
logger.shouldPrintMessage(11,  "foo "); // 11 >= 11, return true, next allowed timestamp for  "foo " is 11 + 10 = 21

**Constraints:**

*   `0 <= timestamp <= 109`
*   Every `timestamp` will be passed in non-decreasing order (chronological order).
*   `1 <= message.length <= 30`
*   At most `104` calls will be made to `shouldPrintMessage`.

## A solution in Java

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

public class Logger {
    private Map<String, Integer> messageTimestamps;

    public Logger() {
        messageTimestamps = new HashMap<>();
    }

    public boolean shouldPrintMessage(int timestamp, String message) {
        if (!messageTimestamps.containsKey(message) || timestamp - messageTimestamps.get(message) >= 10) {
            messageTimestamps.put(message, timestamp);
            return true;
        }
        return false;
    }
}
```
The algorithm initializes an empty map to store message timestamps. The `shouldPrintMessage` function takes input parameters `timestamp` and `message`. It checks if the message is in the map or not. If the message is not in the map or the difference between the given timestamp and the message's timestamp is greater than or equal to 10, it updates the message's timestamp in the map with the given timestamp, and the function returns `true`. If the difference is less than 10, the function returns `false`. This ensures that messages will only be printed at most every 10 seconds.

## A solution in C++

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

class Logger {
public:
    unordered_map<string, int> message_timestamps;

    Logger() {
    }

    bool shouldPrintMessage(int timestamp, string message) {
        if (!message_timestamps.count(message) || timestamp - message_timestamps[message] >= 10) {
            message_timestamps[message] = timestamp;
            return true;
        }
        return false;
    }
};
```
The algorithm initializes an empty map to store message timestamps. The `shouldPrintMessage` function takes input parameters `timestamp` and `message`. It checks if the message is in the map or not. If the message is not in the map or the difference between the given timestamp and the message's timestamp is greater than or equal to 10, it updates the message's timestamp in the map with the given timestamp, and the function returns `true`. If the difference is less than 10, the function returns `false`. This ensures that messages will only be printed at most every 10 seconds.

## A solution in Python

```python
class Logger:
    def __init__(self):
        self.message_timestamps = {}

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        if message not in self.message_timestamps or timestamp - self.message_timestamps[message] >= 10:
            self.message_timestamps[message] = timestamp
            return True
        return False
```
The algorithm initializes an empty map to store message timestamps. The `shouldPrintMessage` function takes input parameters `timestamp` and `message`. It checks if the message is in the map or not. If the message is not in the map or the difference between the given timestamp and the message's timestamp is greater than or equal to 10, it updates the message's timestamp in the map with the given timestamp, and the function returns `true`. If the difference is less than 10, the function returns `false`. This ensures that messages will only be printed at most every 10 seconds.

## A solution in Javascript

```javascript
class Logger {
    constructor() {
        this.messageTimestamps = {};
    }

    shouldPrintMessage(timestamp, message) {
        if (!this.messageTimestamps.hasOwnProperty(message) || timestamp - this.messageTimestamps[message] >= 10) {
            this.messageTimestamps[message] = timestamp;
            return true;
        }
        return false;
    }
}
```
The algorithm initializes an empty map to store message timestamps. The `shouldPrintMessage` function takes input parameters `timestamp` and `message`. It checks if the message is in the map or not. If the message is not in the map or the difference between the given timestamp and the message's timestamp is greater than or equal to 10, it updates the message's timestamp in the map with the given timestamp, and the function returns `true`. If the difference is less than 10, the function returns `false`. This ensures that messages will only be printed at most every 10 seconds.


# Sort Transformed Array

- slug: sort-transformed-array
- difficulty: Medium

Given a **sorted** integer array `nums` and three integers `a`, `b` and `c`, apply a quadratic function of the form `f(x) = ax2 + bx + c` to each element `nums[i]` in the array, and return _the array in a sorted order_.

**Example 1:**

**Input:** nums = \[-4,-2,2,4\], a = 1, b = 3, c = 5
**Output:** \[3,9,15,33\]

**Example 2:**

**Input:** nums = \[-4,-2,2,4\], a = -1, b = 3, c = 5
**Output:** \[-23,-5,1,7\]

**Constraints:**

*   `1 <= nums.length <= 200`
*   `-100 <= nums[i], a, b, c <= 100`
*   `nums` is sorted in **ascending** order.

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

## A solution in Java

```java
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
    int[] result = new int[nums.length];
    int i = 0, j = nums.length - 1, index = (a >= 0) ? nums.length - 1 : 0;

    while (i <= j) {
        int left = nums[i] * nums[i] * a + nums[i] * b + c;
        int right = nums[j] * nums[j] * a + nums[j] * b + c;

        if (a >= 0) {
            if (left >= right) {
                result[index--] = left;
                i++;
            } else {
                result[index--] = right;
                j--;
            }
        } else {
            if (left <= right) {
                result[index++] = left;
                i++;
            } else {
                result[index++] = right;
                j--;
            }
        }
    }
    return result;
}
```
The given sorted array needs to be transformed by applying the given quadratic function: f(x) = ax^2 + bx + c. We need to return the new array in sorted order. To solve this problem in O(n) time, we utilize a two-pointer technique. Initialize pointers, i and j, at the beginning and end of the array. Depending on whether the given coefficient 'a' is positive or negative, we'll determine how the values are sorted after transformation when calculated from left or right of the array.

If 'a' is positive or zero, the parabola of the quadratic function opens upward, meaning larger x values will yield a higher f(x). So, we traverse the array, compare the quadratic function at the indices i and j, and fill the result array from the end to the beginning. If the value at i is greater, store it at current index index, decrement index, and increment i. If value at j is greater or equal, store it and decrement j and index.

On the other hand, if 'a' is negative, the parabola opens downward, meaning smaller x values will yield a higher f(x). In this case, compare the quadratic function at the indices i and j, fill the result array from the beginning to the end. If the value at i is smaller or equal, store it at current index index, increment index and i. If value at j is smaller, store it and decrement j, then increment index. Once i > j, the result array is fully filled with the sorted transformed values.

## A solution in C++

```cpp
vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
    vector<int> result(nums.size());
    int i = 0, j = nums.size() - 1, index = (a >= 0) ? nums.size() - 1 : 0;

    while (i <= j) {
        int left = nums[i] * nums[i] * a + nums[i] * b + c;
        int right = nums[j] * nums[j] * a + nums[j] * b + c;

        if (a >= 0) {
            if (left >= right) {
                result[index--] = left;
                i++;
            } else {
                result[index--] = right;
                j--;
            }
        } else {
            if (left <= right) {
                result[index++] = left;
                i++;
            } else {
                result[index++] = right;
                j--;
            }
        }
    }
    return result;
}
```
The given sorted array needs to be transformed by applying the given quadratic function: f(x) = ax^2 + bx + c. We need to return the new array in sorted order. To solve this problem in O(n) time, we utilize a two-pointer technique. Initialize pointers, i and j, at the beginning and end of the array. Depending on whether the given coefficient 'a' is positive or negative, we'll determine how the values are sorted after transformation when calculated from left or right of the array.

If 'a' is positive or zero, the parabola of the quadratic function opens upward, meaning larger x values will yield a higher f(x). So, we traverse the array, compare the quadratic function at the indices i and j, and fill the result array from the end to the beginning. If the value at i is greater, store it at current index index, decrement index, and increment i. If value at j is greater or equal, store it and decrement j and index.

On the other hand, if 'a' is negative, the parabola opens downward, meaning smaller x values will yield a higher f(x). In this case, compare the quadratic function at the indices i and j, fill the result array from the beginning to the end. If the value at i is smaller or equal, store it at current index index, increment index and i. If value at j is smaller, store it and decrement j, then increment index. Once i > j, the result array is fully filled with the sorted transformed values.

## A solution in Python

```python
def sort_transformed_array(nums, a, b, c):
    result = [0] * len(nums)
    i, j = 0, len(nums) - 1
    index = len(nums) - 1 if a >= 0 else 0

    while i <= j:
        left = nums[i] * nums[i] * a + nums[i] * b + c
        right = nums[j] * nums[j] * a + nums[j] * b + c

        if a >= 0:
            if left >= right:
                result[index] = left
                index -= 1
                i += 1
            else:
                result[index] = right
                index -= 1
                j -= 1
        else:
            if left <= right:
                result[index] = left
                index += 1
                i += 1
            else:
                result[index] = right
                index += 1
                j -= 1
    return result
```
The given sorted array needs to be transformed by applying the given quadratic function: f(x) = ax^2 + bx + c. We need to return the new array in sorted order. To solve this problem in O(n) time, we utilize a two-pointer technique. Initialize pointers, i and j, at the beginning and end of the array. Depending on whether the given coefficient 'a' is positive or negative, we'll determine how the values are sorted after transformation when calculated from left or right of the array.

If 'a' is positive or zero, the parabola of the quadratic function opens upward, meaning larger x values will yield a higher f(x). So, we traverse the array, compare the quadratic function at the indices i and j, and fill the result array from the end to the beginning. If the value at i is greater, store it at current index index, decrement index, and increment i. If value at j is greater or equal, store it and decrement j and index.

On the other hand, if 'a' is negative, the parabola opens downward, meaning smaller x values will yield a higher f(x). In this case, compare the quadratic function at the indices i and j, fill the result array from the beginning to the end. If the value at i is smaller or equal, store it at current index index, increment index and i. If value at j is smaller, store it and decrement j, then increment index. Once i > j, the result array is fully filled with the sorted transformed values.

## A solution in Javascript

```javascript
function sortTransformedArray(nums, a, b, c) {
    let result = new Array(nums.length);
    let i = 0, j = nums.length - 1;
    let index = (a >= 0) ? nums.length - 1 : 0;

    while (i <= j) {
        let left = nums[i] * nums[i] * a + nums[i] * b + c;
        let right = nums[j] * nums[j] * a + nums[j] * b + c;

        if (a >= 0) {
            if (left >= right) {
                result[index--] = left;
                i++;
            } else {
                result[index--] = right;
                j--;
            }
        } else {
            if (left <= right) {
                result[index++] = left;
                i++;
            } else {
                result[index++] = right;
                j--;
            }
        }
    }
    return result;
}
```
The given sorted array needs to be transformed by applying the given quadratic function: f(x) = ax^2 + bx + c. We need to return the new array in sorted order. To solve this problem in O(n) time, we utilize a two-pointer technique. Initialize pointers, i and j, at the beginning and end of the array. Depending on whether the given coefficient 'a' is positive or negative, we'll determine how the values are sorted after transformation when calculated from left or right of the array.

If 'a' is positive or zero, the parabola of the quadratic function opens upward, meaning larger x values will yield a higher f(x). So, we traverse the array, compare the quadratic function at the indices i and j, and fill the result array from the end to the beginning. If the value at i is greater, store it at current index index, decrement index, and increment i. If value at j is greater or equal, store it and decrement j and index.

On the other hand, if 'a' is negative, the parabola opens downward, meaning smaller x values will yield a higher f(x). In this case, compare the quadratic function at the indices i and j, fill the result array from the beginning to the end. If the value at i is smaller or equal, store it at current index index, increment index and i. If value at j is smaller, store it and decrement j, then increment index. Once i > j, the result array is fully filled with the sorted transformed values.


# Bomb Enemy

- slug: bomb-enemy
- difficulty: Medium

Given an `m x n` matrix `grid` where each cell is either a wall `'W'`, an enemy `'E'` or empty `'0'`, return _the maximum enemies you can kill using one bomb_. You can only place the bomb in an empty cell.

The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since it is too strong to be destroyed.

**Example 1:**

**Input:** grid = \[\[ "0 ", "E ", "0 ", "0 "\],\[ "E ", "0 ", "W ", "E "\],\[ "0 ", "E ", "0 ", "0 "\]\]
**Output:** 3

**Example 2:**

**Input:** grid = \[\[ "W ", "W ", "W "\],\[ "0 ", "0 ", "0 "\],\[ "E ", "E ", "E "\]\]
**Output:** 1

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 500`
*   `grid[i][j]` is either `'W'`, `'E'`, or `'0'`.

## A solution in Java

```java
public int maxKilledEnemies(char[][] grid) {
    if (grid.length == 0) return 0;
    int m = grid.length, n = grid[0].length, result = 0, rowhits;
    int[] colhits = new int[n];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (j == 0 || grid[i][j-1] == 'W') {
                rowhits = 0;
                for (int k = j; k < n && grid[i][k] != 'W'; k++)
                    rowhits += grid[i][k] == 'E' ? 1 : 0;
            }
            if (i == 0 || grid[i-1][j] == 'W') {
                colhits[j] = 0;
                for (int k = i; k < m && grid[k][j] != 'W'; k++)
                    colhits[j] += grid[k][j] == 'E' ? 1 : 0;
            }
            if (grid[i][j] == '0') result = Math.max(result, rowhits + colhits[j]);
        }
    }
    return result;
}
```
Initialize `result` to keep track of the maximum number of enemies that can be killed. Then, initialize `rowhits` and `colhits` to store the number of enemies in the current row and column.

Loop through the `grid`. When you start a new row or encounter a wall in the previous cell, reset `rowhits` and count the number of enemies in the row. If you are in the first row, or encounter a wall in the cell above, reset the `colhits` for that column and count the number of enemies in the column.

If you encounter an empty cell, update the `result` with the maximum of its current value and the sum of `rowhits` and `colhits` for that position.

Return `result`.

## A solution in C++

```cpp
int maxKilledEnemies(vector<vector<char>>& grid) {
    if (grid.empty()) return 0;
    int m = grid.size(), n = grid[0].size(), result = 0, rowhits = 0;
    vector<int> colhits(n, 0);
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (j == 0 || grid[i][j - 1] == 'W') {
                rowhits = 0;
                for (int k = j; k < n && grid[i][k] != 'W'; k++)
                    rowhits += grid[i][k] == 'E';
            }
            if (i == 0 || grid[i - 1][j] == 'W') {
                colhits[j] = 0;
                for (int k = i; k < m && grid[k][j] != 'W'; k++)
                    colhits[j] += grid[k][j] == 'E';
            }
            if (grid[i][j] == '0') result = max(result, rowhits + colhits[j]);
        }
    }
    return result;
}
```
Initialize `result` to keep track of the maximum number of enemies that can be killed. Then, initialize `rowhits` and `colhits` to store the number of enemies in the current row and column.

Loop through the `grid`. When you start a new row or encounter a wall in the previous cell, reset `rowhits` and count the number of enemies in the row. If you are in the first row, or encounter a wall in the cell above, reset the `colhits` for that column and count the number of enemies in the column.

If you encounter an empty cell, update the `result` with the maximum of its current value and the sum of `rowhits` and `colhits` for that position.

Return `result`.

## A solution in Python

```python
def maxKilledEnemies(grid):
    if not grid: return 0
    m, n, result, rowhits = len(grid), len(grid[0]), 0, 0
    colhits = [0] * n
    for i in range(m):
        for j in range(n):
            if j == 0 or grid[i][j - 1] == 'W':
                rowhits = 0
                k = j
                while k < n and grid[i][k] != 'W':
                    rowhits += grid[i][k] == 'E'
                    k += 1
            if i == 0 or grid[i - 1][j] == 'W':
                colhits[j] = 0
                k = i
                while k < m and grid[k][j] != 'W':
                    colhits[j] += grid[k][j] == 'E'
                    k += 1
            if grid[i][j] == '0':
                result = max(result, rowhits + colhits[j])
    return result
```
Initialize `result` to keep track of the maximum number of enemies that can be killed. Then, initialize `rowhits` and `colhits` to store the number of enemies in the current row and column.

Loop through the `grid`. When you start a new row or encounter a wall in the previous cell, reset `rowhits` and count the number of enemies in the row. If you are in the first row, or encounter a wall in the cell above, reset the `colhits` for that column and count the number of enemies in the column.

If you encounter an empty cell, update the `result` with the maximum of its current value and the sum of `rowhits` and `colhits` for that position.

Return `result`.

## A solution in Javascript

```javascript
function maxKilledEnemies(grid) {
    if (!grid.length) return 0;
    let m = grid.length, n = grid[0].length, result = 0, rowhits;
    let colhits = new Array(n).fill(0);
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (j === 0 || grid[i][j - 1] === 'W') {
                rowhits = 0;
                for (let k = j; k < n && grid[i][k] !== 'W'; k++)
                    rowhits += grid[i][k] === 'E' ? 1 : 0;
            }
            if (i === 0 || grid[i - 1][j] === 'W') {
                colhits[j] = 0;
                for (let k = i; k < m && grid[k][j] !== 'W'; k++)
                    colhits[j] += grid[k][j] === 'E' ? 1 : 0;
            }
            if (grid[i][j] === '0') result = Math.max(result, rowhits + colhits[j]);
        }
    }
    return result;
}
```
Initialize `result` to keep track of the maximum number of enemies that can be killed. Then, initialize `rowhits` and `colhits` to store the number of enemies in the current row and column.

Loop through the `grid`. When you start a new row or encounter a wall in the previous cell, reset `rowhits` and count the number of enemies in the row. If you are in the first row, or encounter a wall in the cell above, reset the `colhits` for that column and count the number of enemies in the column.

If you encounter an empty cell, update the `result` with the maximum of its current value and the sum of `rowhits` and `colhits` for that position.

Return `result`.


# Design Hit Counter

- slug: design-hit-counter
- difficulty: Medium

Design a hit counter which counts the number of hits received in the past `5` minutes (i.e., the past `300` seconds).

Your system should accept a `timestamp` parameter (**in seconds** granularity), and you may assume that calls are being made to the system in chronological order (i.e., `timestamp` is monotonically increasing). Several hits may arrive roughly at the same time.

Implement the `HitCounter` class:

*   `HitCounter()` Initializes the object of the hit counter system.
*   `void hit(int timestamp)` Records a hit that happened at `timestamp` (**in seconds**). Several hits may happen at the same `timestamp`.
*   `int getHits(int timestamp)` Returns the number of hits in the past 5 minutes from `timestamp` (i.e., the past `300` seconds).

**Example 1:**

**Input**
\[ "HitCounter ",  "hit ",  "hit ",  "hit ",  "getHits ",  "hit ",  "getHits ",  "getHits "\]
\[\[\], \[1\], \[2\], \[3\], \[4\], \[300\], \[300\], \[301\]\]
**Output**
\[null, null, null, null, 3, null, 4, 3\]

**Explanation**
HitCounter hitCounter = new HitCounter();
hitCounter.hit(1);       // hit at timestamp 1.
hitCounter.hit(2);       // hit at timestamp 2.
hitCounter.hit(3);       // hit at timestamp 3.
hitCounter.getHits(4);   // get hits at timestamp 4, return 3.
hitCounter.hit(300);     // hit at timestamp 300.
hitCounter.getHits(300); // get hits at timestamp 300, return 4.
hitCounter.getHits(301); // get hits at timestamp 301, return 3.

**Constraints:**

*   `1 <= timestamp <= 2 * 109`
*   All the calls are being made to the system in chronological order (i.e., `timestamp` is monotonically increasing).
*   At most `300` calls will be made to `hit` and `getHits`.

**Follow up:** What if the number of hits per second could be huge? Does your design scale?

## A solution in Java

```java
import java.util.LinkedList;
import java.util.Queue;

public class HitCounter {
    private Queue<Integer> queue;

    public HitCounter() {
        queue = new LinkedList<>();
    }

    public void hit(int timestamp) {
        queue.offer(timestamp);
    }

    public int getHits(int timestamp) {
        while (!queue.isEmpty() && queue.peek() <= (timestamp - 300)) {
            queue.poll();
        }
        return queue.size();
    }
}
```
The key to solving this problem is maintaining a queue with hit timestamps. Since the timestamps are monotonically increasing, we can simply simulate the moving window by removing hits that are no longer within the last 300 seconds for a given timestamp.

1. Implement the `HitCounter` class with a queue-like data structure (e.g., `deque`, `queue`, `list`, `linkedlist`)
2. For `hit(timestamp)`, add the timestamp to the tail of the queue.
3. For `getHits(timestamp)`, iterate through the timestamps from the head of the queue and remove any timestamp that is not within the last 300 seconds (i.e., <= current_timestamp - 300). Then return the number of timestamps left in the queue (i.e., the size of the queue).

There is no difference in terms of algorithm between the four languages. They all follow the same logic which is based on the explanation above. Some minor differences include the syntax and how certain operations are done, but the core logic remains the same.

## A solution in C++

```cpp
#include <queue>

class HitCounter {
public:
    HitCounter() {}

    void hit(int timestamp) {
        q.push(timestamp);
    }

    int getHits(int timestamp) {
        while (!q.empty() && q.front() <= (timestamp - 300)) {
            q.pop();
        }
        return q.size();
    }

private:
    std::queue<int> q;
};
```
The key to solving this problem is maintaining a queue with hit timestamps. Since the timestamps are monotonically increasing, we can simply simulate the moving window by removing hits that are no longer within the last 300 seconds for a given timestamp.

1. Implement the `HitCounter` class with a queue-like data structure (e.g., `deque`, `queue`, `list`, `linkedlist`)
2. For `hit(timestamp)`, add the timestamp to the tail of the queue.
3. For `getHits(timestamp)`, iterate through the timestamps from the head of the queue and remove any timestamp that is not within the last 300 seconds (i.e., <= current_timestamp - 300). Then return the number of timestamps left in the queue (i.e., the size of the queue).

There is no difference in terms of algorithm between the four languages. They all follow the same logic which is based on the explanation above. Some minor differences include the syntax and how certain operations are done, but the core logic remains the same.

## A solution in Python

```python
from collections import deque

class HitCounter:

    def __init__(self):
        self.queue = deque()

    def hit(self, timestamp: int) -> None:
        self.queue.append(timestamp)

    def getHits(self, timestamp: int) -> int:
        while self.queue and self.queue[0] <= timestamp - 300:
            self.queue.popleft()
        return len(self.queue)
```
The key to solving this problem is maintaining a queue with hit timestamps. Since the timestamps are monotonically increasing, we can simply simulate the moving window by removing hits that are no longer within the last 300 seconds for a given timestamp.

1. Implement the `HitCounter` class with a queue-like data structure (e.g., `deque`, `queue`, `list`, `linkedlist`)
2. For `hit(timestamp)`, add the timestamp to the tail of the queue.
3. For `getHits(timestamp)`, iterate through the timestamps from the head of the queue and remove any timestamp that is not within the last 300 seconds (i.e., <= current_timestamp - 300). Then return the number of timestamps left in the queue (i.e., the size of the queue).

There is no difference in terms of algorithm between the four languages. They all follow the same logic which is based on the explanation above. Some minor differences include the syntax and how certain operations are done, but the core logic remains the same.

## A solution in Javascript

```javascript
class HitCounter {
  constructor() {
    this.queue = [];
  }

  hit(timestamp) {
    this.queue.push(timestamp);
  }

  getHits(timestamp) {
    while (this.queue.length > 0 && this.queue[0] <= timestamp - 300) {
      this.queue.shift();
    }
    return this.queue.length;
  }
}
```
The key to solving this problem is maintaining a queue with hit timestamps. Since the timestamps are monotonically increasing, we can simply simulate the moving window by removing hits that are no longer within the last 300 seconds for a given timestamp.

1. Implement the `HitCounter` class with a queue-like data structure (e.g., `deque`, `queue`, `list`, `linkedlist`)
2. For `hit(timestamp)`, add the timestamp to the tail of the queue.
3. For `getHits(timestamp)`, iterate through the timestamps from the head of the queue and remove any timestamp that is not within the last 300 seconds (i.e., <= current_timestamp - 300). Then return the number of timestamps left in the queue (i.e., the size of the queue).

There is no difference in terms of algorithm between the four languages. They all follow the same logic which is based on the explanation above. Some minor differences include the syntax and how certain operations are done, but the core logic remains the same.


# Max Sum of Rectangle No Larger Than K

- slug: max-sum-of-rectangle-no-larger-than-k
- difficulty: Hard

Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`.

It is **guaranteed** that there will be a rectangle with a sum no larger than `k`.

**Example 1:**

**Input:** matrix = \[\[1,0,1\],\[0,-2,3\]\], k = 2
**Output:** 2
**Explanation:** Because the sum of the blue rectangle \[\[0, 1\], \[-2, 3\]\] is 2, and 2 is the max number no larger than k (k = 2).

**Example 2:**

**Input:** matrix = \[\[2,2,-1\]\], k = 3
**Output:** 3

**Constraints:**

*   `m == matrix.length`
*   `n == matrix[i].length`
*   `1 <= m, n <= 100`
*   `-100 <= matrix[i][j] <= 100`
*   `-105 <= k <= 105`

**Follow up:** What if the number of rows is much larger than the number of columns?

## A solution in Java

```java
import java.util.TreeSet;

public int maxSumSubmatrix(int[][] matrix, int k) {
    int rows = matrix.length;
    int cols = matrix[0].length;
    int maxSum = Integer.MIN_VALUE;

    for (int l = 0; l < cols; ++l) {
        int[] sums = new int[rows];
        for (int r = l; r < cols; ++r) {
            for (int i = 0; i < rows; ++i) {
                sums[i] += matrix[i][r];
            }

            TreeSet<Integer> sortedSums = new TreeSet<>();
            sortedSums.add(0);
            int currSum = 0;
            for (int sum : sums) {
                currSum += sum;
                Integer it = sortedSums.ceiling(currSum - k);
                if (it != null)
                    maxSum = Math.max(maxSum, currSum - it);
                sortedSums.add(currSum);
            }
        }
    }

    return maxSum;
}
```
1. Initialize variables to iterate over all possible column pairs (left and right).
2. For each column pair, calculate the cumulative sum of elements within the column range for each row.
3. Initialize a sorted set (e.g., `set` in C++, `TreeSet` in Java, `SortedList` in Python, and an array in JavaScript) to store the prefix sums.
4. Iterate through the cumulative sums, updating the current sum and finding the lower bound of (currSum - k) in the sorted set.
5. If the iterator is not pointing to the end, update the maxSum using the current sum minus the value pointed by the iterator.
6. Insert the current sum into the sorted set.
7. After all iterations are done, return the maxSum.

## A solution in C++

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

int maxSumSubmatrix(std::vector<std::vector<int>>& matrix, int k) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    int maxSum = INT_MIN;

    for (int l = 0; l < cols; ++l) {
        std::vector<int> sums(rows, 0);
        for (int r = l; r < cols; ++r) {
            for (int i = 0; i < rows; ++i) {
                sums[i] += matrix[i][r];
            }

            std::set<int> sortedSums;
            sortedSums.insert(0);
            int currSum = 0;
            for (int sum : sums) {
                currSum += sum;
                auto it = sortedSums.lower_bound(currSum - k);
                if (it != sortedSums.end())
                    maxSum = std::max(maxSum, currSum - *it);
                sortedSums.insert(currSum);
            }
        }
    }

    return maxSum;
}
```
1. Initialize variables to iterate over all possible column pairs (left and right).
2. For each column pair, calculate the cumulative sum of elements within the column range for each row.
3. Initialize a sorted set (e.g., `set` in C++, `TreeSet` in Java, `SortedList` in Python, and an array in JavaScript) to store the prefix sums.
4. Iterate through the cumulative sums, updating the current sum and finding the lower bound of (currSum - k) in the sorted set.
5. If the iterator is not pointing to the end, update the maxSum using the current sum minus the value pointed by the iterator.
6. Insert the current sum into the sorted set.
7. After all iterations are done, return the maxSum.

## A solution in Python

```python
from sortedcontainers import SortedList

def maxSumSubmatrix(matrix, k):
    rows = len(matrix)
    cols = len(matrix[0])
    max_sum = float('-inf')

    for l in range(cols):
        sums = [0] * rows
        for r in range(l, cols):
            for i in range(rows):
                sums[i] += matrix[i][r]

            sorted_sums = SortedList()
            sorted_sums.add(0)
            curr_sum = 0
            for sum in sums:
                curr_sum += sum
                it = sorted_sums.bisect_left(curr_sum - k)
                if it != len(sorted_sums):
                    max_sum = max(max_sum, curr_sum - sorted_sums[it])
                sorted_sums.add(curr_sum)

    return max_sum
```
1. Initialize variables to iterate over all possible column pairs (left and right).
2. For each column pair, calculate the cumulative sum of elements within the column range for each row.
3. Initialize a sorted set (e.g., `set` in C++, `TreeSet` in Java, `SortedList` in Python, and an array in JavaScript) to store the prefix sums.
4. Iterate through the cumulative sums, updating the current sum and finding the lower bound of (currSum - k) in the sorted set.
5. If the iterator is not pointing to the end, update the maxSum using the current sum minus the value pointed by the iterator.
6. Insert the current sum into the sorted set.
7. After all iterations are done, return the maxSum.

## A solution in Javascript

```javascript
function maxSumSubmatrix(matrix, k) {
    const rows = matrix.length;
    const cols = matrix[0].length;
    let maxSum = -Infinity;

    function lowerBound(arr, target) {
        let l = 0;
        let r = arr.length;
        while (l < r) {
            const mid = Math.floor((l + r) / 2);
            if (arr[mid] >= target) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        return l;
    }

    for (let l = 0; l < cols; ++l) {
        const sums = Array(rows).fill(0);
        for (let r = l; r < cols; ++r) {
            for (let i = 0; i < rows; ++i) {
                sums[i] += matrix[i][r];
            }

            const sortedSums = [0];
            let currSum = 0;
            for (const sum of sums) {
                currSum += sum;
                const it = lowerBound(sortedSums, currSum - k);
                if (it < sortedSums.length)
                    maxSum = Math.max(maxSum, currSum - sortedSums[it]);
                const insertPosition = lowerBound(sortedSums, currSum);
                sortedSums.splice(insertPosition, 0, currSum);
            }
        }
    }

    return maxSum;
}
```
1. Initialize variables to iterate over all possible column pairs (left and right).
2. For each column pair, calculate the cumulative sum of elements within the column range for each row.
3. Initialize a sorted set (e.g., `set` in C++, `TreeSet` in Java, `SortedList` in Python, and an array in JavaScript) to store the prefix sums.
4. Iterate through the cumulative sums, updating the current sum and finding the lower bound of (currSum - k) in the sorted set.
5. If the iterator is not pointing to the end, update the maxSum using the current sum minus the value pointed by the iterator.
6. Insert the current sum into the sorted set.
7. After all iterations are done, return the maxSum.


# Nested List Weight Sum II

- slug: nested-list-weight-sum-ii
- difficulty: Medium

You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists.

The **depth** of an integer is the number of lists that it is inside of. For example, the nested list `[1,[2,2],[[3],2],1]` has each integer's value set to its **depth**. Let `maxDepth` be the **maximum depth** of any integer.

The **weight** of an integer is `maxDepth - (the depth of the integer) + 1`.

Return _the sum of each integer in_ `nestedList` _multiplied by its **weight**_.

**Example 1:**

**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** 8
**Explanation:** Four 1's with a weight of 1, one 2 with a weight of 2.
1\*1 + 1\*1 + 2\*2 + 1\*1 + 1\*1 = 8

**Example 2:**

**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** 17
**Explanation:** One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1.
1\*3 + 4\*2 + 6\*1 = 17

**Constraints:**

*   `1 <= nestedList.length <= 50`
*   The values of the integers in the nested list is in the range `[-100, 100]`.
*   The maximum **depth** of any integer is less than or equal to `50`.

## A solution in Java

```java
import java.util.*;

public int depthSumInverse(List<NestedInteger> nestedList) {
    int maxDepth = maxDepth(nestedList);
    return sumHelper(nestedList, maxDepth);
}

private int maxDepth(List<NestedInteger> nestedList) {
    int depth = 1;
    for (NestedInteger nested : nestedList) {
        if (!nested.isInteger()) {
            depth = Math.max(depth, 1 + maxDepth(nested.getList()));
        }
    }
    return depth;
}

private int sumHelper(List<NestedInteger> nestedList, int depth) {
    int sum = 0;
    for (NestedInteger nested : nestedList) {
        if (nested.isInteger()) {
            sum += depth * nested.getInteger();
        } else {
            sum += sumHelper(nested.getList(), depth - 1);
        }
    }
    return sum;
}
```
1. First, we find the maximum depth of the integers in the input nestedList using a helper function maxDepthHelper by recursively going through all elements in nestedList. For every sublist encountered, we update the depth to the maximum depth found so far.
2. Then, we compute the weighted sum of all integers in the nestedList by calling another helper function sumHelper. sumHelper goes through every element in nestedList and, for each integer, it calculates the weighted sum by multiplying the integer value with its corresponding weight (which is maxDepth - currentDepth + 1).
3. Finally, the main function returns the total weighted sum obtained in the previous step.

Time complexity: O(N) where N is the total number of elements (integers and nested lists) in the input nestedList. In each recursive call, we process a single element.
Space complexity: O(D) where D is the maximum depth of integers found in the nestedList. This is for the recursive call stack.

## A solution in C++

```cpp
#include <variant>
#include <vector>

using NestedInteger = std::variant<int, std::vector<std::variant<int, std::vector<NestedInteger>>>>;

int sumHelper(NestedInteger& nested, int depth) {
    int sum = 0;
    if (auto pInt = std::get_if<int>(&nested)) {
        sum += depth * (*pInt);
    } else {
        auto& list = std::get<std::vector<NestedInteger>>(nested);
        for (auto& element : list) {
            sum += sumHelper(element, depth - 1);
        }
    }
    return sum;
}

int maxDepth(NestedInteger& nested) {
    if (std::holds_alternative<int>(nested)) return 0;
    int depth = 1;
    for (auto& element : std::get<std::vector<NestedInteger>>(nested)) {
        depth = std::max(depth, 1 + maxDepth(element));
    }
    return depth;
}

int depthSumInverse(std::vector<NestedInteger>& nestedList) {
    int max_depth = 1;
    for (auto& nested : nestedList) {
        max_depth = std::max(max_depth, 1 + maxDepth(nested));
    }
    int sum = 0;
    for (auto& nested : nestedList) {
        sum += sumHelper(nested, max_depth);
    }
    return sum;
}
```
1. First, we find the maximum depth of the integers in the input nestedList using a helper function maxDepthHelper by recursively going through all elements in nestedList. For every sublist encountered, we update the depth to the maximum depth found so far.
2. Then, we compute the weighted sum of all integers in the nestedList by calling another helper function sumHelper. sumHelper goes through every element in nestedList and, for each integer, it calculates the weighted sum by multiplying the integer value with its corresponding weight (which is maxDepth - currentDepth + 1).
3. Finally, the main function returns the total weighted sum obtained in the previous step.

Time complexity: O(N) where N is the total number of elements (integers and nested lists) in the input nestedList. In each recursive call, we process a single element.
Space complexity: O(D) where D is the maximum depth of integers found in the nestedList. This is for the recursive call stack.

## A solution in Python

```python
from typing import List, Union

NestedInteger = Union[int, List[Union[int, "NestedInteger"]]]

def depthSumInverse(nestedList: List[NestedInteger]) -> int:
    max_depth = max_depth_helper(nestedList)
    return sum_helper(nestedList, max_depth)

def max_depth_helper(nested_list: List[NestedInteger]) -> int:
    depth = 1
    for nested in nested_list:
        if isinstance(nested, list):
            depth = max(depth, 1 + max_depth_helper(nested))
    return depth

def sum_helper(nested_list: List[NestedInteger], depth: int) -> int:
    sum = 0
    for nested in nested_list:
        if isinstance(nested, int):
            sum += depth * nested
        else:
            sum += sum_helper(nested, depth - 1)
    return sum
```
1. First, we find the maximum depth of the integers in the input nestedList using a helper function maxDepthHelper by recursively going through all elements in nestedList. For every sublist encountered, we update the depth to the maximum depth found so far.
2. Then, we compute the weighted sum of all integers in the nestedList by calling another helper function sumHelper. sumHelper goes through every element in nestedList and, for each integer, it calculates the weighted sum by multiplying the integer value with its corresponding weight (which is maxDepth - currentDepth + 1).
3. Finally, the main function returns the total weighted sum obtained in the previous step.

Time complexity: O(N) where N is the total number of elements (integers and nested lists) in the input nestedList. In each recursive call, we process a single element.
Space complexity: O(D) where D is the maximum depth of integers found in the nestedList. This is for the recursive call stack.

## A solution in Javascript

```javascript
function depthSumInverse(nestedList) {
    function maxDepthHelper(nestedList) {
        let depth = 1;
        for (let nested of nestedList) {
            if (Array.isArray(nested)) {
                depth = Math.max(depth, 1 + maxDepthHelper(nested));
            }
        }
        return depth;
    }
    function sumHelper(nestedList, depth) {
        let sum = 0;
        for (let nested of nestedList) {
            if (typeof nested === "number") {
                sum += depth * nested;
            } else {
                sum += sumHelper(nested, depth - 1);
            }
        }
        return sum;
    }
    let maxDepth = maxDepthHelper(nestedList);
    return sumHelper(nestedList, maxDepth);
}
```
1. First, we find the maximum depth of the integers in the input nestedList using a helper function maxDepthHelper by recursively going through all elements in nestedList. For every sublist encountered, we update the depth to the maximum depth found so far.
2. Then, we compute the weighted sum of all integers in the nestedList by calling another helper function sumHelper. sumHelper goes through every element in nestedList and, for each integer, it calculates the weighted sum by multiplying the integer value with its corresponding weight (which is maxDepth - currentDepth + 1).
3. Finally, the main function returns the total weighted sum obtained in the previous step.

Time complexity: O(N) where N is the total number of elements (integers and nested lists) in the input nestedList. In each recursive call, we process a single element.
Space complexity: O(D) where D is the maximum depth of integers found in the nestedList. This is for the recursive call stack.


# Water and Jug Problem

- slug: water-and-jug-problem
- difficulty: Medium

You are given two jugs with capacities `jug1Capacity` and `jug2Capacity` liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly `targetCapacity` liters using these two jugs.

If `targetCapacity` liters of water are measurable, you must have `targetCapacity` liters of water contained **within one or both buckets** by the end.

Operations allowed:

*   Fill any of the jugs with water.
*   Empty any of the jugs.
*   Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty.

**Example 1:**

**Input:** jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
**Output:** true
**Explanation:** The famous [Die Hard](https://www.youtube.com/watch?v=BVtQNK_ZUJg&ab_channel=notnek01) example

**Example 2:**

**Input:** jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
**Output:** false

**Example 3:**

**Input:** jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
**Output:** true

**Constraints:**

*   `1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106`

## A solution in Java

```java
public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
    if (targetCapacity > jug1Capacity + jug2Capacity) return false;
    if (jug1Capacity == targetCapacity || jug2Capacity == targetCapacity
        || jug1Capacity + jug2Capacity == targetCapacity) return true;
    return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0;
}

private int gcd(int a, int b) {
    while (b != 0) {
        int tmp = a % b;
        a = b;
        b = tmp;
    }
    return a;
}
```
To measure exactly targetCapacity liters using the two jugs, we need to use their GCD (Greatest Common Divisor). The problem can be solved using the mathematical property that the target capacity should be divisible by the GCD of jug1Capacity and jug2Capacity.

First, we calculate GCD of the two jug capacities.
Then, we check if the target capacity is smaller than or equal to the sum of the two jug capacities. If not, it's impossible to get targetCapacity liters.
Return true if targetCapacity is equal to either of the jug capacities or their sum, as it's achievable without performing any GCD checks.
Then, we simply check if targetCapacity is divisible by the GCD of the two jug capacities, returning true if so.

The algorithm uses a single GCD calculation and a few checks to determine whether it's possible to measure the target capacity or not, making it fast and efficient.

## A solution in C++

```cpp
bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
    if (targetCapacity > jug1Capacity + jug2Capacity) return false;
    if (jug1Capacity == targetCapacity || jug2Capacity == targetCapacity
        || jug1Capacity + jug2Capacity == targetCapacity) return true;
    return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0;
}

int gcd(int a, int b) {
    while (b) {
        int tmp = a % b;
        a = b;
        b = tmp;
    }
    return a;
}
```
To measure exactly targetCapacity liters using the two jugs, we need to use their GCD (Greatest Common Divisor). The problem can be solved using the mathematical property that the target capacity should be divisible by the GCD of jug1Capacity and jug2Capacity.

First, we calculate GCD of the two jug capacities.
Then, we check if the target capacity is smaller than or equal to the sum of the two jug capacities. If not, it's impossible to get targetCapacity liters.
Return true if targetCapacity is equal to either of the jug capacities or their sum, as it's achievable without performing any GCD checks.
Then, we simply check if targetCapacity is divisible by the GCD of the two jug capacities, returning true if so.

The algorithm uses a single GCD calculation and a few checks to determine whether it's possible to measure the target capacity or not, making it fast and efficient.

## A solution in Python

```python
def canMeasureWater(jug1Capacity, jug2Capacity, targetCapacity):
    if targetCapacity > jug1Capacity + jug2Capacity:
        return False
    if jug1Capacity == targetCapacity or jug2Capacity == targetCapacity or jug1Capacity + jug2Capacity == targetCapacity:
        return True
    return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
```
To measure exactly targetCapacity liters using the two jugs, we need to use their GCD (Greatest Common Divisor). The problem can be solved using the mathematical property that the target capacity should be divisible by the GCD of jug1Capacity and jug2Capacity.

First, we calculate GCD of the two jug capacities.
Then, we check if the target capacity is smaller than or equal to the sum of the two jug capacities. If not, it's impossible to get targetCapacity liters.
Return true if targetCapacity is equal to either of the jug capacities or their sum, as it's achievable without performing any GCD checks.
Then, we simply check if targetCapacity is divisible by the GCD of the two jug capacities, returning true if so.

The algorithm uses a single GCD calculation and a few checks to determine whether it's possible to measure the target capacity or not, making it fast and efficient.

## A solution in Javascript

```javascript
function canMeasureWater(jug1Capacity, jug2Capacity, targetCapacity) {
    if (targetCapacity > jug1Capacity + jug2Capacity) return false;
    if (jug1Capacity == targetCapacity || jug2Capacity == targetCapacity
        || jug1Capacity + jug2Capacity == targetCapacity) return true;
    return targetCapacity % gcd(jug1Capacity, jug2Capacity) === 0;
}

function gcd(a, b) {
    while (b) {
        let tmp = a % b;
        a = b;
        b = tmp;
    }
    return a;
}
```
To measure exactly targetCapacity liters using the two jugs, we need to use their GCD (Greatest Common Divisor). The problem can be solved using the mathematical property that the target capacity should be divisible by the GCD of jug1Capacity and jug2Capacity.

First, we calculate GCD of the two jug capacities.
Then, we check if the target capacity is smaller than or equal to the sum of the two jug capacities. If not, it's impossible to get targetCapacity liters.
Return true if targetCapacity is equal to either of the jug capacities or their sum, as it's achievable without performing any GCD checks.
Then, we simply check if targetCapacity is divisible by the GCD of the two jug capacities, returning true if so.

The algorithm uses a single GCD calculation and a few checks to determine whether it's possible to measure the target capacity or not, making it fast and efficient.


# Find Leaves of Binary Tree

- slug: find-leaves-of-binary-tree
- difficulty: Medium

Given the `root` of a binary tree, collect a tree's nodes as if you were doing this:

*   Collect all the leaf nodes.
*   Remove all the leaf nodes.
*   Repeat until the tree is empty.

**Example 1:**

**Input:** root = \[1,2,3,4,5\]
**Output:** \[\[4,5,3\],\[2\],\[1\]\]
Explanation:
\[\[3,5,4\],\[2\],\[1\]\] and \[\[3,4,5\],\[2\],\[1\]\] are also considered correct answers since per each level it does not matter the order on which elements are returned.

**Example 2:**

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

**Constraints:**

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

## A solution in Java

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

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

public List<List<Integer>> findLeaves(TreeNode root) {
    List<List<Integer>> result = new ArrayList<>();
    findLeaves(root, result, 0);
    return result;
}

private int findLeaves(TreeNode node, List<List<Integer>> result, int level) {
    if (node == null) return -1;
    int leftLevel = findLeaves(node.left, result, level + 1);
    int rightLevel = findLeaves(node.right, result, level + 1);
    level = Math.max(leftLevel, rightLevel) + 1;
    if (result.size() <= level) result.add(new ArrayList<>());
    result.get(level).add(node.val);
    return level;
}
```
The algorithm uses a Depth-First Search (DFS) approach to find the leaves at the same level. The algorithm uses a helper function `findLeaves` to recursively traverse the tree.

In each recursive call, the current node is checked for being a leaf node (both left and right children are `null`). If the current node is a leaf, its value is added to the corresponding level of the result vector. If not, the recursion continues for the left and right children. The level variable stores the current level of the leaf node.

The `findLeaves` function runs as long as there are nodes left in the tree. Once all the leaf nodes are collected and removed, the result vector contains the desired output.

## A solution in C++

```cpp
#include <vector>

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

void findLeaves(TreeNode* node, std::vector<std::vector<int>>& result, int& level) {
    if (!node) return;
    if (!node->left && !node->right) {
        if (result.size() <= level) {
            result.push_back(std::vector<int>());
        }
        result[level].push_back(node->val);
        node = nullptr;
        return;
    }
    level++;
    findLeaves(node->left, result, level);
    findLeaves(node->right, result, level);
    level--;
}

std::vector<std::vector<int>> findLeaves(TreeNode* root) {
    std::vector<std::vector<int>> result;
    int level = 0;
    while (root) {
        findLeaves(root, result, level);
        if (!root->left && !root->right) root = nullptr;
    }
    return result;
}
```
The algorithm uses a Depth-First Search (DFS) approach to find the leaves at the same level. The algorithm uses a helper function `findLeaves` to recursively traverse the tree.

In each recursive call, the current node is checked for being a leaf node (both left and right children are `null`). If the current node is a leaf, its value is added to the corresponding level of the result vector. If not, the recursion continues for the left and right children. The level variable stores the current level of the leaf node.

The `findLeaves` function runs as long as there are nodes left in the tree. Once all the leaf nodes are collected and removed, the result vector contains the desired output.

## A solution in Python

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

def find_leaves(node, result, level):
    if not node:
        return -1
    left_level = find_leaves(node.left, result, level + 1)
    right_level = find_leaves(node.right, result, level + 1)
    level = max(left_level, right_level) + 1
    if len(result) <= level:
        result.append([])
    result[level].append(node.val)
    return level

def findLeaves(root):
    result = []
    find_leaves(root, result, 0)
    return result
```
The algorithm uses a Depth-First Search (DFS) approach to find the leaves at the same level. The algorithm uses a helper function `findLeaves` to recursively traverse the tree.

In each recursive call, the current node is checked for being a leaf node (both left and right children are `null`). If the current node is a leaf, its value is added to the corresponding level of the result vector. If not, the recursion continues for the left and right children. The level variable stores the current level of the leaf node.

The `findLeaves` function runs as long as there are nodes left in the tree. Once all the leaf nodes are collected and removed, the result vector contains the desired output.

## A solution in Javascript

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

function findLeaves(root) {
    const result = [];
    findLeavesHelper(root, result, 0);
    return result;
}

function findLeavesHelper(node, result, level) {
    if (node === null) return -1;
    const leftLevel = findLeavesHelper(node.left, result, level + 1);
    const rightLevel = findLeavesHelper(node.right, result, level + 1);
    level = Math.max(leftLevel, rightLevel) + 1;
    if (result.length <= level) result.push([]);
    result[level].push(node.val);
    return level;
}
```
The algorithm uses a Depth-First Search (DFS) approach to find the leaves at the same level. The algorithm uses a helper function `findLeaves` to recursively traverse the tree.

In each recursive call, the current node is checked for being a leaf node (both left and right children are `null`). If the current node is a leaf, its value is added to the corresponding level of the result vector. If not, the recursion continues for the left and right children. The level variable stores the current level of the leaf node.

The `findLeaves` function runs as long as there are nodes left in the tree. Once all the leaf nodes are collected and removed, the result vector contains the desired output.


# Valid Perfect Square

- slug: valid-perfect-square
- difficulty: Easy

Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_.

A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself.

You must not use any built-in library function, such as `sqrt`.

**Example 1:**

**Input:** num = 16
**Output:** true
**Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer.

**Example 2:**

**Input:** num = 14
**Output:** false
**Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer.

**Constraints:**

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

## A solution in Java

```java
boolean isPerfectSquare(int num) {
    if (num < 2) return true;
    long left = 2, right = num / 2, mid, square;
    while (left <= right) {
        mid = left + (right - left) / 2;
        square = mid * mid;
        if (square == num) return true;
        if (square > num) right = mid - 1;
        else left = mid + 1;
    }
    return false;
}
```
The algorithm uses a binary search approach to find the square root of the given number. It starts with left at 2 and right at half of the input number. It calculates the middle value and squares it. If the squared middle value is equal to the input number, the function returns True; the number is a perfect square. If the squared middle value is greater than the input number, it updates the right to mid - 1; otherwise, it updates the left to mid + 1. The function repeats until the left value is greater than the right value. In that case, the function returns False, indicating that the input number is not a perfect square.

## A solution in C++

```cpp
bool isPerfectSquare(int num) {
    if (num < 2) return true;
    long long left = 2, right = num / 2, mid, square;
    while (left <= right) {
        mid = left + (right - left) / 2;
        square = mid * mid;
        if (square == num) return true;
        if (square > num) right = mid - 1;
        else left = mid + 1;
    }
    return false;
}
```
The algorithm uses a binary search approach to find the square root of the given number. It starts with left at 2 and right at half of the input number. It calculates the middle value and squares it. If the squared middle value is equal to the input number, the function returns True; the number is a perfect square. If the squared middle value is greater than the input number, it updates the right to mid - 1; otherwise, it updates the left to mid + 1. The function repeats until the left value is greater than the right value. In that case, the function returns False, indicating that the input number is not a perfect square.

## A solution in Python

```python
def is_perfect_square(num: int) -> bool:
    if num < 2:
        return True
    left, right = 2, num // 2
    while left <= right:
        mid = left + (right - left) // 2
        square = mid * mid
        if square == num:
            return True
        if square > num:
            right = mid - 1
        else:
            left = mid + 1
    return False
```
The algorithm uses a binary search approach to find the square root of the given number. It starts with left at 2 and right at half of the input number. It calculates the middle value and squares it. If the squared middle value is equal to the input number, the function returns True; the number is a perfect square. If the squared middle value is greater than the input number, it updates the right to mid - 1; otherwise, it updates the left to mid + 1. The function repeats until the left value is greater than the right value. In that case, the function returns False, indicating that the input number is not a perfect square.

## A solution in Javascript

```javascript
function isPerfectSquare(num) {
    if (num < 2) return true;
    let left = 2, right = Math.floor(num / 2), mid, square;
    while (left <= right) {
        mid = left + Math.floor((right - left) / 2);
        square = mid * mid;
        if (square === num) return true;
        if (square > num) right = mid - 1;
        else left = mid + 1;
    }
    return false;
}
```
The algorithm uses a binary search approach to find the square root of the given number. It starts with left at 2 and right at half of the input number. It calculates the middle value and squares it. If the squared middle value is equal to the input number, the function returns True; the number is a perfect square. If the squared middle value is greater than the input number, it updates the right to mid - 1; otherwise, it updates the left to mid + 1. The function repeats until the left value is greater than the right value. In that case, the function returns False, indicating that the input number is not a perfect square.


# Largest Divisible Subset

- slug: largest-divisible-subset
- difficulty: Medium

Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:

*   `answer[i] % answer[j] == 0`, or
*   `answer[j] % answer[i] == 0`

If there are multiple solutions, return any of them.

**Example 1:**

**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.

**Example 2:**

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

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `1 <= nums[i] <= 2 * 109`
*   All the integers in `nums` are **unique**.

## A solution in Java

```java
import java.util.*;

public List<Integer> largestDivisibleSubset(int[] nums) {
    Arrays.sort(nums);
    int n = nums.length;
    int[] count = new int[n];
    int[] prev = new int[n];
    int max_idx = 0;
    Arrays.fill(prev, -1);
    Arrays.fill(count, 1);

    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (nums[i] % nums[j] == 0 && count[i] < count[j] + 1) {
                count[i] = count[j] + 1;
                prev[i] = j;
            }
        }
        if (count[max_idx] < count[i]) max_idx = i;
    }

    List<Integer> res = new ArrayList<>();
    for (int i = max_idx; i >= 0; i = prev[i]) {
        res.add(nums[i]);
    }

    return res;
}
```
1. Sort the input array.
2. Initialize two arrays: count and prev, both with the same length as the input array.
   - count will store the length of the largest subsets ending at index i.
   - prev stores the index of the previous element in the largest subset.
3. Initialize max_idx to store the index of the maximum count.
4. Loop through the sorted array, and for each element, compare it with its previous elements.
   - If it is divisible by the previous element, update the count and prev arrays accordingly.
5. After looping and updating the arrays, use max_idx to trace back the elements forming the largest subset.
6. Return the largest subset.

## A solution in C++

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

vector<int> largestDivisibleSubset(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int n = nums.size();
    vector<int> count(n, 1), prev(n, -1), res;
    int max_idx = 0;

    for (int i = 1; i < n; ++i) {
        for (int j = 0; j < i; ++j) {
            if (nums[i] % nums[j] == 0 && count[i] < count[j] + 1) {
                count[i] = count[j] + 1;
                prev[i] = j;
            }
        }
        if (count[max_idx] < count[i]) max_idx = i;
    }

    for (int i = max_idx; i >= 0; i = prev[i]) {
        res.push_back(nums[i]);
    }

    return res;
}
```
1. Sort the input array.
2. Initialize two arrays: count and prev, both with the same length as the input array.
   - count will store the length of the largest subsets ending at index i.
   - prev stores the index of the previous element in the largest subset.
3. Initialize max_idx to store the index of the maximum count.
4. Loop through the sorted array, and for each element, compare it with its previous elements.
   - If it is divisible by the previous element, update the count and prev arrays accordingly.
5. After looping and updating the arrays, use max_idx to trace back the elements forming the largest subset.
6. Return the largest subset.

## A solution in Python

```python
def largestDivisibleSubset(nums):
    nums.sort()
    n = len(nums)
    count = [1] * n
    prev = [-1] * n

    max_idx = 0
    for i in range(1, n):
        for j in range(i):
            if nums[i] % nums[j] == 0 and count[i] < count[j] + 1:
                count[i] = count[j] + 1
                prev[i] = j
        if count[max_idx] < count[i]:
            max_idx = i

    res = []
    i = max_idx
    while i >= 0:
        res.append(nums[i])
        i = prev[i]

    return res
```
1. Sort the input array.
2. Initialize two arrays: count and prev, both with the same length as the input array.
   - count will store the length of the largest subsets ending at index i.
   - prev stores the index of the previous element in the largest subset.
3. Initialize max_idx to store the index of the maximum count.
4. Loop through the sorted array, and for each element, compare it with its previous elements.
   - If it is divisible by the previous element, update the count and prev arrays accordingly.
5. After looping and updating the arrays, use max_idx to trace back the elements forming the largest subset.
6. Return the largest subset.

## A solution in Javascript

```javascript
function largestDivisibleSubset(nums) {
    nums.sort((a, b) => a - b);
    const n = nums.length;
    const count = new Array(n).fill(1);
    const prev = new Array(n).fill(-1);
    let max_idx = 0;

    for (let i = 1; i < n; i++) {
        for (let j = 0; j < i; j++) {
            if (nums[i] % nums[j] === 0 && count[i] < count[j] + 1) {
                count[i] = count[j] + 1;
                prev[i] = j;
            }
        }
        if (count[max_idx] < count[i]) {
            max_idx = i;
        }
    }

    const res = [];
    for (let i = max_idx; i >= 0; i = prev[i]) {
        res.push(nums[i]);
    }

    return res;
}
```
1. Sort the input array.
2. Initialize two arrays: count and prev, both with the same length as the input array.
   - count will store the length of the largest subsets ending at index i.
   - prev stores the index of the previous element in the largest subset.
3. Initialize max_idx to store the index of the maximum count.
4. Loop through the sorted array, and for each element, compare it with its previous elements.
   - If it is divisible by the previous element, update the count and prev arrays accordingly.
5. After looping and updating the arrays, use max_idx to trace back the elements forming the largest subset.
6. Return the largest subset.


# Plus One Linked List

- slug: plus-one-linked-list
- difficulty: Medium

Given a non-negative integer represented as a linked list of digits, _plus one to the integer_.

The digits are stored such that the most significant digit is at the `head` of the list.

**Example 1:**

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

**Example 2:**

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

**Constraints:**

*   The number of nodes in the linked list is in the range `[1, 100]`.
*   `0 <= Node.val <= 9`
*   The number represented by the linked list does not contain leading zeros except for the zero itself.

## A solution in Java

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

public ListNode plusOne(ListNode head) {
    if (head == null) return head;
    int carry = plusOneDfs(head);
    if (carry == 1) {
        ListNode newHead = new ListNode(1);
        newHead.next = head;
        return newHead;
    }
    return head;
}

private int plusOneDfs(ListNode node) {
    if (node == null) return 1;
    int carry = plusOneDfs(node.next);
    if (carry + node.val == 10) {
        node.val = 0;
        return 1;
    } else {
        node.val += carry;
        return 0;
    }
}
```
We define our linked list nodes with a simple struct (in C++) or class (in other languages) with the `val` and `next` attributes. We then perform a postorder depth first search on the linked list to obtain the least significant digit first. When the traversal reaches the end of the list (i.e., current node is NULL or None), it returns an initial carry of 1 as we want to "plus one" to the number. As we return from the recursive call, we add the carry to the current node's value, and if it resulted in a 10, we reset the value to 0 and return carry 1 to the next higher digit. Otherwise, we update the node value and return 0 carry.

If a carry of 1 is left after the traversal of the entire list, we create a new head node with value 1 and link it to the original head as the new most significant digit. Finally, we return our new head node of the linked list.

## A solution in C++

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

ListNode* plusOne(ListNode* head) {
    if (head == NULL) return head;
    if (plusOneDfs(head) == 1) {
        ListNode* newHead = new ListNode(1);
        newHead->next = head;
        return newHead;
    }
    return head;
}

int plusOneDfs(ListNode* node) {
    if (node == NULL) return 1;
    int carry = plusOneDfs(node->next);
    if (carry + node->val == 10) {
        node->val = 0;
        return 1;
    } else {
        node->val += carry;
        return 0;
    }
}
```
We define our linked list nodes with a simple struct (in C++) or class (in other languages) with the `val` and `next` attributes. We then perform a postorder depth first search on the linked list to obtain the least significant digit first. When the traversal reaches the end of the list (i.e., current node is NULL or None), it returns an initial carry of 1 as we want to "plus one" to the number. As we return from the recursive call, we add the carry to the current node's value, and if it resulted in a 10, we reset the value to 0 and return carry 1 to the next higher digit. Otherwise, we update the node value and return 0 carry.

If a carry of 1 is left after the traversal of the entire list, we create a new head node with value 1 and link it to the original head as the new most significant digit. Finally, we return our new head node of the linked list.

## A solution in Python

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

def plusOne(head: ListNode) -> ListNode:
    def plusOneDfs(node):
        if not node:
            return 1
        carry = plusOneDfs(node.next)
        if carry + node.val == 10:
            node.val = 0
            return 1
        else:
            node.val += carry
            return 0

    if not head:
        return head
    carry = plusOneDfs(head)
    if carry == 1:
        new_head = ListNode(1)
        new_head.next = head
        return new_head
    return head
```
We define our linked list nodes with a simple struct (in C++) or class (in other languages) with the `val` and `next` attributes. We then perform a postorder depth first search on the linked list to obtain the least significant digit first. When the traversal reaches the end of the list (i.e., current node is NULL or None), it returns an initial carry of 1 as we want to "plus one" to the number. As we return from the recursive call, we add the carry to the current node's value, and if it resulted in a 10, we reset the value to 0 and return carry 1 to the next higher digit. Otherwise, we update the node value and return 0 carry.

If a carry of 1 is left after the traversal of the entire list, we create a new head node with value 1 and link it to the original head as the new most significant digit. Finally, we return our new head node of the linked list.

## A solution in Javascript

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

function plusOne(head) {
    function plusOneDfs(node) {
        if (!node) return 1;
        const carry = plusOneDfs(node.next);
        if (carry + node.val === 10) {
            node.val = 0;
            return 1;
        } else {
            node.val += carry;
            return 0;
        }
    }

    if (!head) return head;
    const carry = plusOneDfs(head);
    if (carry === 1) {
        const newHead = new ListNode(1);
        newHead.next = head;
        return newHead;
    }
    return head;
}
```
We define our linked list nodes with a simple struct (in C++) or class (in other languages) with the `val` and `next` attributes. We then perform a postorder depth first search on the linked list to obtain the least significant digit first. When the traversal reaches the end of the list (i.e., current node is NULL or None), it returns an initial carry of 1 as we want to "plus one" to the number. As we return from the recursive call, we add the carry to the current node's value, and if it resulted in a 10, we reset the value to 0 and return carry 1 to the next higher digit. Otherwise, we update the node value and return 0 carry.

If a carry of 1 is left after the traversal of the entire list, we create a new head node with value 1 and link it to the original head as the new most significant digit. Finally, we return our new head node of the linked list.


# Range Addition

- slug: range-addition
- difficulty: Medium

You are given an integer `length` and an array `updates` where `updates[i] = [startIdxi, endIdxi, inci]`.

You have an array `arr` of length `length` with all zeros, and you have some operation to apply on `arr`. In the `ith` operation, you should increment all the elements `arr[startIdxi], arr[startIdxi + 1], ..., arr[endIdxi]` by `inci`.

Return `arr` _after applying all the_ `updates`.

**Example 1:**

**Input:** length = 5, updates = \[\[1,3,2\],\[2,4,3\],\[0,2,-2\]\]
**Output:** \[-2,0,3,5,3\]

**Example 2:**

**Input:** length = 10, updates = \[\[2,4,6\],\[5,6,8\],\[1,9,-4\]\]
**Output:** \[0,-4,2,2,2,4,4,-4,-4,-4\]

**Constraints:**

*   `1 <= length <= 105`
*   `0 <= updates.length <= 104`
*   `0 <= startIdxi <= endIdxi < length`
*   `-1000 <= inci <= 1000`

## A solution in Java

```java
public int[] getUpdatedArray(int length, int[][] updates) {
    int[] arr = new int[length];

    for (int[] update : updates) {
        arr[update[0]] += update[2];
        if (update[1] + 1 < length) {
            arr[update[1] + 1] -= update[2];
        }
    }

    for (int i = 1; i < length; i++) {
        arr[i] += arr[i - 1];
    }

    return arr;
}
```
The algorithm starts by initializing an array `arr` of length `length` with all zeros. Then, it iterates over each update and simulates its effect on the array. For every update `[startIdx, endIdx, inc]`, the algorithm increases the value at index `startIdx` by `inc` and decreases the value at index `endIdx + 1` by `inc`, assuming `endIdx + 1` is within the bounds of the array. The reason behind this is that it will later make the algorithm simpler.

After processing all the updates, the actual values of the elements in the array are calculated using cumulative sums. The idea is that, for each element in the array after the first one, the final value is the previous value plus the current value. This will properly include the increments and decrements for each range from the updates.

Finally, the algorithm returns the updated array.

## A solution in C++

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

vector<int> getUpdatedArray(int length, vector<vector<int>>& updates) {
    vector<int> arr(length, 0);

    for (const auto& update : updates) {
        arr[update[0]] += update[2];
        if (update[1] + 1 < length) {
            arr[update[1] + 1] -= update[2];
        }
    }

    for (int i = 1; i < length; i++) {
        arr[i] += arr[i - 1];
    }

    return arr;
}
```
The algorithm starts by initializing an array `arr` of length `length` with all zeros. Then, it iterates over each update and simulates its effect on the array. For every update `[startIdx, endIdx, inc]`, the algorithm increases the value at index `startIdx` by `inc` and decreases the value at index `endIdx + 1` by `inc`, assuming `endIdx + 1` is within the bounds of the array. The reason behind this is that it will later make the algorithm simpler.

After processing all the updates, the actual values of the elements in the array are calculated using cumulative sums. The idea is that, for each element in the array after the first one, the final value is the previous value plus the current value. This will properly include the increments and decrements for each range from the updates.

Finally, the algorithm returns the updated array.

## A solution in Python

```python
def get_updated_array(length, updates):
    arr = [0] * length

    for start, end, inc in updates:
        arr[start] += inc
        if end + 1 < length:
            arr[end + 1] -= inc

    for i in range(1, length):
        arr[i] += arr[i - 1]

    return arr
```
The algorithm starts by initializing an array `arr` of length `length` with all zeros. Then, it iterates over each update and simulates its effect on the array. For every update `[startIdx, endIdx, inc]`, the algorithm increases the value at index `startIdx` by `inc` and decreases the value at index `endIdx + 1` by `inc`, assuming `endIdx + 1` is within the bounds of the array. The reason behind this is that it will later make the algorithm simpler.

After processing all the updates, the actual values of the elements in the array are calculated using cumulative sums. The idea is that, for each element in the array after the first one, the final value is the previous value plus the current value. This will properly include the increments and decrements for each range from the updates.

Finally, the algorithm returns the updated array.

## A solution in Javascript

```javascript
function getUpdatedArray(length, updates) {
    const arr = new Array(length).fill(0);

    for (const [start, end, inc] of updates) {
        arr[start] += inc;
        if (end + 1 < length) {
            arr[end + 1] -= inc;
        }
    }

    for (let i = 1; i < length; i++) {
        arr[i] += arr[i - 1];
    }

    return arr;
}
```
The algorithm starts by initializing an array `arr` of length `length` with all zeros. Then, it iterates over each update and simulates its effect on the array. For every update `[startIdx, endIdx, inc]`, the algorithm increases the value at index `startIdx` by `inc` and decreases the value at index `endIdx + 1` by `inc`, assuming `endIdx + 1` is within the bounds of the array. The reason behind this is that it will later make the algorithm simpler.

After processing all the updates, the actual values of the elements in the array are calculated using cumulative sums. The idea is that, for each element in the array after the first one, the final value is the previous value plus the current value. This will properly include the increments and decrements for each range from the updates.

Finally, the algorithm returns the updated array.


# Sum of Two Integers

- slug: sum-of-two-integers
- difficulty: Medium

Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.

**Example 1:**

**Input:** a = 1, b = 2
**Output:** 3

**Example 2:**

**Input:** a = 2, b = 3
**Output:** 5

**Constraints:**

*   `-1000 <= a, b <= 1000`

## A solution in Java

```java
public int add(int a, int b) {
    while (b != 0) {
        int carry = a & b;
        a = a ^ b;
        b = carry << 1;
    }
    return a;
}
```
The algorithm uses bitwise operations to add the two integers without using + or - operators. The addition process can be divided into two parts: addition without considering a carry and handling the carry generated.

1. XOR (^) can be used for adding without carrying, as it sets the bit at a position if the bits in the two numbers being added are different at that position.
2. AND (&) operation, followed by left shift (<<), is used to find the carry. With this operation, we find the bits which are set in both numbers, and they represent the carry. Then, we shift these bits to the left by one position, which is the correct position of the carry bit.

Finally, we keep looping until there is no carry, at which point we have the sum of the two integers. In the Python implementation, extra steps are required due to the lack of fixed-size integers.

## A solution in C++

```cpp
int add(int a, int b) {
    while (b != 0) {
        int carry = a & b;
        a = a ^ b;
        b = carry << 1;
    }
    return a;
}
```
The algorithm uses bitwise operations to add the two integers without using + or - operators. The addition process can be divided into two parts: addition without considering a carry and handling the carry generated.

1. XOR (^) can be used for adding without carrying, as it sets the bit at a position if the bits in the two numbers being added are different at that position.
2. AND (&) operation, followed by left shift (<<), is used to find the carry. With this operation, we find the bits which are set in both numbers, and they represent the carry. Then, we shift these bits to the left by one position, which is the correct position of the carry bit.

Finally, we keep looping until there is no carry, at which point we have the sum of the two integers. In the Python implementation, extra steps are required due to the lack of fixed-size integers.

## A solution in Python

```python
def add(a, b):
    MAX = 0x7FFFFFFF
    MASK = 0xFFFFFFFF
    while b:
        a, b = (a ^ b) & MASK, ((a & b) << 1) & MASK
    return a if a <= MAX else ~(a ^ MASK)
```
The algorithm uses bitwise operations to add the two integers without using + or - operators. The addition process can be divided into two parts: addition without considering a carry and handling the carry generated.

1. XOR (^) can be used for adding without carrying, as it sets the bit at a position if the bits in the two numbers being added are different at that position.
2. AND (&) operation, followed by left shift (<<), is used to find the carry. With this operation, we find the bits which are set in both numbers, and they represent the carry. Then, we shift these bits to the left by one position, which is the correct position of the carry bit.

Finally, we keep looping until there is no carry, at which point we have the sum of the two integers. In the Python implementation, extra steps are required due to the lack of fixed-size integers.

## A solution in Javascript

```javascript
function add(a, b) {
    while (b) {
        let carry = a & b;
        a = a ^ b;
        b = carry << 1;
    }
    return a;
}
```
The algorithm uses bitwise operations to add the two integers without using + or - operators. The addition process can be divided into two parts: addition without considering a carry and handling the carry generated.

1. XOR (^) can be used for adding without carrying, as it sets the bit at a position if the bits in the two numbers being added are different at that position.
2. AND (&) operation, followed by left shift (<<), is used to find the carry. With this operation, we find the bits which are set in both numbers, and they represent the carry. Then, we shift these bits to the left by one position, which is the correct position of the carry bit.

Finally, we keep looping until there is no carry, at which point we have the sum of the two integers. In the Python implementation, extra steps are required due to the lack of fixed-size integers.


# Super Pow

- slug: super-pow
- difficulty: Medium

Your task is to calculate `ab` mod `1337` where `a` is a positive integer and `b` is an extremely large positive integer given in the form of an array.

**Example 1:**

**Input:** a = 2, b = \[3\]
**Output:** 8

**Example 2:**

**Input:** a = 2, b = \[1,0\]
**Output:** 1024

**Example 3:**

**Input:** a = 1, b = \[4,3,3,8,5,2\]
**Output:** 1

**Constraints:**

*   `1 <= a <= 231 - 1`
*   `1 <= b.length <= 2000`
*   `0 <= b[i] <= 9`
*   `b` does not contain leading zeros.

## A solution in Java

```java
public int powmod(int a, int b) {
    if (b == 0) return 1;
    int res = powmod(a, b / 2);
    if (b % 2 == 0) return res * res % 1337;
    return res * res % 1337 * a % 1337;
}

public int superPow(int a, int[] b) {
    int n = 0;
    for (int bi : b) n = (n * 10 + bi) % 1140;
    return powmod(a % 1337, n + 1140);
}
```
- First, we create a utility `powmod` function to compute `a^b % 1337`. We can do this using the fast exponentiation technique, where for an even power, we recursively compute the square, and for an odd power, we additionally multiply by `a`.
- For the main `superPow` function, we first convert the given array into a single integer `n`. Since, the power could be very large, we can instead calculate `(n % 1140) + 1140`, due to Fermat's Little Theorem and Euler's Theorem: `(a^(λ(n)) ≡ 1 (mod n))` so `a^(1140) % 1337 = 1` where λ is Carmichael function.
- Finally, we call our `powmod` function with `a % 1337` and `(n % 1140) + 1140` as the power.

## A solution in C++

```cpp
int powmod(int a, int b) {
    if (b == 0) return 1;
    int res = powmod(a, b / 2);
    if (b % 2 == 0) return res * res % 1337;
    return res * res % 1337 * a % 1337;
}

int superPow(int a, vector<int>& b) {
    int n = 0;
    for (int bi : b) n = (n * 10 + bi) % 1140;
    return powmod(a % 1337, n + 1140);
}
```
- First, we create a utility `powmod` function to compute `a^b % 1337`. We can do this using the fast exponentiation technique, where for an even power, we recursively compute the square, and for an odd power, we additionally multiply by `a`.
- For the main `superPow` function, we first convert the given array into a single integer `n`. Since, the power could be very large, we can instead calculate `(n % 1140) + 1140`, due to Fermat's Little Theorem and Euler's Theorem: `(a^(λ(n)) ≡ 1 (mod n))` so `a^(1140) % 1337 = 1` where λ is Carmichael function.
- Finally, we call our `powmod` function with `a % 1337` and `(n % 1140) + 1140` as the power.

## A solution in Python

```python
def powmod(a, b):
    if b == 0:
        return 1
    res = powmod(a, b // 2)
    return res * res % 1337 * a % 1337 if b % 2 else res * res % 1337

def superPow(a, b):
    n = 0
    for bi in b:
        n = (n * 10 + bi) % 1140
    return powmod(a % 1337, n + 1140)
```
- First, we create a utility `powmod` function to compute `a^b % 1337`. We can do this using the fast exponentiation technique, where for an even power, we recursively compute the square, and for an odd power, we additionally multiply by `a`.
- For the main `superPow` function, we first convert the given array into a single integer `n`. Since, the power could be very large, we can instead calculate `(n % 1140) + 1140`, due to Fermat's Little Theorem and Euler's Theorem: `(a^(λ(n)) ≡ 1 (mod n))` so `a^(1140) % 1337 = 1` where λ is Carmichael function.
- Finally, we call our `powmod` function with `a % 1337` and `(n % 1140) + 1140` as the power.

## A solution in Javascript

```javascript
function powmod(a, b) {
    if (b === 0) return 1;
    const res = powmod(a, Math.floor(b / 2));
    return b % 2 ? res * res % 1337 * a % 1337 : res * res % 1337;
}

function superPow(a, b) {
    let n = 0;
    for (const bi of b) n = (n * 10 + bi) % 1140;
    return powmod(a % 1337, n + 1140);
}
```
- First, we create a utility `powmod` function to compute `a^b % 1337`. We can do this using the fast exponentiation technique, where for an even power, we recursively compute the square, and for an odd power, we additionally multiply by `a`.
- For the main `superPow` function, we first convert the given array into a single integer `n`. Since, the power could be very large, we can instead calculate `(n % 1140) + 1140`, due to Fermat's Little Theorem and Euler's Theorem: `(a^(λ(n)) ≡ 1 (mod n))` so `a^(1140) % 1337 = 1` where λ is Carmichael function.
- Finally, we call our `powmod` function with `a % 1337` and `(n % 1140) + 1140` as the power.


# Find K Pairs with Smallest Sums

- slug: find-k-pairs-with-smallest-sums
- difficulty: Medium

You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`.

Define a pair `(u, v)` which consists of one element from the first array and one element from the second array.

Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_.

**Example 1:**

**Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3
**Output:** \[\[1,2\],\[1,4\],\[1,6\]\]
**Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\]

**Example 2:**

**Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2
**Output:** \[\[1,1\],\[1,1\]\]
**Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\]

**Example 3:**

**Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3
**Output:** \[\[1,3\],\[2,3\]\]
**Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\]

**Constraints:**

*   `1 <= nums1.length, nums2.length <= 105`
*   `-109 <= nums1[i], nums2[i] <= 109`
*   `nums1` and `nums2` both are sorted in **ascending order**.
*   `1 <= k <= 104`

## A solution in Java

```java
public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
    PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> (a[0] + a[1]) - (b[0] + b[1]));
    List<int[]> result = new ArrayList<>();

    if (nums1.length == 0 || nums2.length == 0 || k == 0) {
        return result;
    }

    for (int i = 0; i < nums1.length && i < k; i++) {
        minHeap.offer(new int[]{nums1[i], nums2[0], 0});
    }

    while (k-- > 0 && !minHeap.isEmpty()) {
        int[] curr = minHeap.poll();
        result.add(new int[]{curr[0], curr[1]});
        if (curr[2] == nums2.length - 1) {
            continue;
        }
        minHeap.offer(new int[]{curr[0], nums2[curr[2] + 1], curr[2] + 1});
    }

    return result;
}
```
The idea is to take advantage of the fact that the input arrays are sorted. We start by adding the first element of nums2 with each element of nums1 into a min heap. In each iteration, we pop the smallest sum from the heap, add it to the result, and then replace this sum with the sum of the same element from nums1 but with the next element from nums2, if there is a next element in nums2.

The comparison function used for the min heap is based on the actual sum of pairs of elements from the given arrays.

All solutions have O(k * log(min(k, m))) time complexity, where m is the length of the first array. This is because there will be at most min(k, m) elements in the min heap, and at most k iterations.

## A solution in C++

```cpp
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
    auto comp = [&nums1, &nums2](pair<int, int> a, pair<int, int> b) {
        return nums1[a.first] + nums2[a.second] > nums1[b.first] + nums2[b.second];
    };
    priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> min_heap(comp);
    vector<vector<int>> result;

    if (nums1.empty() || nums2.empty()) return result;

    for (int i = 0; i < nums1.size(); ++i) {
        min_heap.emplace(i, 0);
    }

    while (k-- && !min_heap.empty()) {
        auto curr = min_heap.top();
        min_heap.pop();
        result.push_back({nums1[curr.first], nums2[curr.second]});
        if (curr.second + 1 < nums2.size()) {
            min_heap.emplace(curr.first, curr.second + 1);
        }
    }
    return result;
}
```
The idea is to take advantage of the fact that the input arrays are sorted. We start by adding the first element of nums2 with each element of nums1 into a min heap. In each iteration, we pop the smallest sum from the heap, add it to the result, and then replace this sum with the sum of the same element from nums1 but with the next element from nums2, if there is a next element in nums2.

The comparison function used for the min heap is based on the actual sum of pairs of elements from the given arrays.

All solutions have O(k * log(min(k, m))) time complexity, where m is the length of the first array. This is because there will be at most min(k, m) elements in the min heap, and at most k iterations.

## A solution in Python

```python
import heapq

def kSmallestPairs(nums1, nums2, k):
    if not nums1 or not nums2:
        return []

    heap = [(nums1[i] + nums2[0], i, 0) for i in range(min(k, len(nums1)))]
    heapq.heapify(heap)
    result = []

    while k > 0 and heap:
        s, i, j = heapq.heappop(heap)
        result.append([nums1[i], nums2[j]])
        if j + 1 < len(nums2):
            heapq.heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1))
        k -= 1

    return result
```
The idea is to take advantage of the fact that the input arrays are sorted. We start by adding the first element of nums2 with each element of nums1 into a min heap. In each iteration, we pop the smallest sum from the heap, add it to the result, and then replace this sum with the sum of the same element from nums1 but with the next element from nums2, if there is a next element in nums2.

The comparison function used for the min heap is based on the actual sum of pairs of elements from the given arrays.

All solutions have O(k * log(min(k, m))) time complexity, where m is the length of the first array. This is because there will be at most min(k, m) elements in the min heap, and at most k iterations.

## A solution in Javascript

```javascript
function kSmallestPairs(nums1, nums2, k) {
    const minHeap = new PriorityQueue(k, (a, b) => a[0] + a[1] - (b[0] + b[1]));
    const result = [];

    if (nums1.length === 0 || nums2.length === 0 || k === 0) {
        return result;
    }

    for (let i = 0; i < nums1.length && i < k; i++) {
        minHeap.offer([nums1[i], nums2[0], 0]);
    }

    while (k-- > 0 && !minHeap.isEmpty()) {
        const curr = minHeap.poll();
        result.push([curr[0], curr[1]]);
        if (curr[2] === nums2.length - 1) {
            continue;
        }
        minHeap.offer([curr[0], nums2[curr[2] + 1], curr[2] + 1]);
    }

    return result;
}
```
The idea is to take advantage of the fact that the input arrays are sorted. We start by adding the first element of nums2 with each element of nums1 into a min heap. In each iteration, we pop the smallest sum from the heap, add it to the result, and then replace this sum with the sum of the same element from nums1 but with the next element from nums2, if there is a next element in nums2.

The comparison function used for the min heap is based on the actual sum of pairs of elements from the given arrays.

All solutions have O(k * log(min(k, m))) time complexity, where m is the length of the first array. This is because there will be at most min(k, m) elements in the min heap, and at most k iterations.