# Maximum Number of Ones

- slug: maximum-number-of-ones
- difficulty: Hard

Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones.

Return the maximum possible number of ones that the matrix `M` can have.

**Example 1:**

**Input:** width = 3, height = 3, sideLength = 2, maxOnes = 1
**Output:** 4
**Explanation:**
In a 3\*3 matrix, no 2\*2 sub-matrix can have more than 1 one.
The best solution that has 4 ones is:
\[1,0,1\]
\[0,0,0\]
\[1,0,1\]

**Example 2:**

**Input:** width = 3, height = 3, sideLength = 2, maxOnes = 2
**Output:** 6
**Explanation:**
\[1,0,1\]
\[1,0,1\]
\[1,0,1\]

**Constraints:**

*   `1 <= width, height <= 100`
*   `1 <= sideLength <= width, height`
*   `0 <= maxOnes <= sideLength * sideLength`

## A solution in Java

```java
public double[] sampleStats(int[] count) {
    double minVal = -1, maxVal = -1, mode = 0, median = 0, mean = 0;
    long totalCount = 0, modeCount = 0, curCount = 0;
    double sum = 0;

    for (int i = 0; i <= 255; i++) {
        if (count[i] > 0) {
            if (minVal == -1) minVal = i;
            maxVal = i;
            sum += (double) i * count[i];
            totalCount += count[i];
            if (count[i] > modeCount) {
                modeCount = count[i];
                mode = i;
            }
        }
    }

    mean = sum / totalCount;
    boolean isEven = (totalCount % 2 == 0);
    long mid1 = totalCount / 2, mid2 = mid1 - 1;
    if (isEven) mid2++;

    for (int i = 0; i <= 255; i++) {
        curCount += count[i];
        if (isEven && curCount >= mid2) {
            median += i;
            mid2 = totalCount;
            isEven = false;
        }

        if (curCount >= mid1) {
            median += i;
            break;
        }
    }

    if (!isEven) median /= 2;
    return new double[]{minVal, maxVal, mean, median, mode};
}
```
The algorithm starts by initializing variables for min, max, mean, mode, and median, as well as some others used for calculations. It then iterates through the count array from 0 to 255. For each value, it updates the min and max values if necessary, calculates the sum of the elements and total count (which will be used to calculate the mean later), and updates the mode if the count for that value is greater than the current mode count.

After the initial loop, the mean is calculated by dividing the sum by the total count. The median is calculated by finding the middle value(s) using the total count. If the total count is even, it will be the average of the two middle values; otherwise, it will be just the middle value. This is done by keeping track of the current count of values visited, and adding the index i to the median whenever any of the middle values are reached. The median is then divided by 2 if there was only one middle value, to account for the fact that it was added twice during the median calculation loop.

Finally, the results are returned in an array with the format [minimum, maximum, mean, median, mode].

## A solution in C++

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

std::vector<double> sampleStats(std::vector<int>& count) {
    double minVal = -1, maxVal = -1, mode = 0, median = 0, mean = 0;
    long long totalCount = 0, modeCount = 0, curCount = 0;
    double sum = 0;

    for (int i = 0; i <= 255; i++) {
        if (count[i] > 0) {
            if (minVal == -1) minVal = i;
            maxVal = i;
            sum += static_cast<double>(i) * count[i];
            totalCount += count[i];
            if (count[i] > modeCount) {
                modeCount = count[i];
                mode = i;
            }
        }
    }

    mean = sum / totalCount;
    bool isEven = (totalCount % 2 == 0);
    long long mid1 = totalCount / 2, mid2 = mid1 - 1;
    if (isEven) mid2++;

    for (int i = 0; i <= 255; i++) {
        curCount += count[i];
        if (isEven && curCount >= mid2) {
            median += i;
            mid2 = totalCount;
            isEven = false;
        }

        if (curCount >= mid1) {
            median += i;
            break;
        }
    }

    if (!isEven) median /= 2;
    return {minVal, maxVal, mean, median, mode};
}
```
The algorithm starts by initializing variables for min, max, mean, mode, and median, as well as some others used for calculations. It then iterates through the count array from 0 to 255. For each value, it updates the min and max values if necessary, calculates the sum of the elements and total count (which will be used to calculate the mean later), and updates the mode if the count for that value is greater than the current mode count.

After the initial loop, the mean is calculated by dividing the sum by the total count. The median is calculated by finding the middle value(s) using the total count. If the total count is even, it will be the average of the two middle values; otherwise, it will be just the middle value. This is done by keeping track of the current count of values visited, and adding the index i to the median whenever any of the middle values are reached. The median is then divided by 2 if there was only one middle value, to account for the fact that it was added twice during the median calculation loop.

Finally, the results are returned in an array with the format [minimum, maximum, mean, median, mode].

## A solution in Python

```python
def sampleStats(count):
    minVal, maxVal, mode, median, mean = -1, -1, 0, 0, 0
    totalCount, modeCount, curCount = 0, 0, 0
    sum = 0

    for i in range(256):
        if count[i] > 0:
            if minVal == -1:
                minVal = i
            maxVal = i
            sum += i * count[i]
            totalCount += count[i]
            if count[i] > modeCount:
                modeCount = count[i]
                mode = i

    mean = sum / totalCount
    isEven = (totalCount % 2 == 0)
    mid1 = totalCount // 2
    mid2 = mid1 - 1
    if isEven:
        mid2 += 1

    for i in range(256):
        curCount += count[i]
        if isEven and curCount >= mid2:
            median += i
            mid2 = totalCount
            isEven = False

        if curCount >= mid1:
            median += i
            break

    if not isEven:
        median /= 2
    return [minVal, maxVal, mean, median, mode]
```
The algorithm starts by initializing variables for min, max, mean, mode, and median, as well as some others used for calculations. It then iterates through the count array from 0 to 255. For each value, it updates the min and max values if necessary, calculates the sum of the elements and total count (which will be used to calculate the mean later), and updates the mode if the count for that value is greater than the current mode count.

After the initial loop, the mean is calculated by dividing the sum by the total count. The median is calculated by finding the middle value(s) using the total count. If the total count is even, it will be the average of the two middle values; otherwise, it will be just the middle value. This is done by keeping track of the current count of values visited, and adding the index i to the median whenever any of the middle values are reached. The median is then divided by 2 if there was only one middle value, to account for the fact that it was added twice during the median calculation loop.

Finally, the results are returned in an array with the format [minimum, maximum, mean, median, mode].

## A solution in Javascript

```javascript
function sampleStats(count) {
    let minVal = -1, maxVal = -1, mode = 0, median = 0, mean = 0;
    let totalCount = 0, modeCount = 0, curCount = 0;
    let sum = 0;

    for (let i = 0; i <= 255; i++) {
        if (count[i] > 0) {
            if (minVal === -1) minVal = i;
            maxVal = i;
            sum += i * count[i];
            totalCount += count[i];
            if (count[i] > modeCount) {
                modeCount = count[i];
                mode = i;
            }
        }
    }

    mean = sum / totalCount;
    let isEven = (totalCount % 2 === 0);
    let mid1 = Math.floor(totalCount / 2), mid2 = mid1 - 1;
    if (isEven) mid2++;

    for (let i = 0; i <= 255; i++) {
        curCount += count[i];
        if (isEven && curCount >= mid2) {
            median += i;
            mid2 = totalCount;
            isEven = false;
        }

        if (curCount >= mid1) {
            median += i;
            break;
        }
    }

    if (!isEven) median /= 2;
    return [minVal, maxVal, mean, median, mode];
}
```
The algorithm starts by initializing variables for min, max, mean, mode, and median, as well as some others used for calculations. It then iterates through the count array from 0 to 255. For each value, it updates the min and max values if necessary, calculates the sum of the elements and total count (which will be used to calculate the mean later), and updates the mode if the count for that value is greater than the current mode count.

After the initial loop, the mean is calculated by dividing the sum by the total count. The median is calculated by finding the middle value(s) using the total count. If the total count is even, it will be the average of the two middle values; otherwise, it will be just the middle value. This is done by keeping track of the current count of values visited, and adding the index i to the median whenever any of the middle values are reached. The median is then divided by 2 if there was only one middle value, to account for the fact that it was added twice during the median calculation loop.

Finally, the results are returned in an array with the format [minimum, maximum, mean, median, mode].


# Distance Between Bus Stops

- slug: distance-between-bus-stops
- difficulty: Easy

A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.

The bus goes along both directions i.e. clockwise and counterclockwise.

Return the shortest distance between the given `start` and `destination` stops.

**Example 1:**

**Input:** distance = \[1,2,3,4\], start = 0, destination = 1
**Output:** 1
**Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1.

**Example 2:**

**Input:** distance = \[1,2,3,4\], start = 0, destination = 2
**Output:** 3
**Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3.

**Example 3:**

**Input:** distance = \[1,2,3,4\], start = 0, destination = 3
**Output:** 4
**Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4.

**Constraints:**

*   `1 <= n <= 10^4`
*   `distance.length == n`
*   `0 <= start, destination < n`
*   `0 <= distance[i] <= 10^4`

## A solution in Java

```java
import java.util.Map;
import java.util.TreeMap;

public boolean carPooling(int[][] trips, int capacity) {
    Map<Integer, Integer> stops = new TreeMap<>();
    for (int[] t : trips) {
        stops.put(t[1], stops.getOrDefault(t[1], 0) + t[0]);
        stops.put(t[2], stops.getOrDefault(t[2], 0) - t[0]);
    }
    for (int passengers : stops.values()) {
        capacity -= passengers;
        if (capacity < 0) {
            return false;
        }
    }
    return true;
}
```
1. Create an array `stops` of size 1001 (as locations are from 0 to 1000), initialized with zeros.
2. Iterate through the `trips` array, and for each trip, add `numPassengers` to the `from` index and subtract `numPassengers` from the `to` index in the `stops` array. This will represent the number of passengers to pick up (positive value) or drop off (negative value) at each location.
3. Iterate through the `stops` array, and for each location, update the `capacity` by subtracting the number of passengers at that location. If the capacity becomes negative at any point, return `false`.
4. If we have iterated through all the locations in the `stops` array without the capacity becoming negative, return `true`. This means it's possible to pick up and drop off all passengers for all the given trips.

## A solution in C++

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

bool carPooling(std::vector<std::vector<int>>& trips, int capacity) {
    std::vector<int> stops(1001, 0);
    for (const std::vector<int>& t : trips) {
        stops[t[1]] += t[0];
        stops[t[2]] -= t[0];
    }
    for (int i = 0; i < stops.size(); ++i) {
        capacity -= stops[i];
        if (capacity < 0) {
            return false;
        }
    }
    return true;
}
```
1. Create an array `stops` of size 1001 (as locations are from 0 to 1000), initialized with zeros.
2. Iterate through the `trips` array, and for each trip, add `numPassengers` to the `from` index and subtract `numPassengers` from the `to` index in the `stops` array. This will represent the number of passengers to pick up (positive value) or drop off (negative value) at each location.
3. Iterate through the `stops` array, and for each location, update the `capacity` by subtracting the number of passengers at that location. If the capacity becomes negative at any point, return `false`.
4. If we have iterated through all the locations in the `stops` array without the capacity becoming negative, return `true`. This means it's possible to pick up and drop off all passengers for all the given trips.

## A solution in Python

```python
def carPooling(trips, capacity):
    stops = [0] * 1001
    for num, start, end in trips:
        stops[start] += num
        stops[end] -= num
    for i in stops:
        capacity -= i
        if capacity < 0:
            return False
    return True
```
1. Create an array `stops` of size 1001 (as locations are from 0 to 1000), initialized with zeros.
2. Iterate through the `trips` array, and for each trip, add `numPassengers` to the `from` index and subtract `numPassengers` from the `to` index in the `stops` array. This will represent the number of passengers to pick up (positive value) or drop off (negative value) at each location.
3. Iterate through the `stops` array, and for each location, update the `capacity` by subtracting the number of passengers at that location. If the capacity becomes negative at any point, return `false`.
4. If we have iterated through all the locations in the `stops` array without the capacity becoming negative, return `true`. This means it's possible to pick up and drop off all passengers for all the given trips.

## A solution in Javascript

```javascript
function carPooling(trips, capacity) {
    const stops = new Array(1001).fill(0);
    for (const [num, start, end] of trips) {
        stops[start] += num;
        stops[end] -= num;
    }
    for (const passengers of stops) {
        capacity -= passengers;
        if (capacity < 0) {
            return false;
        }
    }
    return true;
}
```
1. Create an array `stops` of size 1001 (as locations are from 0 to 1000), initialized with zeros.
2. Iterate through the `trips` array, and for each trip, add `numPassengers` to the `from` index and subtract `numPassengers` from the `to` index in the `stops` array. This will represent the number of passengers to pick up (positive value) or drop off (negative value) at each location.
3. Iterate through the `stops` array, and for each location, update the `capacity` by subtracting the number of passengers at that location. If the capacity becomes negative at any point, return `false`.
4. If we have iterated through all the locations in the `stops` array without the capacity becoming negative, return `true`. This means it's possible to pick up and drop off all passengers for all the given trips.


# Day of the Week

- slug: day-of-the-week
- difficulty: Easy

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the `day`, `month` and `year` respectively.

Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.

**Example 1:**

**Input:** day = 31, month = 8, year = 2019
**Output:**  "Saturday "

**Example 2:**

**Input:** day = 18, month = 7, year = 1999
**Output:**  "Sunday "

**Example 3:**

**Input:** day = 15, month = 8, year = 1993
**Output:**  "Sunday "

**Constraints:**

*   The given dates are valid dates between the years `1971` and `2100`.

## A solution in Java

```java
import java.time.LocalDate;

public String dayOfTheWeek(int day, int month, int year) {
    LocalDate date = LocalDate.of(year, month, day);
    int dayOfWeekIndex = date.getDayOfWeek().getValue() % 7;
    String[] days = {"Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "};
    return days[dayOfWeekIndex];
}
```
The algorithm calculates the day of the week based on the given day, month, and year. For the C++ implementation, we implement the calculation of days since the year 1971 and then use the modulus operator to determine the day of the week. For Java, Python, and JavaScript implementations, we take advantage of built-in date libraries (LocalDate, datetime, and Date respectively) to calculate the day of the week. All implementations use a string array `days[]` to get the correct day of the week as the output.

## A solution in C++

```cpp
#include <string>

std::string dayOfTheWeek(int day, int month, int year) {
    int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    std::string week[] = {"Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "};
    if (year < 1971) year += (1971 - year) / 400 * 400;
    int sum = -1;
    for (int i = 1971; i < year; ++i) {
        sum += 365;
        if (i % 4 == 0 && (i % 100 != 0 || i % 400 == 0)) ++sum;
    }
    for (int i = 1; i < month; ++i) {
        sum += days[i];
        if (i == 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ++sum;
    }
    return week[(sum + day) % 7];
}
```
The algorithm calculates the day of the week based on the given day, month, and year. For the C++ implementation, we implement the calculation of days since the year 1971 and then use the modulus operator to determine the day of the week. For Java, Python, and JavaScript implementations, we take advantage of built-in date libraries (LocalDate, datetime, and Date respectively) to calculate the day of the week. All implementations use a string array `days[]` to get the correct day of the week as the output.

## A solution in Python

```python
def day_of_the_week(day, month, year):
    from datetime import date
    days = ["Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "]
    return days[date(year, month, day).weekday()]
```
The algorithm calculates the day of the week based on the given day, month, and year. For the C++ implementation, we implement the calculation of days since the year 1971 and then use the modulus operator to determine the day of the week. For Java, Python, and JavaScript implementations, we take advantage of built-in date libraries (LocalDate, datetime, and Date respectively) to calculate the day of the week. All implementations use a string array `days[]` to get the correct day of the week as the output.

## A solution in Javascript

```javascript
function dayOfTheWeek(day, month, year) {
    let days = ["Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "];
    let date = new Date(year, month - 1, day);
    return days[date.getDay()];
}
```
The algorithm calculates the day of the week based on the given day, month, and year. For the C++ implementation, we implement the calculation of days since the year 1971 and then use the modulus operator to determine the day of the week. For Java, Python, and JavaScript implementations, we take advantage of built-in date libraries (LocalDate, datetime, and Date respectively) to calculate the day of the week. All implementations use a string array `days[]` to get the correct day of the week as the output.


# Maximum Subarray Sum with One Deletion

- slug: maximum-subarray-sum-with-one-deletion
- difficulty: Medium

Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.

Note that the subarray needs to be **non-empty** after deleting one element.

**Example 1:**

**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.

**Example 2:**

**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.

**Example 3:**

**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.

**Constraints:**

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

## A solution in Java

```java
import java.util.concurrent.Semaphore;

class H2O {
    private Semaphore hydrogenSemaphore = new Semaphore(2);
    private Semaphore oxygenSemaphore = new Semaphore(1);

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
        hydrogenSemaphore.acquire();
        releaseHydrogen.run();
        oxygenSemaphore.release();
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        oxygenSemaphore.acquire();
        releaseOxygen.run();
        hydrogenSemaphore.release(2);
    }
}
```
In the synchronization solution, we use semaphores to ensure that a group of three threads containing one oxygen and two hydrogen threads pass through the barriers. In this problem, we use two semaphores, `hydrogenSemaphore` and `oxygenSemaphore`.

We initialize the `hydrogenSemaphore` with an initial value of 2 since we need two hydrogen threads for each water molecule, this semaphore allows us to control the access for the hydrogen threads. Similarly, we initialize the `oxygenSemaphore` with an initial value of 1, to control access to the oxygen thread.

For the hydrogen function, we do the following:
- Acquire hydrogen semaphore.
- Release hydrogen.
- Release oxygen semaphore.

For the oxygen function, we do the following:
- Acquire oxygen semaphore.
- Release oxygen.
- Release hydrogen semaphore by 2 to allow the next two hydrogen threads.

By using both semaphores, we ensure that the threads pass through the barriers in complete sets of water molecules. With this approach, we control the flow of hydrogen and oxygen threads and allow them to pass the barriers in complete groups.

## A solution in C++

```cpp
#include <semaphore.h>

class H2O {
public:
    sem_t hydrogenSemaphore;
    sem_t oxygenSemaphore;

    H2O() {
        sem_init(&hydrogenSemaphore, 0, 2);
        sem_init(&oxygenSemaphore, 0, 1);
    }

    void hydrogen(function<void()> releaseHydrogen) {
        sem_wait(&hydrogenSemaphore);
        releaseHydrogen();
        sem_post(&oxygenSemaphore);
    }

    void oxygen(function<void()> releaseOxygen) {
        sem_wait(&oxygenSemaphore);
        releaseOxygen();
        sem_post(&hydrogenSemaphore);
        sem_post(&hydrogenSemaphore);
    }
};
```
In the synchronization solution, we use semaphores to ensure that a group of three threads containing one oxygen and two hydrogen threads pass through the barriers. In this problem, we use two semaphores, `hydrogenSemaphore` and `oxygenSemaphore`.

We initialize the `hydrogenSemaphore` with an initial value of 2 since we need two hydrogen threads for each water molecule, this semaphore allows us to control the access for the hydrogen threads. Similarly, we initialize the `oxygenSemaphore` with an initial value of 1, to control access to the oxygen thread.

For the hydrogen function, we do the following:
- Acquire hydrogen semaphore.
- Release hydrogen.
- Release oxygen semaphore.

For the oxygen function, we do the following:
- Acquire oxygen semaphore.
- Release oxygen.
- Release hydrogen semaphore by 2 to allow the next two hydrogen threads.

By using both semaphores, we ensure that the threads pass through the barriers in complete sets of water molecules. With this approach, we control the flow of hydrogen and oxygen threads and allow them to pass the barriers in complete groups.

## A solution in Python

```python
from threading import Semaphore

class H2O:
    def __init__(self):
        self.hydrogenSemaphore = Semaphore(2)
        self.oxygenSemaphore = Semaphore(1)

    def hydrogen(self, releaseHydrogen):
        self.hydrogenSemaphore.acquire()
        releaseHydrogen()
        self.oxygenSemaphore.release()

    def oxygen(self, releaseOxygen):
        self.oxygenSemaphore.acquire()
        releaseOxygen()
        self.hydrogenSemaphore.release(2)
```
In the synchronization solution, we use semaphores to ensure that a group of three threads containing one oxygen and two hydrogen threads pass through the barriers. In this problem, we use two semaphores, `hydrogenSemaphore` and `oxygenSemaphore`.

We initialize the `hydrogenSemaphore` with an initial value of 2 since we need two hydrogen threads for each water molecule, this semaphore allows us to control the access for the hydrogen threads. Similarly, we initialize the `oxygenSemaphore` with an initial value of 1, to control access to the oxygen thread.

For the hydrogen function, we do the following:
- Acquire hydrogen semaphore.
- Release hydrogen.
- Release oxygen semaphore.

For the oxygen function, we do the following:
- Acquire oxygen semaphore.
- Release oxygen.
- Release hydrogen semaphore by 2 to allow the next two hydrogen threads.

By using both semaphores, we ensure that the threads pass through the barriers in complete sets of water molecules. With this approach, we control the flow of hydrogen and oxygen threads and allow them to pass the barriers in complete groups.

## A solution in Javascript

```javascript
const { Semaphore } = require('await-semaphore');

class H2O {
  constructor() {
    this.hydrogenSemaphore = new Semaphore(2);
    this.oxygenSemaphore = new Semaphore(1);
  }

  async hydrogen(releaseHydrogen) {
    await this.hydrogenSemaphore.acquire();
    releaseHydrogen();
    this.oxygenSemaphore.release();
  }

  async oxygen(releaseOxygen) {
    await this.oxygenSemaphore.acquire();
    releaseOxygen();
    this.hydrogenSemaphore.release(2);
  }
}
```
In the synchronization solution, we use semaphores to ensure that a group of three threads containing one oxygen and two hydrogen threads pass through the barriers. In this problem, we use two semaphores, `hydrogenSemaphore` and `oxygenSemaphore`.

We initialize the `hydrogenSemaphore` with an initial value of 2 since we need two hydrogen threads for each water molecule, this semaphore allows us to control the access for the hydrogen threads. Similarly, we initialize the `oxygenSemaphore` with an initial value of 1, to control access to the oxygen thread.

For the hydrogen function, we do the following:
- Acquire hydrogen semaphore.
- Release hydrogen.
- Release oxygen semaphore.

For the oxygen function, we do the following:
- Acquire oxygen semaphore.
- Release oxygen.
- Release hydrogen semaphore by 2 to allow the next two hydrogen threads.

By using both semaphores, we ensure that the threads pass through the barriers in complete sets of water molecules. With this approach, we control the flow of hydrogen and oxygen threads and allow them to pass the barriers in complete groups.


# Make Array Strictly Increasing

- slug: make-array-strictly-increasing
- difficulty: Hard

Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.

In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.

If there is no way to make `arr1` strictly increasing, return `-1`.

**Example 1:**

**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.

**Example 2:**

**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.

**Example 3:**

**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.

**Constraints:**

*   `1 <= arr1.length, arr2.length <= 2000`
*   `0 <= arr1[i], arr2[i] <= 10^9`

## A solution in Java

```java
import java.util.concurrent.*;

class FooBar {
    private int n;
    private Semaphore fooSemaphore = new Semaphore(1);
    private Semaphore barSemaphore = new Semaphore(0);

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            fooSemaphore.acquire();
            printFoo.run();
            barSemaphore.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            barSemaphore.acquire();
            printBar.run();
            fooSemaphore.release();
        }
    }
}
```
1. In all four languages, a class named FooBar is created. The constructor accepts a single integer argument, `n`, which will be used later for looping purposes.

2. The main challenge is to ensure that functions 'foo' and 'bar' are executed in the correct order ("foobar") `n` times by the two threads simultaneously. The method of synchronization differs in each language implementation.

3. In C++, the implementation uses mutex and condition_variable from the standard library to synchronize the threads. A boolean, `foo_done`, is used to maintain the state of whether the foo function has been executed or not.

4. In Java, semaphores are used to synchronize the threads in the `foo` and `bar` functions. The `acquire()` and `release()` methods of semaphores ensure that the threads wait and proceed in the correct order.

5. In Python, Lock objects from the `threading` library are used to synchronize the two functions. `foo_lock` and `bar_lock` ensure the correct order of execution.

6. In JavaScript, Promises and async/await are used to synchronize the execution of the `foo` and `bar` functions. By using the `await` keyword, the functions wait for each other to complete their execution before progressing, ensuring the correct order.

In all implementations, the goal is to ensure that the 'foo' function is executed before the 'bar' function for `n` iterations in two separate threads, such that the output is "foobar" repeated `n` times.

## A solution in C++

```cpp
#include <mutex>
#include <condition_variable>

class FooBar {
private:
    int n;
    std::mutex mtx;
    std::condition_variable cv;
    bool foo_done = false;

public:
    FooBar(int n) {
        this->n = n;
    }

    void foo(function<void()> printFoo) {
        for (int i = 0; i < n; i++) {
            std::unique_lock<std::mutex> lock(mtx);
            cv.wait(lock, [this]() { return !foo_done; });
            printFoo();
            foo_done = true;
            cv.notify_all();
        }
    }

    void bar(function<void()> printBar) {
        for (int i = 0; i < n; i++) {
            std::unique_lock<std::mutex> lock(mtx);
            cv.wait(lock, [this]() { return foo_done; });
            printBar();
            foo_done = false;
            cv.notify_all();
        }
    }
};
```
1. In all four languages, a class named FooBar is created. The constructor accepts a single integer argument, `n`, which will be used later for looping purposes.

2. The main challenge is to ensure that functions 'foo' and 'bar' are executed in the correct order ("foobar") `n` times by the two threads simultaneously. The method of synchronization differs in each language implementation.

3. In C++, the implementation uses mutex and condition_variable from the standard library to synchronize the threads. A boolean, `foo_done`, is used to maintain the state of whether the foo function has been executed or not.

4. In Java, semaphores are used to synchronize the threads in the `foo` and `bar` functions. The `acquire()` and `release()` methods of semaphores ensure that the threads wait and proceed in the correct order.

5. In Python, Lock objects from the `threading` library are used to synchronize the two functions. `foo_lock` and `bar_lock` ensure the correct order of execution.

6. In JavaScript, Promises and async/await are used to synchronize the execution of the `foo` and `bar` functions. By using the `await` keyword, the functions wait for each other to complete their execution before progressing, ensuring the correct order.

In all implementations, the goal is to ensure that the 'foo' function is executed before the 'bar' function for `n` iterations in two separate threads, such that the output is "foobar" repeated `n` times.

## A solution in Python

```python
from threading import Lock

class FooBar:
    def __init__(self, n: int):
        self.n = n
        self.foo_lock = Lock()
        self.bar_lock = Lock()
        self.bar_lock.acquire()

    def foo(self, printFoo) -> None:
        for _ in range(self.n):
            self.foo_lock.acquire()
            printFoo()
            self.bar_lock.release()

    def bar(self, printBar) -> None:
        for _ in range(self.n):
            self.bar_lock.acquire()
            printBar()
            self.foo_lock.release()
```
1. In all four languages, a class named FooBar is created. The constructor accepts a single integer argument, `n`, which will be used later for looping purposes.

2. The main challenge is to ensure that functions 'foo' and 'bar' are executed in the correct order ("foobar") `n` times by the two threads simultaneously. The method of synchronization differs in each language implementation.

3. In C++, the implementation uses mutex and condition_variable from the standard library to synchronize the threads. A boolean, `foo_done`, is used to maintain the state of whether the foo function has been executed or not.

4. In Java, semaphores are used to synchronize the threads in the `foo` and `bar` functions. The `acquire()` and `release()` methods of semaphores ensure that the threads wait and proceed in the correct order.

5. In Python, Lock objects from the `threading` library are used to synchronize the two functions. `foo_lock` and `bar_lock` ensure the correct order of execution.

6. In JavaScript, Promises and async/await are used to synchronize the execution of the `foo` and `bar` functions. By using the `await` keyword, the functions wait for each other to complete their execution before progressing, ensuring the correct order.

In all implementations, the goal is to ensure that the 'foo' function is executed before the 'bar' function for `n` iterations in two separate threads, such that the output is "foobar" repeated `n` times.

## A solution in Javascript

```javascript
class FooBar {
  constructor(n) {
    this.n = n;
    this.fooPromiseResolver = null;
    this.fooPromise = new Promise((resolve) => (this.fooPromiseResolver = resolve));
    this.barPromiseResolver = null;
    this.barPromise = new Promise((resolve) => (this.barPromiseResolver = resolve));
  }

  async foo(printFoo) {
    for (let i = 0; i < this.n; i++) {
      await this.fooPromise;
      printFoo();
      this.barPromiseResolver();
      this.fooPromise = new Promise((resolve) => (this.fooPromiseResolver = resolve));
    }
  }

  async bar(printBar) {
    for (let i = 0; i < this.n; i++) {
      await this.barPromise;
      printBar();
      this.fooPromiseResolver();
      this.barPromise = new Promise((resolve) => (this.barPromiseResolver = resolve));
    }
  }
}
```
1. In all four languages, a class named FooBar is created. The constructor accepts a single integer argument, `n`, which will be used later for looping purposes.

2. The main challenge is to ensure that functions 'foo' and 'bar' are executed in the correct order ("foobar") `n` times by the two threads simultaneously. The method of synchronization differs in each language implementation.

3. In C++, the implementation uses mutex and condition_variable from the standard library to synchronize the threads. A boolean, `foo_done`, is used to maintain the state of whether the foo function has been executed or not.

4. In Java, semaphores are used to synchronize the threads in the `foo` and `bar` functions. The `acquire()` and `release()` methods of semaphores ensure that the threads wait and proceed in the correct order.

5. In Python, Lock objects from the `threading` library are used to synchronize the two functions. `foo_lock` and `bar_lock` ensure the correct order of execution.

6. In JavaScript, Promises and async/await are used to synchronize the execution of the `foo` and `bar` functions. By using the `await` keyword, the functions wait for each other to complete their execution before progressing, ensuring the correct order.

In all implementations, the goal is to ensure that the 'foo' function is executed before the 'bar' function for `n` iterations in two separate threads, such that the output is "foobar" repeated `n` times.


# Maximum Number of Balloons

- slug: maximum-number-of-balloons
- difficulty: Easy

Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.

You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.

**Example 1:**

**Input:** text =  "nlaebolko "
**Output:** 1

**Example 2:**

**Input:** text =  "loonbalxballpoon "
**Output:** 2

**Example 3:**

**Input:** text =  "leetcode "
**Output:** 0

**Constraints:**

*   `1 <= text.length <= 104`
*   `text` consists of lower case English letters only.

## A solution in Java

```java
public int maxNumberOfBalloons(String text) {
    int[] letter_count = new int[5];
    for (char c : text.toCharArray()) {
        if (c == 'b') letter_count[0]++;
        if (c == 'a') letter_count[1]++;
        if (c == 'l') letter_count[2]++;
        if (c == 'o') letter_count[3]++;
        if (c == 'n') letter_count[4]++;
    }
    letter_count[2] /= 2;
    letter_count[3] /= 2;
    return Arrays.stream(letter_count).min().getAsInt();
}
```
1. First, we initialize an array `letter_count` with a length of 5 to represent each character in the word "balloon".
2. We then loop through each character in the input string `text`.
3. For each character, we increment the corresponding index in the `letter_count` array if it matches one of the characters in the word "balloon".
4. After the loop, we divide the count of 'l' and 'o' by 2 since they appear twice in the word "balloon".
5. Finally, we return the minimum value in the `letter_count` array, which represents the maximum number of instances of the word "balloon" that can be formed.

## A solution in C++

```cpp
int maxNumberOfBalloons(string text) {
    int letter_count[5] = {0};
    for (char c : text) {
        if (c == 'b') letter_count[0]++;
        if (c == 'a') letter_count[1]++;
        if (c == 'l') letter_count[2]++;
        if (c == 'o') letter_count[3]++;
        if (c == 'n') letter_count[4]++;
    }
    letter_count[2] /= 2;
    letter_count[3] /= 2;
    return *min_element(letter_count, letter_count + 5);
}
```
1. First, we initialize an array `letter_count` with a length of 5 to represent each character in the word "balloon".
2. We then loop through each character in the input string `text`.
3. For each character, we increment the corresponding index in the `letter_count` array if it matches one of the characters in the word "balloon".
4. After the loop, we divide the count of 'l' and 'o' by 2 since they appear twice in the word "balloon".
5. Finally, we return the minimum value in the `letter_count` array, which represents the maximum number of instances of the word "balloon" that can be formed.

## A solution in Python

```python
def max_number_of_balloons(text: str) -> int:
    letter_count = [0] * 5
    for c in text:
        if c == 'b': letter_count[0] += 1
        if c == 'a': letter_count[1] += 1
        if c == 'l': letter_count[2] += 1
        if c == 'o': letter_count[3] += 1
        if c == 'n': letter_count[4] += 1
    letter_count[2] //= 2
    letter_count[3] //= 2
    return min(letter_count)
```
1. First, we initialize an array `letter_count` with a length of 5 to represent each character in the word "balloon".
2. We then loop through each character in the input string `text`.
3. For each character, we increment the corresponding index in the `letter_count` array if it matches one of the characters in the word "balloon".
4. After the loop, we divide the count of 'l' and 'o' by 2 since they appear twice in the word "balloon".
5. Finally, we return the minimum value in the `letter_count` array, which represents the maximum number of instances of the word "balloon" that can be formed.

## A solution in Javascript

```javascript
function maxNumberOfBalloons(text) {
    const letter_count = [0, 0, 0, 0, 0];
    for (let c of text) {
        if (c === 'b') letter_count[0]++;
        if (c === 'a') letter_count[1]++;
        if (c === 'l') letter_count[2]++;
        if (c === 'o') letter_count[3]++;
        if (c === 'n') letter_count[4]++;
    }
    letter_count[2] = Math.floor(letter_count[2] / 2);
    letter_count[3] = Math.floor(letter_count[3] / 2);
    return Math.min(...letter_count);
}
```
1. First, we initialize an array `letter_count` with a length of 5 to represent each character in the word "balloon".
2. We then loop through each character in the input string `text`.
3. For each character, we increment the corresponding index in the `letter_count` array if it matches one of the characters in the word "balloon".
4. After the loop, we divide the count of 'l' and 'o' by 2 since they appear twice in the word "balloon".
5. Finally, we return the minimum value in the `letter_count` array, which represents the maximum number of instances of the word "balloon" that can be formed.


# Reverse Substrings Between Each Pair of Parentheses

- slug: reverse-substrings-between-each-pair-of-parentheses
- difficulty: Medium

You are given a string `s` that consists of lower case English letters and brackets.

Reverse the strings in each pair of matching parentheses, starting from the innermost one.

Your result should **not** contain any brackets.

**Example 1:**

**Input:** s =  "(abcd) "
**Output:**  "dcba "

**Example 2:**

**Input:** s =  "(u(love)i) "
**Output:**  "iloveu "
**Explanation:** The substring  "love " is reversed first, then the whole string is reversed.

**Example 3:**

**Input:** s =  "(ed(et(oc))el) "
**Output:**  "leetcode "
**Explanation:** First, we reverse the substring  "oc ", then  "etco ", and finally, the whole string.

**Constraints:**

*   `1 <= s.length <= 2000`
*   `s` only contains lower case English characters and parentheses.
*   It is guaranteed that all parentheses are balanced.

## A solution in Java

```java
import java.util.Stack;

public String reverseParentheses(String s) {
    Stack<Integer> stack = new Stack<>();
    StringBuilder result = new StringBuilder(s);
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '(') {
            stack.push(i);
        } else if (s.charAt(i) == ')') {
            int start = stack.pop();
            int end = i;
            result.replace(start, end + 1, new StringBuilder(s.substring(start + 1, end)).reverse().toString());
            s = result.toString();
            i -= 2;
        }
    }
    for (int i = 0; i < result.length(); i++) {
        if (result.charAt(i) == '(' || result.charAt(i) == ')') {
            result.deleteCharAt(i);
            i--;
        }
    }
    return result.toString();
}
```
1. Create an empty stack.
2. Iterate over the characters in the input string.
3. For each character, if it is an opening bracket, push the current index to the stack.
4. If the current character is a closing bracket, pop the top element from the stack (which gives the matching opening bracket) and reverse the substring between the opening and closing brackets. Update the input string with the reversed substring.
5. Repeat steps 3-4 until all the characters in the input string are processed.
6. Construct the final output string by removing all the brackets.
7. Return the final output string.

## A solution in C++

```cpp
#include<bits/stdc++.h>
using namespace std;
string reverseParentheses(string s) {

    stack<int> st;
        for(int i = 0; i < s.length(); ++i){

            if(s[i] == '(')
                st.push(i);
            else if(s[i] == ')'){
                reverse(s.begin() + st.top() + 1,  s.begin() + i);
                st.pop();
            }
        }
        string result = "";
        for(int i = 0 ; i < s.length(); ++i){

            if(s[i] != '(' && s[i] != ')')
                result += s[i];
        }
        return result;
}
```
1. Create an empty stack.
2. Iterate over the characters in the input string.
3. For each character, if it is an opening bracket, push the current index to the stack.
4. If the current character is a closing bracket, pop the top element from the stack (which gives the matching opening bracket) and reverse the substring between the opening and closing brackets. Update the input string with the reversed substring.
5. Repeat steps 3-4 until all the characters in the input string are processed.
6. Construct the final output string by removing all the brackets.
7. Return the final output string.

## A solution in Python

```python
def reverseParentheses(s: str) -> str:
    stack = []
    for i, c in enumerate(s):
        if c == '(':
            stack.append(i)
        elif c == ')':
            start, end = stack.pop(), i
            # reversal of the substring
            s = s[:start] + s[start+1:end][::-1] + s[end+1:]
    return ''.join(c for c in s if c.isalpha())
```
1. Create an empty stack.
2. Iterate over the characters in the input string.
3. For each character, if it is an opening bracket, push the current index to the stack.
4. If the current character is a closing bracket, pop the top element from the stack (which gives the matching opening bracket) and reverse the substring between the opening and closing brackets. Update the input string with the reversed substring.
5. Repeat steps 3-4 until all the characters in the input string are processed.
6. Construct the final output string by removing all the brackets.
7. Return the final output string.

## A solution in Javascript

```javascript
function reverseParentheses(s) {
    const stack = [];
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '(') {
            stack.push(i);
        } else if (s[i] === ')') {
            const start = stack.pop();
            const end = i;
            const substring = s.slice(start + 1, end).split('').reverse().join('');
            s = s.slice(0, start) + substring + s.slice(end + 1);
        }
    }
    let result = '';
    for (let i = 0; i < s.length; i++) {
        if (s[i] !== '(' && s[i] !== ')') {
            result += s[i];
        }
    }
    return result;
}
```
1. Create an empty stack.
2. Iterate over the characters in the input string.
3. For each character, if it is an opening bracket, push the current index to the stack.
4. If the current character is a closing bracket, pop the top element from the stack (which gives the matching opening bracket) and reverse the substring between the opening and closing brackets. Update the input string with the reversed substring.
5. Repeat steps 3-4 until all the characters in the input string are processed.
6. Construct the final output string by removing all the brackets.
7. Return the final output string.


# K-Concatenation Maximum Sum

- slug: k-concatenation-maximum-sum
- difficulty: Medium

Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.

For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.

Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`.

As the answer can be very large, return the answer **modulo** `109 + 7`.

**Example 1:**

**Input:** arr = \[1,2\], k = 3
**Output:** 9

**Example 2:**

**Input:** arr = \[1,-2,1\], k = 5
**Output:** 2

**Example 3:**

**Input:** arr = \[-1,-2\], k = 7
**Output:** 0

**Constraints:**

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

## A solution in Java

```java
public int kConcatenationMaxSum(int[] arr, int k) {
    long mod = (long) 1e9 + 7, n = arr.length;
    long sum = 0, maxSum = 0, tempSum = 0, maxLeft = 0, maxRight = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
        tempSum += arr[i];
        maxSum = Math.max(maxSum, tempSum);
        tempSum = Math.max(0, tempSum);
        maxLeft = Math.max(maxLeft, sum);
    }

    long temp = sum;
    for (int i = n - 1; i >= 0; i--) {
        temp -= arr[i];
        maxRight = Math.max(maxRight, temp);
    }

    long ans = Math.max(maxSum, maxLeft + maxRight + sum * (k - 2));
    return (int) (ans % mod);
}
```
The algorithm maintains several variables to keep track of the maximum subarray sum within the array, its maximum prefix sum, maximum suffix sum, and the total sum of the array. We iterate over the array twice, first to obtain the maximum subarray sum, maximum prefix sum, and total sum, and then again to obtain the maximum suffix sum. Using these four values, we can compute the maximum subarray sum of the concatenated array through several cases. If k is 1, the maximum subarray sum is just the maximum sum of the single array. If k > 1, we can either take the maximum subarray sum of the array multiplied by k, or combine the maximum prefix sum, maximum suffix sum, and the sum of the array multiplied by k minus 2 to find the maximum subarray sum. Finally, we return the maximum subarray sum modulo 10^9 + 7.

## A solution in C++

```cpp
int kConcatenationMaxSum(vector<int>& arr, int k) {
    long long mod = 1e9 + 7, n = arr.size(), sum = 0, maxSum = 0, tempSum = 0, maxLeft = 0, maxRight = 0;
    for (int i = 0; i < n; ++i) {
        sum += arr[i];
        tempSum += arr[i];
        maxSum = max(maxSum, tempSum);
        tempSum = max(0LL, tempSum);
        maxLeft = max(maxLeft, sum);
    }
    long long temp = sum;
    for (int i = n - 1; i >= 0; --i) {
        temp -= arr[i];
        maxRight = max(maxRight, temp);
    }
    long long ans = max({maxSum, maxLeft + maxRight + sum * (k - 2), 0LL});
    return ans % mod;
}
```
The algorithm maintains several variables to keep track of the maximum subarray sum within the array, its maximum prefix sum, maximum suffix sum, and the total sum of the array. We iterate over the array twice, first to obtain the maximum subarray sum, maximum prefix sum, and total sum, and then again to obtain the maximum suffix sum. Using these four values, we can compute the maximum subarray sum of the concatenated array through several cases. If k is 1, the maximum subarray sum is just the maximum sum of the single array. If k > 1, we can either take the maximum subarray sum of the array multiplied by k, or combine the maximum prefix sum, maximum suffix sum, and the sum of the array multiplied by k minus 2 to find the maximum subarray sum. Finally, we return the maximum subarray sum modulo 10^9 + 7.

## A solution in Python

```python
def kConcatenationMaxSum(arr, k):
    mod = 10**9 + 7
    n = len(arr)
    max_sum, max_left, max_right = 0, 0, 0
    total_sum = sum(arr)
    temp_sum = 0

    for i in range(n):
        temp_sum += arr[i]
        max_sum = max(max_sum, temp_sum)
        temp_sum = max(0, temp_sum)
        max_left = max(max_left, temp_sum)

    temp = total_sum
    for i in range(n - 1, -1, -1):
        temp -= arr[i]
        max_right = max(max_right, temp)

    ans = max(max_sum, max_left + max_right + total_sum * (k - 2), 0)
    return ans % mod
```
The algorithm maintains several variables to keep track of the maximum subarray sum within the array, its maximum prefix sum, maximum suffix sum, and the total sum of the array. We iterate over the array twice, first to obtain the maximum subarray sum, maximum prefix sum, and total sum, and then again to obtain the maximum suffix sum. Using these four values, we can compute the maximum subarray sum of the concatenated array through several cases. If k is 1, the maximum subarray sum is just the maximum sum of the single array. If k > 1, we can either take the maximum subarray sum of the array multiplied by k, or combine the maximum prefix sum, maximum suffix sum, and the sum of the array multiplied by k minus 2 to find the maximum subarray sum. Finally, we return the maximum subarray sum modulo 10^9 + 7.

## A solution in Javascript

```javascript
function kConcatenationMaxSum(arr, k) {
    const mod = 1e9 + 7;
    let n = arr.length;
    let sum = 0, maxSum = 0, tempSum = 0, maxLeft = 0, maxRight = 0;

    for (let i = 0; i < n; i++) {
        sum += arr[i];
        tempSum += arr[i];
        maxSum = Math.max(maxSum, tempSum);
        tempSum = Math.max(0, tempSum);
        maxLeft = Math.max(maxLeft, sum);
    }

    let temp = sum;
    for (let i = n - 1; i >= 0; i--) {
        temp -= arr[i];
        maxRight = Math.max(maxRight, temp);
    }

    let ans = Math.max(maxSum, maxLeft + maxRight + sum * (k - 2), 0);
    return ans % mod;
}
```
The algorithm maintains several variables to keep track of the maximum subarray sum within the array, its maximum prefix sum, maximum suffix sum, and the total sum of the array. We iterate over the array twice, first to obtain the maximum subarray sum, maximum prefix sum, and total sum, and then again to obtain the maximum suffix sum. Using these four values, we can compute the maximum subarray sum of the concatenated array through several cases. If k is 1, the maximum subarray sum is just the maximum sum of the single array. If k > 1, we can either take the maximum subarray sum of the array multiplied by k, or combine the maximum prefix sum, maximum suffix sum, and the sum of the array multiplied by k minus 2 to find the maximum subarray sum. Finally, we return the maximum subarray sum modulo 10^9 + 7.


# Critical Connections in a Network

- slug: critical-connections-in-a-network
- difficulty: Hard

There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network.

A _critical connection_ is a connection that, if removed, will make some servers unable to reach some other server.

Return all critical connections in the network in any order.

**Example 1:**

**Input:** n = 4, connections = \[\[0,1\],\[1,2\],\[2,0\],\[1,3\]\]
**Output:** \[\[1,3\]\]
**Explanation:** \[\[3,1\]\] is also accepted.

**Example 2:**

**Input:** n = 2, connections = \[\[0,1\]\]
**Output:** \[\[0,1\]\]

**Constraints:**

*   `2 <= n <= 105`
*   `n - 1 <= connections.length <= 105`
*   `0 <= ai, bi <= n - 1`
*   `ai != bi`
*   There are no repeated connections.

## A solution in Java

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

public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
    List<List<Integer>> result = new ArrayList<>();
    Map<Integer, List<Integer>> graph = new HashMap<>();
    for (List<Integer> connection : connections) {
        graph.putIfAbsent(connection.get(0), new ArrayList<>());
        graph.putIfAbsent(connection.get(1), new ArrayList<>());
        graph.get(connection.get(0)).add(connection.get(1));
        graph.get(connection.get(1)).add(connection.get(0));
    }
    int[] rank = new int[n];
    for (int i = 0; i < n; i++) {
        rank[i] = -1;
    }
    dfs(0, -1, 0, rank, graph, result);
    return result;
}

private void dfs(int node, int parent, int depth, int[] rank, Map<Integer, List<Integer>> graph, List<List<Integer>> result) {
    rank[node] = depth;
    for (int neighbor : graph.get(node)) {
        if (neighbor == parent) {
            continue;
        }
        if (rank[neighbor] == -1) {
            dfs(neighbor, node, depth + 1, rank, graph, result);
        }
        rank[node] = Math.min(rank[node], rank[neighbor]);
        if (rank[neighbor] == depth + 1) {
            result.add(List.of(node, neighbor));
        }
    }
}
```
The problem can be solved using a Depth-First Search (DFS) algorithm. The algorithm starts by creating a graph from the server connections, represented by an adjacency list. Then a Rank array is initialized with -1 as initial value, which will store the rank/depth of each node in the DFS traversal.

We execute a DFS starting from the initial node (0) and at each step, we update the rank of the current node accordingly. Then, we visit neighbors. If the neighbor is the parent node from where the current node is visited, we just skip and continue to the next neighbor.

If the neighbor node has not been visited yet, DFS is called recursively for the neighbor node, increasing the depth by one. After the DFS call, we update the current node's rank with the minimum rank between its rank and the neighbors' rank if a neighbor node has been visited earlier.

Finally, we check if the neighbor node's rank is equal to the depth of the current node plus one. If true, it means the connection between the current node and the neighbor node is critical, thus we add this connection to the result.

Once the algorithm is done executing the DFS, the result will contain all critical connections.

## A solution in C++

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

using namespace std;

void dfs(int node, int parent, int depth, vector<int>& rank, unordered_map<int, vector<int>>& graph, vector<vector<int>>& result) {
    rank[node] = depth;
    for (const int& neighbor : graph[node]) {
        if (neighbor == parent) {
            continue;
        }
        if (rank[neighbor] == -1) {
            dfs(neighbor, node, depth + 1, rank, graph, result);
        }
        rank[node] = min(rank[node], rank[neighbor]);
        if (rank[neighbor] == depth + 1) {
            result.push_back({node, neighbor});
        }
    }
}

vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
    vector<vector<int>> result;
    unordered_map<int, vector<int>> graph;
    for (const vector<int>& connection : connections) {
        graph[connection[0]].push_back(connection[1]);
        graph[connection[1]].push_back(connection[0]);
    }
    vector<int> rank(n, -1);
    dfs(0, -1, 0, rank, graph, result);
    return result;
}
```
The problem can be solved using a Depth-First Search (DFS) algorithm. The algorithm starts by creating a graph from the server connections, represented by an adjacency list. Then a Rank array is initialized with -1 as initial value, which will store the rank/depth of each node in the DFS traversal.

We execute a DFS starting from the initial node (0) and at each step, we update the rank of the current node accordingly. Then, we visit neighbors. If the neighbor is the parent node from where the current node is visited, we just skip and continue to the next neighbor.

If the neighbor node has not been visited yet, DFS is called recursively for the neighbor node, increasing the depth by one. After the DFS call, we update the current node's rank with the minimum rank between its rank and the neighbors' rank if a neighbor node has been visited earlier.

Finally, we check if the neighbor node's rank is equal to the depth of the current node plus one. If true, it means the connection between the current node and the neighbor node is critical, thus we add this connection to the result.

Once the algorithm is done executing the DFS, the result will contain all critical connections.

## A solution in Python

```python
from collections import defaultdict

def criticalConnections(n, connections):
    def dfs(node, parent, depth, rank, graph, result):
        rank[node] = depth
        for neighbor in graph[node]:
            if neighbor == parent:
                continue
            if rank[neighbor] == -1:
                dfs(neighbor, node, depth + 1, rank, graph, result)
            rank[node] = min(rank[node], rank[neighbor])
            if rank[neighbor] == depth + 1:
                result.append((node, neighbor))

    graph = defaultdict(list)
    for fr, to in connections:
        graph[fr].append(to)
        graph[to].append(fr)

    rank = [-1] * n
    result = []
    dfs(0, -1, 0, rank, graph, result)
    return result
```
The problem can be solved using a Depth-First Search (DFS) algorithm. The algorithm starts by creating a graph from the server connections, represented by an adjacency list. Then a Rank array is initialized with -1 as initial value, which will store the rank/depth of each node in the DFS traversal.

We execute a DFS starting from the initial node (0) and at each step, we update the rank of the current node accordingly. Then, we visit neighbors. If the neighbor is the parent node from where the current node is visited, we just skip and continue to the next neighbor.

If the neighbor node has not been visited yet, DFS is called recursively for the neighbor node, increasing the depth by one. After the DFS call, we update the current node's rank with the minimum rank between its rank and the neighbors' rank if a neighbor node has been visited earlier.

Finally, we check if the neighbor node's rank is equal to the depth of the current node plus one. If true, it means the connection between the current node and the neighbor node is critical, thus we add this connection to the result.

Once the algorithm is done executing the DFS, the result will contain all critical connections.

## A solution in Javascript

```javascript
function criticalConnections(n, connections) {
    const graph = new Map();
    for (const [fr, to] of connections) {
        if (!graph.has(fr)) {
            graph.set(fr, []);
        }
        if (!graph.has(to)) {
            graph.set(to, []);
        }
        graph.get(fr).push(to);
        graph.get(to).push(fr);
    }

    const rank = new Array(n).fill(-1);
    const result = [];
    dfs(0, -1, 0, rank, graph, result);
    return result;
}

function dfs(node, parent, depth, rank, graph, result) {
    rank[node] = depth;
    for (const neighbor of graph.get(node)) {
        if (neighbor === parent) {
            continue;
        }
        if (rank[neighbor] === -1) {
            dfs(neighbor, node, depth + 1, rank, graph, result);
        }
        rank[node] = Math.min(rank[node], rank[neighbor]);
        if (rank[neighbor] === depth + 1) {
            result.push([node, neighbor]);
        }
    }
}
```
The problem can be solved using a Depth-First Search (DFS) algorithm. The algorithm starts by creating a graph from the server connections, represented by an adjacency list. Then a Rank array is initialized with -1 as initial value, which will store the rank/depth of each node in the DFS traversal.

We execute a DFS starting from the initial node (0) and at each step, we update the rank of the current node accordingly. Then, we visit neighbors. If the neighbor is the parent node from where the current node is visited, we just skip and continue to the next neighbor.

If the neighbor node has not been visited yet, DFS is called recursively for the neighbor node, increasing the depth by one. After the DFS call, we update the current node's rank with the minimum rank between its rank and the neighbors' rank if a neighbor node has been visited earlier.

Finally, we check if the neighbor node's rank is equal to the depth of the current node plus one. If true, it means the connection between the current node and the neighbor node is critical, thus we add this connection to the result.

Once the algorithm is done executing the DFS, the result will contain all critical connections.


# How Many Apples Can You Put into the Basket

- slug: how-many-apples-can-you-put-into-the-basket
- difficulty: Easy

You have some apples and a basket that can carry up to `5000` units of weight.

Given an integer array `weight` where `weight[i]` is the weight of the `ith` apple, return _the maximum number of apples you can put in the basket_.

**Example 1:**

**Input:** weight = \[100,200,150,1000\]
**Output:** 4
**Explanation:** All 4 apples can be carried by the basket since their sum of weights is 1450.

**Example 2:**

**Input:** weight = \[900,950,800,1000,700,800\]
**Output:** 5
**Explanation:** The sum of weights of the 6 apples exceeds 5000 so we choose any 5 of them.

**Constraints:**

*   `1 <= weight.length <= 103`
*   `1 <= weight[i] <= 103`

## A solution in Java

```java
public int minHeightShelves(int[][] books, int shelfWidth) {
    int n = books.length;
    int[] dp = new int[n + 1];
    Arrays.fill(dp, 1000000);
    dp[0] = 0;

    for (int i = 1; i <= n; i++) {
        int width = 0, height = 0;
        for (int j = i; j >= 1; j--) {
            width += books[j - 1][0];
            height = Math.max(height, books[j - 1][1]);

            if (width <= shelfWidth)
                dp[i] = Math.min(dp[i], dp[j - 1] + height);
        }
    }

    return dp[n];
}
```
We can solve this problem using dynamic programming. We create a DP array dp where dp[i] represents the minimum height of the bookshelf after placing the first i books. We initialize the DP array with a large number (e.g., 1000000) except for dp[0], which we set to 0.

We iterate over the books from 1 to n, and for each book, we go through another loop in reverse order from i to 1. In this inner loop, we keep track of the width and maximum height of the books we've seen so far. We calculate the width by adding the thickness of the current book (books[j - 1][0]) to the width accumulator, and update the maximum height (height) if the height of the current book (books[j - 1][1]) is greater than the previously stored maximum height.

If the width of the books we've seen does not exceed shelfWidth, we update dp[i] with the minimum between dp[i] and the sum of the height we would get by placing a new bookshelf below the current one (dp[j - 1] + height). We do this for every iteration in both loops.

Finally, we return the value of dp[n], which represents the minimum height of the bookshelf after placing all the books.

## A solution in C++

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

int minHeightShelves(std::vector<std::vector<int>>& books, int shelfWidth) {
    int n = books.size();
    std::vector<int> dp(n + 1, 1000000);
    dp[0] = 0;

    for (int i = 1; i <= n; ++i) {
        int width = 0, height = 0;
        for (int j = i; j >= 1; --j) {
            width += books[j - 1][0];
            height = std::max(height, books[j - 1][1]);

            if (width <= shelfWidth)
                dp[i] = std::min(dp[i], dp[j - 1] + height);
        }
    }

    return dp[n];
}
```
We can solve this problem using dynamic programming. We create a DP array dp where dp[i] represents the minimum height of the bookshelf after placing the first i books. We initialize the DP array with a large number (e.g., 1000000) except for dp[0], which we set to 0.

We iterate over the books from 1 to n, and for each book, we go through another loop in reverse order from i to 1. In this inner loop, we keep track of the width and maximum height of the books we've seen so far. We calculate the width by adding the thickness of the current book (books[j - 1][0]) to the width accumulator, and update the maximum height (height) if the height of the current book (books[j - 1][1]) is greater than the previously stored maximum height.

If the width of the books we've seen does not exceed shelfWidth, we update dp[i] with the minimum between dp[i] and the sum of the height we would get by placing a new bookshelf below the current one (dp[j - 1] + height). We do this for every iteration in both loops.

Finally, we return the value of dp[n], which represents the minimum height of the bookshelf after placing all the books.

## A solution in Python

```python
def minHeightShelves(books, shelfWidth):
    n = len(books)
    dp = [1000000] * (n + 1)
    dp[0] = 0

    for i in range(1, n + 1):
        width = 0
        height = 0
        j = i
        while j >= 1:
            width += books[j - 1][0]
            height = max(height, books[j - 1][1])

            if width <= shelfWidth:
                dp[i] = min(dp[i], dp[j - 1] + height)
            j -= 1

    return dp[n]
```
We can solve this problem using dynamic programming. We create a DP array dp where dp[i] represents the minimum height of the bookshelf after placing the first i books. We initialize the DP array with a large number (e.g., 1000000) except for dp[0], which we set to 0.

We iterate over the books from 1 to n, and for each book, we go through another loop in reverse order from i to 1. In this inner loop, we keep track of the width and maximum height of the books we've seen so far. We calculate the width by adding the thickness of the current book (books[j - 1][0]) to the width accumulator, and update the maximum height (height) if the height of the current book (books[j - 1][1]) is greater than the previously stored maximum height.

If the width of the books we've seen does not exceed shelfWidth, we update dp[i] with the minimum between dp[i] and the sum of the height we would get by placing a new bookshelf below the current one (dp[j - 1] + height). We do this for every iteration in both loops.

Finally, we return the value of dp[n], which represents the minimum height of the bookshelf after placing all the books.

## A solution in Javascript

```javascript
function minHeightShelves(books, shelfWidth) {
    const n = books.length;
    const dp = new Array(n + 1).fill(1000000);
    dp[0] = 0;

    for (let i = 1; i <= n; i++) {
        let width = 0, height = 0;
        for (let j = i; j >= 1; j--) {
            width += books[j - 1][0];
            height = Math.max(height, books[j - 1][1]);

            if (width <= shelfWidth)
                dp[i] = Math.min(dp[i], dp[j - 1] + height);
        }
    }

    return dp[n];
}
```
We can solve this problem using dynamic programming. We create a DP array dp where dp[i] represents the minimum height of the bookshelf after placing the first i books. We initialize the DP array with a large number (e.g., 1000000) except for dp[0], which we set to 0.

We iterate over the books from 1 to n, and for each book, we go through another loop in reverse order from i to 1. In this inner loop, we keep track of the width and maximum height of the books we've seen so far. We calculate the width by adding the thickness of the current book (books[j - 1][0]) to the width accumulator, and update the maximum height (height) if the height of the current book (books[j - 1][1]) is greater than the previously stored maximum height.

If the width of the books we've seen does not exceed shelfWidth, we update dp[i] with the minimum between dp[i] and the sum of the height we would get by placing a new bookshelf below the current one (dp[j - 1] + height). We do this for every iteration in both loops.

Finally, we return the value of dp[n], which represents the minimum height of the bookshelf after placing all the books.


# Minimum Knight Moves

- slug: minimum-knight-moves
- difficulty: Medium

In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`.

A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

Return _the minimum number of steps needed to move the knight to the square_ `[x, y]`. It is guaranteed the answer exists.

**Example 1:**

**Input:** x = 2, y = 1
**Output:** 1
**Explanation:** \[0, 0\] -> \[2, 1\]

**Example 2:**

**Input:** x = 5, y = 5
**Output:** 4
**Explanation:** \[0, 0\] -> \[2, 1\] -> \[4, 2\] -> \[3, 4\] -> \[5, 5\]

**Constraints:**

*   `-300 <= x, y <= 300`
*   `0 <= |x| + |y| <= 300`

"t", evaluating to True; "f", evaluating to False; "!(expression)", evaluating to the logical NOT of the expression inside the parentheses; "&(expression1,expression2,...)", evaluating to the logical AND of 2 or more expressions; "|(expression1,expression2,...)", evaluating to the logical OR of 2 or more expressions.

## A solution in Java

```java
public boolean parseBoolExpr(String expression, int[] pos) {
    char current = expression.charAt(pos[0]++);
    switch (current) {
        case 't': return true;
        case 'f': return false;
        case '!': return !parseBoolExpr(expression, ++pos);
        case '&': {
            pos[0]++;
            boolean result = true;
            while (expression.charAt(pos[0]) != ')') {
                result &= parseBoolExpr(expression, pos);
                if(expression.charAt(pos[0]) == ',') pos[0]++;
            }
            pos[0]++;
            return result;
        }
        case '|': {
            pos[0]++;
            boolean result = false;
            while (expression.charAt(pos[0]) != ')') {
                result |= parseBoolExpr(expression, pos);
                if(expression.charAt(pos[0]) == ',') pos[0]++;
            }
            pos[0]++;
            return result;
        }
    }
    return false;
}

public boolean parseBoolExpr(String expression) {
    int[] pos = new int[] {0};
    return parseBoolExpr(expression, pos);
}
```
The algorithm uses a recursive descent parser. It evaluates the given boolean expression string by iterating over each character and processing it based on its type.

For each character encountered in the input string, the algorithm takes the following actions:
1. If it is 't' or 'f', it returns true or false, respectively.
2. If it is '!', it increments the position and evaluates the expression inside the parenthesis, returning its negation.
3. If it is '&', it evaluates all expressions inside the parentheses, taking the logical AND of the results.
4. If it is '|', it evaluates all expressions inside the parentheses, taking the logical OR of the results.

In each case, the parser uses a position variable (`pos`) to keep track of the current position in the expression string. The parser increments the position throughout the evaluation process to handle nested boolean expressions properly.

For languages like Java and JavaScript, which lack support for reference variables, an array of a single element (e.g., `int[] pos` or `pos = [0]`) is used to emulate pass-by-reference. This way, the position is shared and updated among recursive calls.

## A solution in C++

```cpp
bool parseBoolExpr(string expression, int &pos) {
    switch (expression[pos++]) {
        case 't': return true;
        case 'f': return false;
        case '!': return !parseBoolExpr(expression, ++pos);
        case '&': {
            pos++;
            bool result = true;
            while (expression[pos] != ')') {
                result &= parseBoolExpr(expression, pos);
                if(expression[pos] == ',') pos++;
            }
            pos++;
            return result;
        }
        case '|': {
            pos++;
            bool result = false;
            while (expression[pos] != ')') {
                result |= parseBoolExpr(expression, pos);
                if(expression[pos] == ',') pos++;
            }
            pos++;
            return result;
        }
    }
}

bool parseBoolExpr(string expression) {
    int pos = 0;
    return parseBoolExpr(expression, pos);
}
```
The algorithm uses a recursive descent parser. It evaluates the given boolean expression string by iterating over each character and processing it based on its type.

For each character encountered in the input string, the algorithm takes the following actions:
1. If it is 't' or 'f', it returns true or false, respectively.
2. If it is '!', it increments the position and evaluates the expression inside the parenthesis, returning its negation.
3. If it is '&', it evaluates all expressions inside the parentheses, taking the logical AND of the results.
4. If it is '|', it evaluates all expressions inside the parentheses, taking the logical OR of the results.

In each case, the parser uses a position variable (`pos`) to keep track of the current position in the expression string. The parser increments the position throughout the evaluation process to handle nested boolean expressions properly.

For languages like Java and JavaScript, which lack support for reference variables, an array of a single element (e.g., `int[] pos` or `pos = [0]`) is used to emulate pass-by-reference. This way, the position is shared and updated among recursive calls.

## A solution in Python

```python
def parse_bool_expr(expression, pos=None):
    if pos is None:
        pos = [0]
    current = expression[pos[0]]
    pos[0] += 1
    if current == 't': return True
    if current == 'f': return False
    if current == '!':
        pos[0] += 1
        return not parse_bool_expr(expression, pos)
    if current == '&':
        pos[0] += 1
        result = True
        while expression[pos[0]] != ')':
            result &= parse_bool_expr(expression, pos)
            if expression[pos[0]] == ',': pos[0] += 1
    elif current == '|':
        pos[0] += 1
        result = False
        while expression[pos[0]] != ')':
            result |= parse_bool_expr(expression, pos)
            if expression[pos[0]] == ',': pos[0] += 1
    pos[0] += 1
    return result
```
The algorithm uses a recursive descent parser. It evaluates the given boolean expression string by iterating over each character and processing it based on its type.

For each character encountered in the input string, the algorithm takes the following actions:
1. If it is 't' or 'f', it returns true or false, respectively.
2. If it is '!', it increments the position and evaluates the expression inside the parenthesis, returning its negation.
3. If it is '&', it evaluates all expressions inside the parentheses, taking the logical AND of the results.
4. If it is '|', it evaluates all expressions inside the parentheses, taking the logical OR of the results.

In each case, the parser uses a position variable (`pos`) to keep track of the current position in the expression string. The parser increments the position throughout the evaluation process to handle nested boolean expressions properly.

For languages like Java and JavaScript, which lack support for reference variables, an array of a single element (e.g., `int[] pos` or `pos = [0]`) is used to emulate pass-by-reference. This way, the position is shared and updated among recursive calls.

## A solution in Javascript

```javascript
function parseBoolExpr(expression, pos = [0]) {
    const current = expression[pos[0]++];
    if (current === 't') return true;
    if (current === 'f') return false;
    if (current === '!') {
        pos[0]++;
        return !parseBoolExpr(expression, pos);
    }
    if (current === '&') {
        pos[0]++;
        let result = true;
        while (expression[pos[0]] !== ')') {
            result &= parseBoolExpr(expression, pos);
            if (expression[pos[0]] === ',') pos[0]++;
        }
    } else if (current === '|') {
        pos[0]++;
        let result = false;
        while (expression[pos[0]] !== ')') {
            result |= parseBoolExpr(expression, pos);
            if (expression[pos[0]] === ',') pos[0]++;
        }
    }
    pos[0]++;
    return result;
}
```
The algorithm uses a recursive descent parser. It evaluates the given boolean expression string by iterating over each character and processing it based on its type.

For each character encountered in the input string, the algorithm takes the following actions:
1. If it is 't' or 'f', it returns true or false, respectively.
2. If it is '!', it increments the position and evaluates the expression inside the parenthesis, returning its negation.
3. If it is '&', it evaluates all expressions inside the parentheses, taking the logical AND of the results.
4. If it is '|', it evaluates all expressions inside the parentheses, taking the logical OR of the results.

In each case, the parser uses a position variable (`pos`) to keep track of the current position in the expression string. The parser increments the position throughout the evaluation process to handle nested boolean expressions properly.

For languages like Java and JavaScript, which lack support for reference variables, an array of a single element (e.g., `int[] pos` or `pos = [0]`) is used to emulate pass-by-reference. This way, the position is shared and updated among recursive calls.


# Find Smallest Common Element in All Rows

- slug: find-smallest-common-element-in-all-rows
- difficulty: Medium

Given an `m x n` matrix `mat` where every row is sorted in **strictly** **increasing** order, return _the **smallest common element** in all rows_.

If there is no common element, return `-1`.

**Example 1:**

**Input:** mat = \[\[1,2,3,4,5\],\[2,4,5,8,10\],\[3,5,7,9,11\],\[1,3,5,7,9\]\]
**Output:** 5

**Example 2:**

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

**Constraints:**

*   `m == mat.length`
*   `n == mat[i].length`
*   `1 <= m, n <= 500`
*   `1 <= mat[i][j] <= 104`
*   `mat[i]` is sorted in strictly increasing order.

## A solution in Java

```java
public int smallestCommonElement(int[][] mat) {
    HashMap<Integer, Integer> counts = new HashMap<>();
    for (int[] row : mat) {
        for (int num : row) {
            counts.put(num, counts.getOrDefault(num, 0) + 1);
            if (counts.get(num) == mat.length) {
                return num;
            }
        }
    }
    return -1;
}
```
The algorithm iterates through each value in the matrix and maintains an unordered_map (HashMap, dictionary, or Map, depending on the language) which stores the count of each value. Every time it encounters a value, it increments the counter in the map. If at any point, the count of a number equals the number of rows in the matrix ('mat.length' or 'len(mat)'), it returns that number as the smallest common element. If no common element is found, it returns -1.

## A solution in C++

```cpp
int smallestCommonElement(vector<vector<int>>& mat) {
    unordered_map<int, int> counts;
    for (const auto& row : mat) {
        for (int num : row) {
            ++counts[num];
            if (counts[num] == mat.size()) {
                return num;
            }
        }
    }
    return -1;
}
```
The algorithm iterates through each value in the matrix and maintains an unordered_map (HashMap, dictionary, or Map, depending on the language) which stores the count of each value. Every time it encounters a value, it increments the counter in the map. If at any point, the count of a number equals the number of rows in the matrix ('mat.length' or 'len(mat)'), it returns that number as the smallest common element. If no common element is found, it returns -1.

## A solution in Python

```python
def smallest_common_element(mat):
    counts = {}
    for row in mat:
        for num in row:
            counts[num] = counts.get(num, 0) + 1
            if counts[num] == len(mat):
                return num
    return -1
```
The algorithm iterates through each value in the matrix and maintains an unordered_map (HashMap, dictionary, or Map, depending on the language) which stores the count of each value. Every time it encounters a value, it increments the counter in the map. If at any point, the count of a number equals the number of rows in the matrix ('mat.length' or 'len(mat)'), it returns that number as the smallest common element. If no common element is found, it returns -1.

## A solution in Javascript

```javascript
function smallestCommonElement(mat) {
    const counts = new Map();
    for (const row of mat) {
        for (const num of row) {
            counts.set(num, (counts.get(num) || 0) + 1);
            if (counts.get(num) === mat.length) {
                return num;
            }
        }
    }
    return -1;
}
```
The algorithm iterates through each value in the matrix and maintains an unordered_map (HashMap, dictionary, or Map, depending on the language) which stores the count of each value. Every time it encounters a value, it increments the counter in the map. If at any point, the count of a number equals the number of rows in the matrix ('mat.length' or 'len(mat)'), it returns that number as the smallest common element. If no common element is found, it returns -1.


# Minimum Time to Build Blocks

- slug: minimum-time-to-build-blocks
- difficulty: Hard

You are given a list of blocks, where `blocks[i] = t` means that the `i`\-th block needs `t` units of time to be built. A block can only be built by exactly one worker.

A worker can either split into two workers (number of workers increases by one) or build a block then go home. Both decisions cost some time.

The time cost of spliting one worker into two workers is given as an integer `split`. Note that if two workers split at the same time, they split in parallel so the cost would be `split`.

Output the minimum time needed to build all blocks.

Initially, there is only **one** worker.

**Example 1:**

**Input:** blocks = \[1\], split = 1
**Output:** 1
**Explanation:** We use 1 worker to build 1 block in 1 time unit.

**Example 2:**

**Input:** blocks = \[1,2\], split = 5
**Output:** 7
**Explanation:** We split the worker into 2 workers in 5 time units then assign each of them to a block so the cost is 5 + max(1, 2) = 7.

**Example 3:**

**Input:** blocks = \[1,2,3\], split = 1
**Output:** 4
**Explanation:** Split 1 worker into 2, then assign the first worker to the last block and split the second worker into 2.
Then, use the two unassigned workers to build the first two blocks.
The cost is 1 + max(3, 1 + max(1, 2)) = 4.

**Constraints:**

*   `1 <= blocks.length <= 1000`
*   `1 <= blocks[i] <= 10^5`
*   `1 <= split <= 100`

## A solution in Java

```java
import java.util.PriorityQueue;

public int minBuildTime(int[] blocks, int split) {
    PriorityQueue<Integer> pq = new PriorityQueue<>();

    for (int block : blocks) {
        pq.add(block);
    }

    while (pq.size() > 1) {
        int a = pq.poll();
        int b = pq.poll();
        pq.add(b + split);
    }

    return pq.poll();
}
```
We use a priority queue to get the smallest time units of the blocks. In each iteration, we get the two smallest time units and insert the larger one plus the split time back into the priority queue. This is repeated until there is only one element left in the priority queue.

This results in the workers splitting and working on the blocks with the smallest time units.

Initially, we insert all blocks' time units into the priority queue. Then we enter a loop where we get the two smallest elements (a and b), pop them from the priority queue, and add (b + split) back into the priority queue. We keep doing this until there's only one element left in the priority queue.

Finally, we return the last remaining element as the minimum time needed to build all blocks.

## A solution in C++

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

int minBuildTime(std::vector<int>& blocks, int split) {
    std::priority_queue<int, std::vector<int>, greater<int>> pq(blocks.begin(), blocks.end());

    while (pq.size() > 1) {
        int a = pq.top();
        pq.pop();
        int b = pq.top();
        pq.pop();
        pq.push(b + split);
    }

    return pq.top();
}
```
We use a priority queue to get the smallest time units of the blocks. In each iteration, we get the two smallest time units and insert the larger one plus the split time back into the priority queue. This is repeated until there is only one element left in the priority queue.

This results in the workers splitting and working on the blocks with the smallest time units.

Initially, we insert all blocks' time units into the priority queue. Then we enter a loop where we get the two smallest elements (a and b), pop them from the priority queue, and add (b + split) back into the priority queue. We keep doing this until there's only one element left in the priority queue.

Finally, we return the last remaining element as the minimum time needed to build all blocks.

## A solution in Python

```python
import heapq

def min_build_time(blocks, split):
    heapq.heapify(blocks)

    while len(blocks) > 1:
        a = heapq.heappop(blocks)
        b = heapq.heappop(blocks)
        heapq.heappush(blocks, b + split)

    return blocks[0]
```
We use a priority queue to get the smallest time units of the blocks. In each iteration, we get the two smallest time units and insert the larger one plus the split time back into the priority queue. This is repeated until there is only one element left in the priority queue.

This results in the workers splitting and working on the blocks with the smallest time units.

Initially, we insert all blocks' time units into the priority queue. Then we enter a loop where we get the two smallest elements (a and b), pop them from the priority queue, and add (b + split) back into the priority queue. We keep doing this until there's only one element left in the priority queue.

Finally, we return the last remaining element as the minimum time needed to build all blocks.

## A solution in Javascript

```javascript
function minBuildTime(blocks, split) {
    const pq = new PriorityQueue();
    for (const block of blocks) {
        pq.add(block);
    }

    while (pq.size() > 1) {
        const a = pq.poll();
        const b = pq.poll();
        pq.add(b + split);
    }

    return pq.poll();
}
```
We use a priority queue to get the smallest time units of the blocks. In each iteration, we get the two smallest time units and insert the larger one plus the split time back into the priority queue. This is repeated until there is only one element left in the priority queue.

This results in the workers splitting and working on the blocks with the smallest time units.

Initially, we insert all blocks' time units into the priority queue. Then we enter a loop where we get the two smallest elements (a and b), pop them from the priority queue, and add (b + split) back into the priority queue. We keep doing this until there's only one element left in the priority queue.

Finally, we return the last remaining element as the minimum time needed to build all blocks.


# Minimum Absolute Difference

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

Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.

Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows

*   `a, b` are from `arr`
*   `a < b`
*   `b - a` equals to the minimum absolute difference of any two elements in `arr`

**Example 1:**

**Input:** arr = \[4,2,1,3\]
**Output:** \[\[1,2\],\[2,3\],\[3,4\]\]
**Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.

**Example 2:**

**Input:** arr = \[1,3,6,10,15\]
**Output:** \[\[1,3\]\]

**Example 3:**

**Input:** arr = \[3,8,-10,23,19,-4,-14,27\]
**Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\]

**Constraints:**

*   `2 <= arr.length <= 105`
*   `-106 <= arr[i] <= 106`

## A solution in Java

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

public List<List<Integer>> minimumAbsDifference(int[] arr) {
    Arrays.sort(arr);
    int minDiff = Integer.MAX_VALUE;
    for (int i = 1; i < arr.length; i++) {
        minDiff = Math.min(minDiff, arr[i] - arr[i - 1]);
    }

    List<List<Integer>> result = new ArrayList<>();
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] - arr[i - 1] == minDiff) {
            result.add(Arrays.asList(arr[i - 1], arr[i]));
        }
    }

    return result;
}
```
1. Sort the input array in ascending order.
2. Iterate through the sorted array and find the minimum absolute difference between adjacent elements. This value will be the minimum difference between any two elements in the array.
3. Iterate through the sorted array again and construct the output list by adding pairs of elements with an absolute difference equal to the minimum difference found in step 2.

## A solution in C++

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

vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
    sort(arr.begin(), arr.end());
    int minDiff = INT_MAX;
    for (int i = 1; i < arr.size(); i++) {
        minDiff = min(minDiff, arr[i] - arr[i - 1]);
    }

    vector<vector<int>> result;
    for (int i = 1; i < arr.size(); i++) {
        if (arr[i] - arr[i - 1] == minDiff) {
            result.push_back({arr[i - 1], arr[i]});
        }
    }

    return result;
}
```
1. Sort the input array in ascending order.
2. Iterate through the sorted array and find the minimum absolute difference between adjacent elements. This value will be the minimum difference between any two elements in the array.
3. Iterate through the sorted array again and construct the output list by adding pairs of elements with an absolute difference equal to the minimum difference found in step 2.

## A solution in Python

```python
from typing import List

def minimumAbsDifference(arr: List[int]) -> List[List[int]]:
    arr.sort()
    min_diff = min(arr[i] - arr[i - 1] for i in range(1, len(arr)))

    result = []
    for i in range(1, len(arr)):
        if arr[i] - arr[i - 1] == min_diff:
            result.append([arr[i - 1], arr[i]])

    return result
```
1. Sort the input array in ascending order.
2. Iterate through the sorted array and find the minimum absolute difference between adjacent elements. This value will be the minimum difference between any two elements in the array.
3. Iterate through the sorted array again and construct the output list by adding pairs of elements with an absolute difference equal to the minimum difference found in step 2.

## A solution in Javascript

```javascript
function minimumAbsDifference(arr) {
    arr.sort((a, b) => a - b);
    let minDiff = Infinity;
    for (let i = 1; i < arr.length; i++) {
        minDiff = Math.min(minDiff, arr[i] - arr[i - 1]);
    }

    const result = [];
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] - arr[i - 1] === minDiff) {
            result.push([arr[i - 1], arr[i]]);
        }
    }

    return result;
}
```
1. Sort the input array in ascending order.
2. Iterate through the sorted array and find the minimum absolute difference between adjacent elements. This value will be the minimum difference between any two elements in the array.
3. Iterate through the sorted array again and construct the output list by adding pairs of elements with an absolute difference equal to the minimum difference found in step 2.